diff --git a/analysis_options.yaml b/analysis_options.yaml index 6680f5c4f6..a733a58a24 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -99,7 +99,7 @@ linter: # - conditional_uri_does_not_exist # not yet tested # - constant_identifier_names # needs an opt-out https://github.com/dart-lang/linter/issues/204 - control_flow_in_finally - # - curly_braces_in_flow_control_structures # not required by flutter style, but developer-facing code should have this on + - curly_braces_in_flow_control_structures - depend_on_referenced_packages - deprecated_consistency # - diagnostic_describe_all_properties # enabled only at the framework level (packages/flutter/lib) diff --git a/dev/benchmarks/complex_layout/lib/main.dart b/dev/benchmarks/complex_layout/lib/main.dart index 5139d9cc70..9e386bafca 100644 --- a/dev/benchmarks/complex_layout/lib/main.dart +++ b/dev/benchmarks/complex_layout/lib/main.dart @@ -113,10 +113,11 @@ class ComplexLayoutState extends State { key: const Key('complex-scroll'), // this key is used by the driver test controller: ScrollController(), // So that the scroll offset can be tracked itemBuilder: (BuildContext context, int index) { - if (index.isEven) + if (index.isEven) { return FancyImageItem(index, key: PageStorageKey(index)); - else + } else { return FancyGalleryItem(index, key: PageStorageKey(index)); + } }, ), ), diff --git a/dev/benchmarks/complex_layout/test/measure_scroll_smoothness.dart b/dev/benchmarks/complex_layout/test/measure_scroll_smoothness.dart index 5ce952c4e4..ef8d24552f 100644 --- a/dev/benchmarks/complex_layout/test/measure_scroll_smoothness.dart +++ b/dev/benchmarks/complex_layout/test/measure_scroll_smoothness.dart @@ -239,8 +239,9 @@ Map scrollSummary( // final double absJerk = (scrollOffset[i-1] + scrollOffset[i+1] - 2*scrollOffset[i]).abs(); absJerkAvg += absJerk; - if (absJerk > 0.5) + if (absJerk > 0.5) { jankyCount += 1; + } } // expect(lostFrame < 0.1 * frameTimestamp.length, true); absJerkAvg /= frameTimestamp.length - lostFrame; diff --git a/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart b/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart index afa169fb1e..0291e084cf 100644 --- a/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart +++ b/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart @@ -18,8 +18,9 @@ void main() { }); tearDownAll(() async { - if (driver != null) + if (driver != null) { driver.close(); + } }); Future testScrollPerf(String listKey, String summaryName) async { diff --git a/dev/benchmarks/complex_layout/test_driver/semantics_perf_test.dart b/dev/benchmarks/complex_layout/test_driver/semantics_perf_test.dart index 491a296f12..9df73ccbda 100644 --- a/dev/benchmarks/complex_layout/test_driver/semantics_perf_test.dart +++ b/dev/benchmarks/complex_layout/test_driver/semantics_perf_test.dart @@ -19,8 +19,9 @@ void main() { }); tearDownAll(() async { - if (driver != null) + if (driver != null) { driver.close(); + } }); test('initial tree creation', () async { @@ -34,8 +35,9 @@ void main() { }); final Iterable? semanticsEvents = timeline.events?.where((TimelineEvent event) => event.name == 'SEMANTICS'); - if (semanticsEvents?.length != 2) + if (semanticsEvents?.length != 2) { fail('Expected exactly two "SEMANTICS" events, got ${semanticsEvents?.length}:\n$semanticsEvents'); + } final Duration semanticsTreeCreation = Duration(microseconds: semanticsEvents!.last.timestampMicros! - semanticsEvents.first.timestampMicros!); final String jsonEncoded = json.encode({'initialSemanticsTreeCreation': semanticsTreeCreation.inMilliseconds}); diff --git a/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart b/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart index a4012d8409..7a24cffbaa 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/stack_size.dart @@ -44,13 +44,16 @@ const int kExitCodeSuccess = 0; final GetStackPointerCallback getStackPointer = () { // Makes sure we are running on an Android arm64 device. - if (!io.Platform.isAndroid) + if (!io.Platform.isAndroid) { throw 'This benchmark test can only be run on Android arm devices.'; + } final io.ProcessResult result = io.Process.runSync('getprop', ['ro.product.cpu.abi']); - if (result.exitCode != 0) + if (result.exitCode != 0) { throw 'Failed to retrieve CPU information.'; - if (!result.stdout.toString().contains('armeabi')) + } + if (!result.stdout.toString().contains('armeabi')) { throw 'This benchmark test can only be run on Android arm devices.'; + } // Creates a block of memory to store the assembly code. final ffi.Pointer region = mmap(ffi.nullptr, kMemorySize, kProtRead | kProtWrite, diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart index 62f848ae55..f9b1ad0fda 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_grid_hover.dart @@ -159,8 +159,9 @@ class _Tester { final Stopwatch stopwatch = Stopwatch()..start(); await gesture.moveTo(location, timeStamp: currentTime); stopwatch.stop(); - if (onDataPoint != null) + if (onDataPoint != null) { onDataPoint(stopwatch.elapsed); + } await _UntilNextFrame.wait(); } diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_mixed_grid_hover.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_mixed_grid_hover.dart index bddc1078eb..16a6c22d2e 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_mixed_grid_hover.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/bench_mouse_region_mixed_grid_hover.dart @@ -181,8 +181,9 @@ class _Tester { final Stopwatch stopwatch = Stopwatch()..start(); await gesture.moveTo(location, timeStamp: currentTime); stopwatch.stop(); - if (onDataPoint != null) + if (onDataPoint != null) { onDataPoint(stopwatch.elapsed); + } await _UntilNextFrame.wait(); } diff --git a/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart b/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart index 836fb6b20d..a543a32686 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart @@ -405,8 +405,9 @@ abstract class WidgetRecorder extends Recorder implements FrameRecorder { if (shouldContinue()) { PlatformDispatcher.instance.scheduleFrame(); } else { - for (final VoidCallback fn in _didStopCallbacks) + for (final VoidCallback fn in _didStopCallbacks) { fn(); + } _runCompleter!.complete(); } } @@ -520,8 +521,9 @@ abstract class WidgetBuildRecorder extends Recorder implements FrameRecorder { showWidget = !showWidget; _hostState._setStateTrampoline(); } else { - for (final VoidCallback fn in _didStopCallbacks) + for (final VoidCallback fn in _didStopCallbacks) { fn(); + } _runCompleter!.complete(); } } diff --git a/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart b/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart index c6d9420abe..0eedaef66b 100644 --- a/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/foundation/change_notifier_bench.dart @@ -39,13 +39,14 @@ void main() { watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; - if (addResult) + if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); + } } } @@ -65,13 +66,14 @@ void main() { watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; - if (addResult) + if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); + } } } @@ -107,13 +109,14 @@ void main() { watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; - if (addResult) + if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); + } } } @@ -156,13 +159,14 @@ void main() { watch.stop(); final int elapsed = watch.elapsedMicroseconds; final double averagePerIteration = elapsed / iteration; - if (addResult) + if (addResult) { printer.addResult( description: '$name ($listenerCount listeners)', value: averagePerIteration * _kScale, unit: 'ns per iteration', name: '$name$listenerCount', ); + } } } diff --git a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart index 576546e188..c64f79bbcd 100644 --- a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart @@ -32,10 +32,12 @@ void main() { watch.start(); for (int i = 0; i < _kNumIters; i += 1) { for (final PointerEvent event in velocityEventData) { - if (event is PointerDownEvent || event is PointerMoveEvent) + if (event is PointerDownEvent || event is PointerMoveEvent) { tracker.addPosition(event.timeStamp, event.position); - if (event is PointerUpEvent) + } + if (event is PointerUpEvent) { tracker.getVelocity(); + } } } watch.stop(); diff --git a/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart b/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart index 5419a90911..da74224438 100644 --- a/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart +++ b/dev/benchmarks/test_apps/stocks/lib/stock_arrow.dart @@ -67,8 +67,9 @@ class StockArrow extends StatelessWidget { } Color _colorForPercentChange(double percentChange) { - if (percentChange > 0) + if (percentChange > 0) { return Colors.green[_colorIndexForPercentChange(percentChange)]!; + } return Colors.red[_colorIndexForPercentChange(percentChange)]!; } diff --git a/dev/benchmarks/test_apps/stocks/lib/stock_home.dart b/dev/benchmarks/test_apps/stocks/lib/stock_home.dart index 197db62964..cc1141f0d7 100644 --- a/dev/benchmarks/test_apps/stocks/lib/stock_home.dart +++ b/dev/benchmarks/test_apps/stocks/lib/stock_home.dart @@ -85,8 +85,9 @@ class StockHomeState extends State { } void _handleStockModeChange(StockMode? value) { - if (widget.updater != null) + if (widget.updater != null) { widget.updater(widget.configuration.copyWith(stockMode: value)); + } } void _handleStockMenu(BuildContext context, _StockMenuItem value) { @@ -239,8 +240,9 @@ class StockHomeState extends State { } Iterable _filterBySearchQuery(Iterable stocks) { - if (_searchQuery.text.isEmpty) + if (_searchQuery.text.isEmpty) { return stocks; + } final RegExp regexp = RegExp(_searchQuery.text, caseSensitive: false); return stocks.where((Stock stock) => stock.symbol.contains(regexp)); } diff --git a/dev/benchmarks/test_apps/stocks/lib/stock_row.dart b/dev/benchmarks/test_apps/stocks/lib/stock_row.dart index 8b94c7283c..fb6b42110a 100644 --- a/dev/benchmarks/test_apps/stocks/lib/stock_row.dart +++ b/dev/benchmarks/test_apps/stocks/lib/stock_row.dart @@ -32,8 +32,9 @@ class StockRow extends StatelessWidget { Widget build(BuildContext context) { final String lastSale = '\$${stock.lastSale.toStringAsFixed(2)}'; String changeInPrice = '${stock.percentChange.toStringAsFixed(2)}%'; - if (stock.percentChange > 0) + if (stock.percentChange > 0) { changeInPrice = '+$changeInPrice'; + } return InkWell( key: ValueKey(stock.symbol), onTap: _getHandler(onPressed), diff --git a/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart b/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart index 1be3d0118b..460ad3a120 100644 --- a/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart +++ b/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart @@ -93,8 +93,9 @@ class StockSettingsState extends State { } void sendUpdates(StockConfiguration value) { - if (widget.updater != null) + if (widget.updater != null) { widget.updater(value); + } } AppBar buildAppBar(BuildContext context) { diff --git a/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart b/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart index 77be8275c4..3291f4d417 100644 --- a/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart +++ b/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart @@ -21,8 +21,9 @@ class _StockSymbolView extends StatelessWidget { assert(stock != null); final String lastSale = '\$${stock.lastSale.toStringAsFixed(2)}'; String changeInPrice = '${stock.percentChange.toStringAsFixed(2)}%'; - if (stock.percentChange > 0) + if (stock.percentChange > 0) { changeInPrice = '+$changeInPrice'; + } final TextStyle headings = Theme.of(context).textTheme.bodyText1!; return Container( diff --git a/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart b/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart index 9bcc5a5799..3a8b8f71ab 100644 --- a/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart +++ b/dev/benchmarks/test_apps/stocks/test/icon_color_test.dart @@ -9,8 +9,9 @@ import 'package:stocks/stock_data.dart' as stock_data; Element? findElementOfExactWidgetTypeGoingDown(Element node, Type targetType) { void walker(Element child) { - if (child.widget.runtimeType == targetType) + if (child.widget.runtimeType == targetType) { throw child; + } child.visitChildElements(walker); } try { diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index b7ff8b649c..9d66ecf742 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -460,12 +460,14 @@ Future verifyDeprecations(String workingDirectory, { int minimumMatches = for (int lineNumber in linesWithDeprecations) { try { final RegExpMatch? startMatch = _deprecationStartPattern.firstMatch(lines[lineNumber]); - if (startMatch == null) + if (startMatch == null) { throw 'Deprecation notice does not match required pattern.'; + } final String indent = startMatch.namedGroup('indent')!; lineNumber += 1; - if (lineNumber >= lines.length) + if (lineNumber >= lines.length) { throw 'Incomplete deprecation notice.'; + } RegExpMatch? versionMatch; String? message; do { @@ -477,17 +479,20 @@ Future verifyDeprecations(String workingDirectory, { int minimumMatches = } throw 'Deprecation notice does not match required pattern.$possibleReason'; } - if (!lines[lineNumber].startsWith("$indent '")) + if (!lines[lineNumber].startsWith("$indent '")) { throw 'Unexpected deprecation notice indent.'; + } if (message == null) { message = messageMatch.namedGroup('message'); final String firstChar = String.fromCharCode(message!.runes.first); - if (firstChar.toUpperCase() != firstChar) + if (firstChar.toUpperCase() != firstChar) { throw 'Deprecation notice should be a grammatically correct sentence and start with a capital letter; see style guide: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo'; + } } lineNumber += 1; - if (lineNumber >= lines.length) + if (lineNumber >= lines.length) { throw 'Incomplete deprecation notice.'; + } versionMatch = _deprecationVersionPattern.firstMatch(lines[lineNumber]); } while (versionMatch == null); final int major = int.parse(versionMatch.namedGroup('major')!); @@ -497,20 +502,26 @@ Future verifyDeprecations(String workingDirectory, { int minimumMatches = // There was a beta release that was mistakenly labeled 3.1.0 without a build. final bool specialBeta = major == 3 && minor == 1 && patch == 0; if (!specialBeta && (major > 1 || (major == 1 && minor >= 20))) { - if (!hasBuild) + if (!hasBuild) { throw 'Deprecation notice does not accurately indicate a beta branch version number; please see https://flutter.dev/docs/development/tools/sdk/releases to find the latest beta build version number.'; + } } - if (!message.endsWith('.') && !message.endsWith('!') && !message.endsWith('?')) + if (!message.endsWith('.') && !message.endsWith('!') && !message.endsWith('?')) { throw 'Deprecation notice should be a grammatically correct sentence and end with a period.'; - if (!lines[lineNumber].startsWith("$indent '")) + } + if (!lines[lineNumber].startsWith("$indent '")) { throw 'Unexpected deprecation notice indent.'; + } lineNumber += 1; - if (lineNumber >= lines.length) + if (lineNumber >= lines.length) { throw 'Incomplete deprecation notice.'; - if (!lines[lineNumber].contains(_deprecationEndPattern)) + } + if (!lines[lineNumber].contains(_deprecationEndPattern)) { throw 'End of deprecation notice does not match required pattern.'; - if (!lines[lineNumber].startsWith('$indent)')) + } + if (!lines[lineNumber].startsWith('$indent)')) { throw 'Unexpected deprecation notice indent.'; + } } catch (error) { errors.add('${file.path}:${lineNumber + 1}: $error'); } @@ -569,10 +580,12 @@ Future _verifyNoMissingLicenseForExtension( final List errors = []; await for (final File file in _allFiles(workingDirectory, extension, minimumMatches: minimumMatches)) { final String contents = file.readAsStringSync().replaceAll('\r\n', '\n'); - if (contents.isEmpty) + if (contents.isEmpty) { continue; // let's not go down the /bin/true rabbit hole - if (!contents.startsWith(RegExp(header + licensePattern))) + } + if (!contents.startsWith(RegExp(header + licensePattern))) { errors.add(file.path); + } } // Fail if any errors if (errors.isNotEmpty) { @@ -679,8 +692,9 @@ Future verifyNoTestImports(String workingDirectory) async { for (final File file in dartFiles) { for (final String line in file.readAsLinesSync()) { final Match? match = _testImportPattern.firstMatch(line); - if (match != null && !_exemptTestImports.contains(match.group(2))) + if (match != null && !_exemptTestImports.contains(match.group(2))) { errors.add(file.path); + } } } // Fail if any errors @@ -733,8 +747,9 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { for (final String key in dependencyMap.keys) { for (final String dependency in dependencyMap[key]!) { - if (dependencyMap[dependency] != null) + if (dependencyMap[dependency] != null) { continue; + } // Sanity check before performing _deepSearch, to ensure there's no rogue // dependencies. final String validFilenames = dependencyMap.keys.map((String name) => '$name.dart').join(', '); @@ -931,8 +946,9 @@ Future verifyNoRuntimeTypeInToString(String workingDirectory) async { } } } - if (problems.isNotEmpty) + if (problems.isNotEmpty) { exitWithError(problems); + } } Future verifyNoTrailingSpaces(String workingDirectory, { int minimumMatches = 4000 }) async { @@ -956,11 +972,13 @@ Future verifyNoTrailingSpaces(String workingDirectory, { int minimumMatche problems.add('${file.path}:${index + 1}: trailing U+0009 tab character'); } } - if (lines.isNotEmpty && lines.last == '') + if (lines.isNotEmpty && lines.last == '') { problems.add('${file.path}:${lines.length}: trailing blank line'); + } } - if (problems.isNotEmpty) + if (problems.isNotEmpty) { exitWithError(problems); + } } String _bullets(String value) => ' * $value'; @@ -984,8 +1002,9 @@ Future verifyIssueLinks(String workingDirectory) async { final Set suggestions = {}; final List files = await _gitFiles(workingDirectory); for (final File file in files) { - if (path.basename(file.path).endsWith('_test.dart') || path.basename(file.path) == 'analyze.dart') + if (path.basename(file.path).endsWith('_test.dart') || path.basename(file.path) == 'analyze.dart') { continue; // Skip tests, they're not public-facing. + } final Uint8List bytes = file.readAsBytesSync(); // We allow invalid UTF-8 here so that binaries don't trip us up. // There's a separate test in this file that verifies that all text @@ -1087,8 +1106,9 @@ class Hash256 { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is Hash256 && other.a == a && other.b == b @@ -1481,8 +1501,9 @@ Future verifyNoBinaries(String workingDirectory, { Set? legacyBin utf8.decode(bytes); } on FormatException catch (error) { final Digest digest = sha256.convert(bytes); - if (!legacyBinaries.contains(Hash256.fromDigest(digest))) + if (!legacyBinaries.contains(Hash256.fromDigest(digest))) { problems.add('${file.path}:${error.offset}: file is not valid UTF-8'); + } } } if (problems.isNotEmpty) { @@ -1506,11 +1527,13 @@ Future verifyNoBinaries(String workingDirectory, { Set? legacyBin bool _listEquals(List a, List b) { assert(a != null); assert(b != null); - if (a.length != b.length) + if (a.length != b.length) { return false; + } for (int index = 0; index < a.length; index += 1) { - if (a[index] != b[index]) + if (a[index] != b[index]) { return false; + } } return true; } @@ -1550,38 +1573,51 @@ Stream _allFiles(String workingDirectory, String? extension, { required in while (pending.isNotEmpty) { final FileSystemEntity entity = pending.first; pending.remove(entity); - if (path.extension(entity.path) == '.tmpl') + if (path.extension(entity.path) == '.tmpl') { continue; + } if (entity is File) { - if (!gitFileNamesSet.contains(path.canonicalize(entity.absolute.path))) + if (!gitFileNamesSet.contains(path.canonicalize(entity.absolute.path))) { continue; - if (_isGeneratedPluginRegistrant(entity)) + } + if (_isGeneratedPluginRegistrant(entity)) { continue; - if (path.basename(entity.path) == 'flutter_export_environment.sh') + } + if (path.basename(entity.path) == 'flutter_export_environment.sh') { continue; - if (path.basename(entity.path) == 'gradlew.bat') + } + if (path.basename(entity.path) == 'gradlew.bat') { continue; - if (path.basename(entity.path) == '.DS_Store') + } + if (path.basename(entity.path) == '.DS_Store') { continue; + } if (extension == null || path.extension(entity.path) == '.$extension') { matches += 1; yield entity; } } else if (entity is Directory) { - if (File(path.join(entity.path, '.dartignore')).existsSync()) + if (File(path.join(entity.path, '.dartignore')).existsSync()) { continue; - if (path.basename(entity.path) == '.git') + } + if (path.basename(entity.path) == '.git') { continue; - if (path.basename(entity.path) == '.idea') + } + if (path.basename(entity.path) == '.idea') { continue; - if (path.basename(entity.path) == '.gradle') + } + if (path.basename(entity.path) == '.gradle') { continue; - if (path.basename(entity.path) == '.dart_tool') + } + if (path.basename(entity.path) == '.dart_tool') { continue; - if (path.basename(entity.path) == '.idea') + } + if (path.basename(entity.path) == '.idea') { continue; - if (path.basename(entity.path) == 'build') + } + if (path.basename(entity.path) == 'build') { continue; + } pending.addAll(entity.listSync()); } } @@ -1830,8 +1866,9 @@ Future> _findFlutterDependencies(String srcPath, List errors final Set result = {}; for (final String line in file.readAsLinesSync()) { Match? match = _importPattern.firstMatch(line); - if (match != null) + if (match != null) { result.add(match.group(2)!); + } if (checkForMeta) { match = _importMetaPattern.firstMatch(line); if (match != null) { @@ -1852,14 +1889,17 @@ Future> _findFlutterDependencies(String srcPath, List errors } List? _deepSearch(Map> map, T start, [ Set? seen ]) { - if (map[start] == null) + if (map[start] == null) { return null; // We catch these separately. + } for (final T key in map[start]!) { - if (key == start) + if (key == start) { continue; // we catch these separately - if (seen != null && seen.contains(key)) + } + if (seen != null && seen.contains(key)) { return [start, key]; + } final List? result = _deepSearch( map, key, @@ -1874,8 +1914,9 @@ List? _deepSearch(Map> map, T start, [ Set? seen ]) { // For example a->b->a, rather than c->a->b->a. // Since we visit every node, we know the shortest chains are those // that start and end on the loop. - if (result.first == result.last) + if (result.first == result.last) { return result; + } } } return null; diff --git a/dev/bots/analyze_snippet_code.dart b/dev/bots/analyze_snippet_code.dart index 7c604c6b4e..90b4b742d6 100644 --- a/dev/bots/analyze_snippet_code.dart +++ b/dev/bots/analyze_snippet_code.dart @@ -396,12 +396,14 @@ class _SnippetChecker { } } } - if (!silent) + if (!silent) { print('Found ${sections.length} snippet code blocks'); + } for (final _Section section in sections) { final String path = _writeSection(section).path; - if (sectionMap != null) + if (sectionMap != null) { sectionMap[path] = section; + } } } @@ -448,8 +450,9 @@ class _SnippetChecker { /// Invokes the analyzer on the given [directory] and returns the stdout. int _runAnalyzer(Directory directory, {bool silent = true, required List output}) { - if (!silent) + if (!silent) { print('Starting analysis of code snippets.'); + } _createConfigurationFiles(directory); final ProcessResult result = Process.runSync( _flutter, @@ -598,8 +601,9 @@ class _SnippetChecker { exitCode = 0; } if (exitCode == 0) { - if (!silent) + if (!silent) { print('No analysis errors in snippets!'); + } assert(analysisErrors.isEmpty); } return _AnalysisResult(exitCode, analysisErrors); @@ -633,17 +637,19 @@ class _SnippetChecker { // Each section of the dart code that is either split by a blank line, or with '// ...' is // treated as a separate code block. if (block[index] == '' || block[index] == '// ...') { - if (subline == null) + if (subline == null) { throw _SnippetCheckerException('${_Line(filename: line.filename, line: line.line + index, indent: line.indent)}: ' 'Unexpected blank line or "// ..." line near start of subblock in snippet code.'); + } subblocks += 1; subsections.add(_processBlock(subline, buffer)); buffer.clear(); assert(buffer.isEmpty); subline = null; } else if (block[index].startsWith('// ')) { - if (buffer.length > 1) // don't include leading comments + if (buffer.length > 1) { buffer.add('/${block[index]}'); // so that it doesn't start with "// " and get caught in this again + } } else { subline ??= _Line( code: block[index], diff --git a/dev/bots/flutter_compact_formatter.dart b/dev/bots/flutter_compact_formatter.dart index 9bb08fd0c0..8504f54151 100644 --- a/dev/bots/flutter_compact_formatter.dart +++ b/dev/bots/flutter_compact_formatter.dart @@ -133,10 +133,12 @@ class FlutterCompactFormatter { originalResult.errorMessage = error; originalResult.stackTrace = stackTrace; } else { - if (error != null) + if (error != null) { stderr.writeln(error); - if (stackTrace != null) + } + if (stackTrace != null) { stderr.writeln(stackTrace); + } } break; case 'print': diff --git a/dev/bots/test.dart b/dev/bots/test.dart index ae60fe1b9b..cbb1bf6ed4 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -39,12 +39,15 @@ final String engineVersionFile = path.join(flutterRoot, 'bin', 'internal', 'engi final String flutterPluginsVersionFile = path.join(flutterRoot, 'bin', 'internal', 'flutter_plugins.version'); String get platformFolderName { - if (Platform.isWindows) + if (Platform.isWindows) { return 'windows-x64'; - if (Platform.isMacOS) + } + if (Platform.isMacOS) { return 'darwin-x64'; - if (Platform.isLinux) + } + if (Platform.isLinux) { return 'linux-x64'; + } throw UnsupportedError('The platform ${Platform.operatingSystem} is not supported by this script.'); } final String flutterTester = path.join(flutterRoot, 'bin', 'cache', 'artifacts', 'engine', platformFolderName, 'flutter_tester$exe'); @@ -187,8 +190,9 @@ Future main(List args) async { } } flutterTestArgs.removeWhere((String arg) => removeArgs.contains(arg)); - if (Platform.environment.containsKey(CIRRUS_TASK_NAME)) + if (Platform.environment.containsKey(CIRRUS_TASK_NAME)) { print('Running task: ${Platform.environment[CIRRUS_TASK_NAME]}'); + } print('═' * 80); await selectShard({ 'add_to_app_life_cycle_tests': _runAddToAppLifeCycleTests, @@ -327,8 +331,9 @@ Future _runTestHarnessTests() async { // Verify that we correctly generated the version file. final String? versionError = await verifyVersion(File(path.join(flutterRoot, 'version'))); - if (versionError != null) + if (versionError != null) { exitWithError([versionError]); + } } final String _toolsPath = path.join(flutterRoot, 'packages', 'flutter_tools'); @@ -1748,8 +1753,9 @@ Future _runFlutterTest(String workingDirectory, { ]; final bool shouldProcessOutput = useFlutterTestFormatter && !expectFailure && !options.contains('--coverage'); - if (shouldProcessOutput) + if (shouldProcessOutput) { args.add('--machine'); + } if (script != null) { final String fullScriptPath = path.join(workingDirectory, script); @@ -1757,8 +1763,9 @@ Future _runFlutterTest(String workingDirectory, { print('${red}Could not find test$reset: $green$fullScriptPath$reset'); print('Working directory: $cyan$workingDirectory$reset'); print('Script: $green$script$reset'); - if (!printOutput) + if (!printOutput) { print('This is one of the tests that does not normally print output.'); + } exit(1); } args.add(script); @@ -1782,8 +1789,9 @@ Future _runFlutterTest(String workingDirectory, { if (outputChecker != null) { final String? message = outputChecker(result); - if (message != null) + if (message != null) { exitWithError([message]); + } } return; } @@ -1862,12 +1870,15 @@ Future verifyVersion(File file) async { final RegExp pattern = RegExp( r'^(\d+)\.(\d+)\.(\d+)((-\d+\.\d+)?\.pre(\.\d+)?)?$'); final String version = await file.readAsString(); - if (!file.existsSync()) + if (!file.existsSync()) { return 'The version logic failed to create the Flutter version file.'; - if (version == '0.0.0-unknown') + } + if (version == '0.0.0-unknown') { return 'The version logic failed to determine the Flutter version.'; - if (!version.contains(pattern)) + } + if (!version.contains(pattern)) { return 'The version logic generated an invalid version string: "$version".'; + } return null; } diff --git a/dev/bots/utils.dart b/dev/bots/utils.dart index 0311fc94c7..e174431f14 100644 --- a/dev/bots/utils.dart +++ b/dev/bots/utils.dart @@ -59,8 +59,9 @@ String get clock { String prettyPrintDuration(Duration duration) { String result = ''; final int minutes = duration.inMinutes; - if (minutes > 0) + if (minutes > 0) { result += '${minutes}min '; + } final int seconds = duration.inSeconds - minutes * 60; final int milliseconds = duration.inMilliseconds - (seconds * 1000 + minutes * 60 * 1000); result += '$seconds.${milliseconds.toString().padLeft(3, "0")}s'; diff --git a/dev/conductor/core/analysis_options.yaml b/dev/conductor/core/analysis_options.yaml index 2d24879e53..27f5b1d21f 100644 --- a/dev/conductor/core/analysis_options.yaml +++ b/dev/conductor/core/analysis_options.yaml @@ -8,6 +8,5 @@ analyzer: linter: rules: avoid_catches_without_on_clauses: true - curly_braces_in_flow_control_structures: true prefer_relative_imports: true unawaited_futures: true diff --git a/dev/customer_testing/lib/customer_test.dart b/dev/customer_testing/lib/customer_test.dart index 067fdcb4e1..b56b300444 100644 --- a/dev/customer_testing/lib/customer_test.dart +++ b/dev/customer_testing/lib/customer_test.dart @@ -31,42 +31,54 @@ class CustomerTest { test.add(line.substring(5)); } else if (line.startsWith('test.windows=')) { hasTests = true; - if (Platform.isWindows) + if (Platform.isWindows) { test.add(line.substring(13)); + } } else if (line.startsWith('test.macos=')) { hasTests = true; - if (Platform.isMacOS) + if (Platform.isMacOS) { test.add(line.substring(11)); + } } else if (line.startsWith('test.linux=')) { hasTests = true; - if (Platform.isLinux) + if (Platform.isLinux) { test.add(line.substring(11)); + } } else if (line.startsWith('test.posix=')) { hasTests = true; - if (Platform.isLinux || Platform.isMacOS) + if (Platform.isLinux || Platform.isMacOS) { test.add(line.substring(11)); + } } else { throw FormatException('${errorPrefix}Unexpected directive:\n$line'); } } - if (contacts.isEmpty) + if (contacts.isEmpty) { throw FormatException('${errorPrefix}No contacts specified. At least one contact e-mail address must be specified.'); - for (final String email in contacts) { - if (!email.contains(_email) || email.endsWith('@example.com')) - throw FormatException('${errorPrefix}The following e-mail address appears to be an invalid e-mail address: $email'); } - if (fetch.isEmpty) + for (final String email in contacts) { + if (!email.contains(_email) || email.endsWith('@example.com')) { + throw FormatException('${errorPrefix}The following e-mail address appears to be an invalid e-mail address: $email'); + } + } + if (fetch.isEmpty) { throw FormatException('${errorPrefix}No "fetch" directives specified. Two lines are expected: "git clone https://github.com/USERNAME/REPOSITORY.git tests" and "git -C tests checkout HASH".'); - if (fetch.length < 2) + } + if (fetch.length < 2) { throw FormatException('${errorPrefix}Only one "fetch" directive specified. Two lines are expected: "git clone https://github.com/USERNAME/REPOSITORY.git tests" and "git -C tests checkout HASH".'); - if (!fetch[0].contains(_fetch1)) + } + if (!fetch[0].contains(_fetch1)) { throw FormatException('${errorPrefix}First "fetch" directive does not match expected pattern (expected "git clone https://github.com/USERNAME/REPOSITORY.git tests").'); - if (!fetch[1].contains(_fetch2)) + } + if (!fetch[1].contains(_fetch2)) { throw FormatException('${errorPrefix}Second "fetch" directive does not match expected pattern (expected "git -C tests checkout HASH").'); - if (update.isEmpty) + } + if (update.isEmpty) { throw FormatException('${errorPrefix}No "update" directives specified. At least one directory must be specified. (It can be "." to just upgrade the root of the repository.)'); - if (!hasTests) + } + if (!hasTests) { throw FormatException('${errorPrefix}No "test" directives specified. At least one command must be specified to run tests.'); + } return CustomerTest._( List.unmodifiable(contacts), List.unmodifiable(fetch), diff --git a/dev/customer_testing/lib/runner.dart b/dev/customer_testing/lib/runner.dart index 58e00ca26d..f453483d56 100644 --- a/dev/customer_testing/lib/runner.dart +++ b/dev/customer_testing/lib/runner.dart @@ -17,8 +17,9 @@ Future runTests({ int shardIndex = 0, required List files, }) async { - if (verbose) + if (verbose) { print('Starting run_tests.dart...'); + } // Best attempt at evenly splitting tests among the shards final List shardedFiles = []; @@ -46,18 +47,21 @@ Future runTests({ } else { print('Tests:'); } - for (final File file in shardedFiles) + for (final File file in shardedFiles) { print(file.path); + } } print(''); for (final File file in shardedFiles) { - if (verbose) + if (verbose) { print('Processing ${file.path}...'); + } void printHeader() { - if (!verbose) + if (!verbose) { print('Processing ${file.path}...'); + } } void failure(String message) { @@ -82,8 +86,9 @@ Future runTests({ bool success = true; final Directory checkout = Directory.systemTemp.createTempSync('flutter_customer_testing.${path.basenameWithoutExtension(file.path)}.'); - if (verbose) + if (verbose) { print('Created temporary directory: ${checkout.path}'); + } try { assert(instructions.fetch.isNotEmpty); for (final String fetchCommand in instructions.fetch) { @@ -105,8 +110,9 @@ Future runTests({ final Directory customerRepo = Directory(path.join(checkout.path, 'tests')); for (final Directory updateDirectory in instructions.update) { final Directory resolvedUpdateDirectory = Directory(path.join(customerRepo.path, updateDirectory.path)); - if (verbose) + if (verbose) { print('Updating code in ${resolvedUpdateDirectory.path}...'); + } if (!File(path.join(resolvedUpdateDirectory.path, 'pubspec.yaml')).existsSync()) { failure('The directory ${updateDirectory.path}, which was specified as an update directory, does not contain a "pubspec.yaml" file.'); success = false; @@ -124,11 +130,13 @@ Future runTests({ } } if (success) { - if (verbose) + if (verbose) { print('Running tests...'); + } for (int iteration = 0; iteration < repeat; iteration += 1) { - if (verbose && repeat > 1) + if (verbose && repeat > 1) { print('Round ${iteration + 1} of $repeat.'); + } for (final String testCommand in instructions.tests) { testCount += 1; success = await shell(testCommand, customerRepo, verbose: verbose, failedCallback: printHeader); @@ -138,13 +146,15 @@ Future runTests({ } } } - if (verbose && success) + if (verbose && success) { print('Tests finished.'); + } } } } finally { - if (verbose) + if (verbose) { print('Deleting temporary directory...'); + } try { checkout.deleteSync(recursive: true); } on FileSystemException { @@ -155,8 +165,9 @@ Future runTests({ final String s = instructions.contacts.length == 1 ? '' : 's'; print('Contact$s: ${instructions.contacts.join(", ")}'); } - if (verbose || !success) + if (verbose || !success) { print(''); + } } if (failures > 0) { final String s = failures == 1 ? '' : 's'; @@ -170,8 +181,9 @@ Future runTests({ final RegExp _spaces = RegExp(r' +'); Future shell(String command, Directory directory, { bool verbose = false, bool silentFailure = false, void Function()? failedCallback }) async { - if (verbose) + if (verbose) { print('>> $command'); + } Process process; if (Platform.isWindows) { process = await Process.start('CMD.EXE', ['/S', '/C', command], workingDirectory: directory.path); @@ -183,11 +195,13 @@ Future shell(String command, Directory directory, { bool verbose = false, utf8.decoder.bind(process.stdout).transform(const LineSplitter()).listen(verbose ? printLog : output.add); utf8.decoder.bind(process.stderr).transform(const LineSplitter()).listen(verbose ? printLog : output.add); final bool success = await process.exitCode == 0; - if (success || silentFailure) + if (success || silentFailure) { return success; + } if (!verbose) { - if (failedCallback != null) + if (failedCallback != null) { failedCallback(); + } print('>> $command'); output.forEach(printLog); } diff --git a/dev/customer_testing/run_tests.dart b/dev/customer_testing/run_tests.dart index a0c90bf7df..c3c5f3482b 100644 --- a/dev/customer_testing/run_tests.dart +++ b/dev/customer_testing/run_tests.dart @@ -92,8 +92,9 @@ Future run(List arguments) async { if (help || repeat == null || files.isEmpty || numberShards == null || numberShards <= 0 || shardIndex == null || shardIndex < 0) { printHelp(); if (verbose) { - if (repeat == null) + if (repeat == null) { print('Error: Could not parse repeat count ("${parsedArguments['repeat']}")'); + } if (numberShards == null) { print('Error: Could not parse shards count ("${parsedArguments['shards']}")'); } else if (numberShards < 1) { @@ -121,8 +122,9 @@ Future run(List arguments) async { return false; } - if (files.length < numberShards) + if (files.length < numberShards) { print('Warning: There are more shards than tests. Some shards will not run any tests.'); + } return runTests( repeat: repeat, diff --git a/dev/devicelab/bin/tasks/android_engine_dependency_proxy_test.dart b/dev/devicelab/bin/tasks/android_engine_dependency_proxy_test.dart index 314854d0d0..f768e94813 100644 --- a/dev/devicelab/bin/tasks/android_engine_dependency_proxy_test.dart +++ b/dev/devicelab/bin/tasks/android_engine_dependency_proxy_test.dart @@ -19,8 +19,9 @@ Future main() async { section('Find Java'); final String? javaHome = await findJavaHome(); - if (javaHome == null) + if (javaHome == null) { return TaskResult.failure('Could not find Java'); + } print('\nUsing JAVA_HOME=$javaHome'); section('Create project'); diff --git a/dev/devicelab/bin/tasks/build_aar_module_test.dart b/dev/devicelab/bin/tasks/build_aar_module_test.dart index dfafb1041b..1f5850c41c 100644 --- a/dev/devicelab/bin/tasks/build_aar_module_test.dart +++ b/dev/devicelab/bin/tasks/build_aar_module_test.dart @@ -19,8 +19,9 @@ Future main() async { section('Find Java'); final String? javaHome = await findJavaHome(); - if (javaHome == null) + if (javaHome == null) { return TaskResult.failure('Could not find Java'); + } print('\nUsing JAVA_HOME=$javaHome'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.'); diff --git a/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart b/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart index d14c90e3c6..2063b5f9f5 100644 --- a/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart +++ b/dev/devicelab/bin/tasks/flutter_gallery__back_button_memory.dart @@ -42,8 +42,9 @@ class BackButtonMemoryTest extends MemoryTest { prepareForNextMessage('READY'); final String output = await device!.shellEval('am', ['start', '-n', '$packageName/$activityName']); print('adb shell am start: $output'); - if (output.contains('Error')) + if (output.contains('Error')) { fail('unable to launch activity'); + } await receivedNextMessage; // Wait for the Flutter app to settle (e.g. run GCs). diff --git a/dev/devicelab/bin/tasks/flutter_test_performance.dart b/dev/devicelab/bin/tasks/flutter_test_performance.dart index 0bbee03c56..4c1a720107 100644 --- a/dev/devicelab/bin/tasks/flutter_test_performance.dart +++ b/dev/devicelab/bin/tasks/flutter_test_performance.dart @@ -90,12 +90,15 @@ Future runTest({bool coverage = false, bool noPub = false}) async { }); final int result = await analysis.exitCode; clock.stop(); - if (result != 0) + if (result != 0) { throw Exception('flutter test failed with exit code $result'); - if (badLines > 0) + } + if (badLines > 0) { throw Exception('flutter test rendered unexpected output ($badLines bad lines)'); - if (step != TestStep.testPassed) + } + if (step != TestStep.testPassed) { throw Exception('flutter test did not finish (only reached step $step)'); + } print('elapsed time: ${clock.elapsedMilliseconds}ms'); return clock.elapsedMilliseconds; } diff --git a/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart b/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart index 459b039ab7..d791ae8041 100644 --- a/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart +++ b/dev/devicelab/bin/tasks/gradle_plugin_light_apk_test.dart @@ -258,19 +258,22 @@ Future main() async { ]); }); - if (result.exitCode == 0) + if (result.exitCode == 0) { throw failure( 'Gradle did not exit with error as expected', result); + } String output = '${result.stdout}\n${result.stderr}'; if (output.contains('GradleException') || output.contains('Failed to notify') || - output.contains('at org.gradle')) + output.contains('at org.gradle')) { throw failure( 'Gradle output should not contain stacktrace', result); - if (!output.contains('Build failed')) + } + if (!output.contains('Build failed')) { throw failure( 'Gradle output should contain a readable error message', result); + } section('flutter build apk on build script with error'); await project.introduceError(); @@ -280,18 +283,21 @@ Future main() async { '--release', ]); }); - if (result.exitCode == 0) + if (result.exitCode == 0) { throw failure( 'flutter build apk should fail when Gradle does', result); + } output = '${result.stdout}\n${result.stderr}'; - if (!output.contains('Build failed')) + if (!output.contains('Build failed')) { throw failure( 'flutter build apk output should contain a readable Gradle error message', result); - if (hasMultipleOccurrences(output, 'Build failed')) + } + if (hasMultipleOccurrences(output, 'Build failed')) { throw failure( 'flutter build apk should not invoke Gradle repeatedly on error', result); + } }); await runProjectTest((FlutterProject project) async { @@ -303,12 +309,14 @@ Future main() async { '--release', ]); }); - if (result.exitCode == 0) + if (result.exitCode == 0) { throw failure( 'Gradle did not exit with error as expected', result); + } final String output = '${result.stdout}\n${result.stderr}'; - if (!output.contains('No file or variants found for asset: lib/gallery/example_code.dart.')) + if (!output.contains('No file or variants found for asset: lib/gallery/example_code.dart.')) { throw failure(output, result); + } }); return TaskResult.success(null); diff --git a/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart b/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart index 203f32697f..cf037565ac 100644 --- a/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart +++ b/dev/devicelab/bin/tasks/module_custom_host_app_name_test.dart @@ -23,8 +23,9 @@ Future main() async { section('Find Java'); final String? javaHome = await findJavaHome(); - if (javaHome == null) + if (javaHome == null) { return TaskResult.failure('Could not find Java'); + } print('\nUsing JAVA_HOME=$javaHome'); section('Create Flutter module project'); diff --git a/dev/devicelab/bin/tasks/module_test.dart b/dev/devicelab/bin/tasks/module_test.dart index 8ef1c54574..328d5de310 100644 --- a/dev/devicelab/bin/tasks/module_test.dart +++ b/dev/devicelab/bin/tasks/module_test.dart @@ -26,8 +26,9 @@ Future main() async { section('Find Java'); final String? javaHome = await findJavaHome(); - if (javaHome == null) + if (javaHome == null) { return TaskResult.failure('Could not find Java'); + } print('\nUsing JAVA_HOME=$javaHome'); section('Create Flutter module project'); diff --git a/dev/devicelab/bin/tasks/routing_test.dart b/dev/devicelab/bin/tasks/routing_test.dart index 3f55507af4..cbf0e46666 100644 --- a/dev/devicelab/bin/tasks/routing_test.dart +++ b/dev/devicelab/bin/tasks/routing_test.dart @@ -66,8 +66,9 @@ void main() { }); unawaited(run.exitCode.then((int exitCode) { ok = false; })); await Future.any(>[ ready.future, run.exitCode ]); - if (!ok) + if (!ok) { throw 'Failed to run test app.'; + } print('drive: starting...'); final Process drive = await startProcess( path.join(flutterDirectory.path, 'bin', 'flutter'), @@ -90,11 +91,13 @@ void main() { await flutter('install', options: [ '--uninstall-only', ]); - if (result != 0) + if (result != 0) { throw 'Failed to drive test app (exit code $result).'; + } result = await run.exitCode; - if (result != 0) + if (result != 0) { throw 'Received unexpected exit code $result from run process.'; + } }); return TaskResult.success(null); }); diff --git a/dev/devicelab/bin/tasks/service_extensions_test.dart b/dev/devicelab/bin/tasks/service_extensions_test.dart index a130cd7f35..caf51a414f 100644 --- a/dev/devicelab/bin/tasks/service_extensions_test.dart +++ b/dev/devicelab/bin/tasks/service_extensions_test.dart @@ -52,8 +52,9 @@ void main() { }); unawaited(run.exitCode.then((int exitCode) { ok = false; })); await Future.any(>[ ready.future, run.exitCode ]); - if (!ok) + if (!ok) { throw 'Failed to run test app.'; + } final VmService client = await vmServiceConnectUri('ws://localhost:$vmServicePort/ws'); final VM vm = await client.getVM(); @@ -114,14 +115,16 @@ void main() { run.stdin.write('q'); final int result = await run.exitCode; - if (result != 0) + if (result != 0) { throw 'Received unexpected exit code $result from run process.'; + } }); return TaskResult.success(null); }); } void expect(bool value) { - if (!value) + if (!value) { throw 'failed assertion in service extensions test'; + } } diff --git a/dev/devicelab/bin/tasks/smoke_test_device.dart b/dev/devicelab/bin/tasks/smoke_test_device.dart index 61733344fd..e5967ebadd 100644 --- a/dev/devicelab/bin/tasks/smoke_test_device.dart +++ b/dev/devicelab/bin/tasks/smoke_test_device.dart @@ -11,7 +11,7 @@ Future main() async { deviceOperatingSystem = DeviceOperatingSystem.fake; await task(() async { final Device device = await devices.workingDevice; - if (device.deviceId == 'FAKE_SUCCESS') + if (device.deviceId == 'FAKE_SUCCESS') { return TaskResult.success({ 'metric1': 42, 'metric2': 123, @@ -20,7 +20,8 @@ Future main() async { 'metric1', 'metric2', ]); - else + } else { return TaskResult.failure('Failed'); + } }); } diff --git a/dev/devicelab/bin/tasks/technical_debt__cost.dart b/dev/devicelab/bin/tasks/technical_debt__cost.dart index 34fe474895..ff113b32d6 100644 --- a/dev/devicelab/bin/tasks/technical_debt__cost.dart +++ b/dev/devicelab/bin/tasks/technical_debt__cost.dart @@ -36,35 +36,46 @@ final RegExp dartVersionPattern = RegExp(r'// *@dart *= *(\d+).(\d+)'); final Version firstNullSafeDartVersion = Version(2, 12, 0); Future findCostsForFile(File file) async { - if (path.extension(file.path) == '.py') + if (path.extension(file.path) == '.py') { return pythonCost; + } if (path.extension(file.path) != '.dart' && path.extension(file.path) != '.yaml' && - path.extension(file.path) != '.sh') + path.extension(file.path) != '.sh') { return 0.0; + } final bool isTest = file.path.endsWith('_test.dart'); final bool isDart = file.path.endsWith('.dart'); double total = 0.0; for (final String line in await file.readAsLines()) { - if (line.contains(todoPattern)) + if (line.contains(todoPattern)) { total += todoCost; - if (line.contains(ignorePattern)) + } + if (line.contains(ignorePattern)) { total += ignoreCost; - if (line.contains(ignoreForFilePattern)) + } + if (line.contains(ignoreForFilePattern)) { total += ignoreForFileCost; - if (!isTest && line.contains(asDynamicPattern)) + } + if (!isTest && line.contains(asDynamicPattern)) { total += asDynamicCost; - if (line.contains(deprecationPattern)) + } + if (line.contains(deprecationPattern)) { total += deprecationCost; - if (line.contains(legacyDeprecationPattern)) + } + if (line.contains(legacyDeprecationPattern)) { total += legacyDeprecationCost; - if (isTest && line.contains('skip:') && !line.contains('[intended]')) + } + if (isTest && line.contains('skip:') && !line.contains('[intended]')) { total += skipCost; - if (isDart && isOptingOutOfNullSafety(line)) + } + if (isDart && isOptingOutOfNullSafety(line)) { total += fileNullSafetyMigrationCost; + } } - if (path.basename(file.path) == 'pubspec.yaml' && !packageIsNullSafe(file)) + if (path.basename(file.path) == 'pubspec.yaml' && !packageIsNullSafe(file)) { total += packageNullSafetyMigrationCost; + } return total; } @@ -89,12 +100,14 @@ bool packageIsNullSafe(File file) { } Future findGlobalsForFile(File file) async { - if (path.extension(file.path) != '.dart') + if (path.extension(file.path) != '.dart') { return 0; + } int total = 0; for (final String line in await file.readAsLines()) { - if (line.contains(globalsPattern)) + if (line.contains(globalsPattern)) { total += 1; + } } return total; } @@ -106,11 +119,13 @@ Future findCostsForRepo() async { workingDirectory: flutterDirectory.path, ); double total = 0.0; - await for (final String entry in git.stdout.transform(utf8.decoder).transform(const LineSplitter())) + await for (final String entry in git.stdout.transform(utf8.decoder).transform(const LineSplitter())) { total += await findCostsForFile(File(path.join(flutterDirectory.path, entry))); + } final int gitExitCode = await git.exitCode; - if (gitExitCode != 0) + if (gitExitCode != 0) { throw Exception('git exit with unexpected error code $gitExitCode'); + } return total; } @@ -121,11 +136,13 @@ Future findGlobalsForTool() async { workingDirectory: flutterDirectory.path, ); int total = 0; - await for (final String entry in git.stdout.transform(utf8.decoder).transform(const LineSplitter())) + await for (final String entry in git.stdout.transform(utf8.decoder).transform(const LineSplitter())) { total += await findGlobalsForFile(File(path.join(flutterDirectory.path, entry))); + } final int gitExitCode = await git.exitCode; - if (gitExitCode != 0) + if (gitExitCode != 0) { throw Exception('git exit with unexpected error code $gitExitCode'); + } return total; } @@ -135,8 +152,9 @@ Future countDependencies() async { options: ['--transitive-closure'], )).split('\n'); final int count = lines.where((String line) => line.contains('->')).length; - if (count < 2) // we'll always have flutter and flutter_test, at least... + if (count < 2) { throw Exception('"flutter update-packages --transitive-closure" returned bogus output:\n${lines.join("\n")}'); + } return count; } @@ -146,8 +164,9 @@ Future countConsumerDependencies() async { options: ['--transitive-closure', '--consumer-only'], )).split('\n'); final int count = lines.where((String line) => line.contains('->')).length; - if (count < 2) // we'll always have flutter and flutter_test, at least... + if (count < 2) { throw Exception('"flutter update-packages --transitive-closure" returned bogus output:\n${lines.join("\n")}'); + } return count; } diff --git a/dev/devicelab/lib/framework/apk_utils.dart b/dev/devicelab/lib/framework/apk_utils.dart index db959a4b77..e9a989cefd 100644 --- a/dev/devicelab/lib/framework/apk_utils.dart +++ b/dev/devicelab/lib/framework/apk_utils.dart @@ -410,8 +410,9 @@ Future _runGradleTask({ print('stderr:'); print(result.stderr); } - if (result.exitCode != 0) + if (result.exitCode != 0) { throw 'Gradle exited with error'; + } } Future _resultOfGradleTask({ @@ -422,8 +423,9 @@ Future _resultOfGradleTask({ section('Find Java'); final String? javaHome = await findJavaHome(); - if (javaHome == null) + if (javaHome == null) { throw TaskResult.failure('Could not find Java'); + } print('\nUsing JAVA_HOME=$javaHome'); diff --git a/dev/devicelab/lib/framework/devices.dart b/dev/devicelab/lib/framework/devices.dart index 5835a53e14..a35df37d3c 100644 --- a/dev/devicelab/lib/framework/devices.dart +++ b/dev/devicelab/lib/framework/devices.dart @@ -252,8 +252,9 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { .map((String id) => AndroidDevice(deviceId: id)) .toList(); - if (allDevices.isEmpty) + if (allDevices.isEmpty) { throw const DeviceException('No Android devices detected'); + } if (cpu != null) { for (final AndroidDevice device in allDevices) { @@ -268,8 +269,9 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { _workingDevice = allDevices[math.Random().nextInt(allDevices.length)]; } - if (_workingDevice == null) + if (_workingDevice == null) { throw const DeviceException('Cannot find a suitable Android device'); + } print('Device chosen: $_workingDevice'); } @@ -300,11 +302,13 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { final List results = []; for (final String line in output) { // Skip lines like: * daemon started successfully * - if (line.startsWith('* daemon ')) + if (line.startsWith('* daemon ')) { continue; + } - if (line.startsWith('List of devices')) + if (line.startsWith('List of devices')) { continue; + } if (_kDeviceRegex.hasMatch(line)) { final Match match = _kDeviceRegex.firstMatch(line)!; @@ -551,15 +555,17 @@ class AndroidDevice extends Device { /// Wake up the device if it is not awake using [togglePower]. @override Future wakeUp() async { - if (!(await isAwake())) + if (!(await isAwake())) { await togglePower(); + } } /// Send the device to sleep mode if it is not asleep using [togglePower]. @override Future sendToSleep() async { - if (!(await isAsleep())) + if (!(await isAsleep())) { await togglePower(); + } } /// Sends `KEYCODE_HOME` (3), which causes the device to go to the home screen. @@ -840,8 +846,9 @@ class IosDeviceDiscovery implements DeviceDiscovery { .map((String id) => IosDevice(deviceId: id)) .toList(); - if (allDevices.isEmpty) + if (allDevices.isEmpty) { throw const DeviceException('No iOS devices detected'); + } // TODO(yjbanov): filter out and warn about those with low battery level _workingDevice = allDevices[math.Random().nextInt(allDevices.length)]; @@ -1211,8 +1218,9 @@ String get adbPath { final String adbPath = path.join(androidHome, 'platform-tools/adb'); - if (!canRun(adbPath)) + if (!canRun(adbPath)) { throw DeviceException('adb not found at: $adbPath'); + } return path.absolute(adbPath); } diff --git a/dev/devicelab/lib/framework/framework.dart b/dev/devicelab/lib/framework/framework.dart index 7a475f4a91..2282907aaf 100644 --- a/dev/devicelab/lib/framework/framework.dart +++ b/dev/devicelab/lib/framework/framework.dart @@ -46,8 +46,9 @@ bool _isTaskRegistered = false; /// If no `processManager` is provided, a default [LocalProcessManager] is created /// for the task. Future task(TaskFunction task, { ProcessManager? processManager }) async { - if (_isTaskRegistered) + if (_isTaskRegistered) { throw StateError('A task is already registered'); + } _isTaskRegistered = true; processManager ??= const LocalProcessManager(); @@ -163,8 +164,9 @@ class _TaskRunner { } Future futureResult = _performTask(); - if (taskTimeout != null) + if (taskTimeout != null) { futureResult = futureResult.timeout(taskTimeout); + } result = await futureResult; } finally { @@ -241,8 +243,9 @@ class _TaskRunner { /// Causes the Dart VM to stay alive until a request to run the task is /// received via the VM service protocol. void keepVmAliveUntilTaskRunRequested() { - if (_taskStarted) + if (_taskStarted) { throw StateError('Task already started.'); + } // Merely creating this port object will cause the VM to stay alive and keep // the VM service server running until the port is disposed of. @@ -280,8 +283,9 @@ class _TaskRunner { // are catching errors coming from arbitrary (and untrustworthy) task // code. Our goal is to convert the failure into a readable message. // Propagating it further is not useful. - if (!completer.isCompleted) + if (!completer.isCompleted) { completer.complete(TaskResult.failure(message)); + } }); return completer.future; } diff --git a/dev/devicelab/lib/framework/runner.dart b/dev/devicelab/lib/framework/runner.dart index d7992c2f38..1c40144adc 100644 --- a/dev/devicelab/lib/framework/runner.dart +++ b/dev/devicelab/lib/framework/runner.dart @@ -156,8 +156,9 @@ Future runTask( }) async { final String taskExecutable = 'bin/tasks/$taskName.dart'; - if (!file(taskExecutable).existsSync()) + if (!file(taskExecutable).existsSync()) { throw 'Executable Dart file not found: $taskExecutable'; + } final Process runner = await startProcess( dartBin, @@ -190,8 +191,9 @@ Future runTask( .listen((String line) { if (!uri.isCompleted) { final Uri? serviceUri = parseServiceUri(line, prefix: RegExp('(Observatory|The Dart VM service is) listening on ')); - if (serviceUri != null) + if (serviceUri != null) { uri.complete(serviceUri); + } } if (!silent) { stdout.writeln('[$taskName] [STDOUT] $line'); @@ -255,12 +257,14 @@ Future _connectToRunnerIsolate(Uri vmServiceUri) async { } final IsolateRef isolate = vm.isolates!.first; final Response response = await client.callServiceExtension('ext.cocoonRunnerReady', isolateId: isolate.id); - if (response.json!['response'] != 'ready') + if (response.json!['response'] != 'ready') { throw 'not ready yet'; + } return ConnectionResult(client, isolate); } catch (error) { - if (stopwatch.elapsed > const Duration(seconds: 10)) + if (stopwatch.elapsed > const Duration(seconds: 10)) { print('VM service still not ready after ${stopwatch.elapsed}: $error\nContinuing to retry...'); + } await Future.delayed(const Duration(milliseconds: 50)); } } diff --git a/dev/devicelab/lib/framework/utils.dart b/dev/devicelab/lib/framework/utils.dart index ea31c73cbd..73d4612574 100644 --- a/dev/devicelab/lib/framework/utils.dart +++ b/dev/devicelab/lib/framework/utils.dart @@ -126,14 +126,15 @@ void copy(File sourceFile, Directory targetDirectory, {String? name}) { } void recursiveCopy(Directory source, Directory target) { - if (!target.existsSync()) + if (!target.existsSync()) { target.createSync(); + } for (final FileSystemEntity entity in source.listSync(followLinks: false)) { final String name = path.basename(entity.path); - if (entity is Directory && !entity.path.contains('.dart_tool')) + if (entity is Directory && !entity.path.contains('.dart_tool')) { recursiveCopy(entity, Directory(path.join(target.path, name))); - else if (entity is File) { + } else if (entity is File) { final File dest = File(path.join(target.path, name)); dest.writeAsBytesSync(entity.readAsBytesSync()); // Preserve executable bit @@ -194,8 +195,9 @@ void section(String title) { title = '╡ ••• $title ••• ╞'; final String line = '═' * math.max((80 - title.length) ~/ 2, 2); output = '$line$title$line'; - if (output.length == 79) + if (output.length == 79) { output += '═'; + } } print('\n\n$output\n'); } @@ -209,10 +211,12 @@ Future getDartVersion() async { // Dart VM version: 1.17.0-dev.2.0 (Tue May 3 12:14:52 2016) on "macos_x64" // to: // 1.17.0-dev.2.0 - if (version.contains('(')) + if (version.contains('(')) { version = version.substring(0, version.indexOf('(')).trim(); - if (version.contains(':')) + } + if (version.contains(':')) { version = version.substring(version.indexOf(':') + 1).trim(); + } return version.replaceAll('"', "'"); } @@ -295,8 +299,9 @@ Future startProcess( } Future forceQuitRunningProcesses() async { - if (_runningProcesses.isEmpty) + if (_runningProcesses.isEmpty) { return; + } // Give normally quitting processes a chance to report their exit code. await Future.delayed(const Duration(seconds: 1)); @@ -354,8 +359,9 @@ Future _execute( ); final int exitCode = await process.exitCode; - if (exitCode != 0 && !canFail) + if (exitCode != 0 && !canFail) { fail('Executable "$executable" failed with exit code $exitCode.'); + } return exitCode; } @@ -545,8 +551,9 @@ Future findJavaHome() async { 'Java binary at: ', from: await evalFlutter('doctor', options: ['-v']), ); - if (hits.isEmpty) + if (hits.isEmpty) { return null; + } final String javaBinary = hits.first .split(': ') .last; @@ -579,8 +586,9 @@ void cd(dynamic directory) { throw FileSystemException('Unsupported directory type ${directory.runtimeType}', directory.toString()); } - if (!d.existsSync()) + if (!d.existsSync()) { throw FileSystemException('Cannot cd into directory that does not exist', d.toString()); + } } Directory get flutterDirectory => Directory.current.parent.parent; @@ -590,15 +598,17 @@ Directory get openpayDirectory => Directory(requireEnvVar('OPENPAY_CHECKOUT_PATH String requireEnvVar(String name) { final String? value = Platform.environment[name]; - if (value == null) + if (value == null) { fail('$name environment variable is missing. Quitting.'); + } return value!; } T requireConfigProperty(Map map, String propertyName) { - if (!map.containsKey(propertyName)) + if (!map.containsKey(propertyName)) { fail('Configuration property not found: $propertyName'); + } final T result = map[propertyName] as T; return result; } @@ -634,26 +644,36 @@ void checkNotNull(Object o1, Object o8 = 1, Object o9 = 1, Object o10 = 1]) { - if (o1 == null) + if (o1 == null) { throw 'o1 is null'; - if (o2 == null) + } + if (o2 == null) { throw 'o2 is null'; - if (o3 == null) + } + if (o3 == null) { throw 'o3 is null'; - if (o4 == null) + } + if (o4 == null) { throw 'o4 is null'; - if (o5 == null) + } + if (o5 == null) { throw 'o5 is null'; - if (o6 == null) + } + if (o6 == null) { throw 'o6 is null'; - if (o7 == null) + } + if (o7 == null) { throw 'o7 is null'; - if (o8 == null) + } + if (o8 == null) { throw 'o8 is null'; - if (o9 == null) + } + if (o9 == null) { throw 'o9 is null'; - if (o10 == null) + } + if (o10 == null) { throw 'o10 is null'; + } } /// Splits [from] into lines and selects those that contain [pattern]. diff --git a/dev/devicelab/lib/microbenchmarks.dart b/dev/devicelab/lib/microbenchmarks.dart index 88c2095610..72430f2791 100644 --- a/dev/devicelab/lib/microbenchmarks.dart +++ b/dev/devicelab/lib/microbenchmarks.dart @@ -74,8 +74,9 @@ Future> readJsonResults(Process process) { return; } - if (jsonStarted && line.contains(jsonPrefix)) + if (jsonStarted && line.contains(jsonPrefix)) { jsonBuf.writeln(line.substring(line.indexOf(jsonPrefix) + jsonPrefix.length)); + } }); process.exitCode.then((int code) async { diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index 2534510f0d..f53637bc5d 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -288,8 +288,9 @@ TaskFunction createBasicMaterialCompileTest() { await flutter('create', options: ['--template=app', sampleAppName]); }); - if (!sampleDir.existsSync()) + if (!sampleDir.existsSync()) { throw 'Failed to create default Flutter app in ${sampleDir.path}'; + } return CompileTest(sampleDir.path).run(); }; @@ -754,8 +755,9 @@ class StartupTest { final Map averageResults = _average(results, iterations); - if (!reportMetrics) + if (!reportMetrics) { return TaskResult.success(averageResults); + } return TaskResult.success(averageResults, benchmarkScoreKeys: [ 'timeToFirstFrameMicros', @@ -860,8 +862,9 @@ class DevtoolsStartupTest { device.deviceId, ]); - if (sawLine) + if (sawLine) { return TaskResult.success(null, benchmarkScoreKeys: []); + } return TaskResult.failure('Did not see line "The Flutter DevTools debugger and profiler" in output'); }); } @@ -1401,8 +1404,9 @@ class CompileTest { // IPAs are created manually, https://flutter.dev/ios-release/ await exec('tar', ['-zcf', 'build/app.ipa', appPath]); releaseSizeInBytes = await file('$cwd/build/app.ipa').length(); - if (reportPackageContentSizes) + if (reportPackageContentSizes) { metrics.addAll(await getSizesFromIosApp(appPath)); + } break; case DeviceOperatingSystem.android: case DeviceOperatingSystem.androidArm: @@ -1416,8 +1420,9 @@ class CompileTest { final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk'; final File apk = file(apkPath); releaseSizeInBytes = apk.lengthSync(); - if (reportPackageContentSizes) + if (reportPackageContentSizes) { metrics.addAll(await getSizesFromApk(apkPath)); + } break; case DeviceOperatingSystem.androidArm64: options.insert(0, 'apk'); @@ -1430,8 +1435,9 @@ class CompileTest { final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk'; final File apk = file(apkPath); releaseSizeInBytes = apk.lengthSync(); - if (reportPackageContentSizes) + if (reportPackageContentSizes) { metrics.addAll(await getSizesFromApk(apkPath)); + } break; case DeviceOperatingSystem.fake: throw Exception('Unsupported option for fake devices'); @@ -1572,8 +1578,9 @@ class MemoryTest { final StreamSubscription adb = device!.logcat.listen( (String data) { - if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) + if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) { _receivedNextMessage?.complete(); + } }, ); @@ -1764,8 +1771,9 @@ class ReportedDurationTest { final StreamSubscription adb = device!.logcat.listen( (String data) { - if (durationPattern.hasMatch(data)) + if (durationPattern.hasMatch(data)) { durationCompleter.complete(int.parse(durationPattern.firstMatch(data)!.group(1)!)); + } }, ); print('launching $project$test on device...'); diff --git a/dev/devicelab/test/adb_test.dart b/dev/devicelab/test/adb_test.dart index 063c645535..e9d0033f08 100644 --- a/dev/devicelab/test/adb_test.dart +++ b/dev/devicelab/test/adb_test.dart @@ -158,8 +158,9 @@ class CommandArgs { @override bool operator==(Object other) { - if (other.runtimeType != CommandArgs) + if (other.runtimeType != CommandArgs) { return false; + } return other is CommandArgs && other.command == command && const ListEquality().equals(other.arguments, arguments) diff --git a/dev/integration_tests/android_semantics_testing/lib/main.dart b/dev/integration_tests/android_semantics_testing/lib/main.dart index fd0a7d3146..3e8002ba23 100644 --- a/dev/integration_tests/android_semantics_testing/lib/main.dart +++ b/dev/integration_tests/android_semantics_testing/lib/main.dart @@ -33,10 +33,11 @@ Future dataHandler(String message) async { }); completer.complete(json.encode(result)); } - if (SchedulerBinding.instance.hasScheduledFrame) + if (SchedulerBinding.instance.hasScheduledFrame) { SchedulerBinding.instance.addPostFrameCallback(completeSemantics); - else + } else { completeSemantics(); + } return completer.future; } if (message.contains('setClipboard')) { @@ -48,10 +49,11 @@ Future dataHandler(String message) async { }); completer.complete(''); } - if (SchedulerBinding.instance.hasScheduledFrame) + if (SchedulerBinding.instance.hasScheduledFrame) { SchedulerBinding.instance.addPostFrameCallback(completeSetClipboard); - else + } else { completeSetClipboard(); + } return completer.future; } throw UnimplementedError(); diff --git a/dev/integration_tests/android_semantics_testing/lib/src/common.dart b/dev/integration_tests/android_semantics_testing/lib/src/common.dart index 2f4338d2ef..9305855f49 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/common.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/common.dart @@ -187,8 +187,9 @@ class Rect { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is Rect && other.top == top && other.left == left @@ -219,8 +220,9 @@ class Size { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is Size && other.width == width && other.height == height; diff --git a/dev/integration_tests/android_semantics_testing/lib/src/constants.dart b/dev/integration_tests/android_semantics_testing/lib/src/constants.dart index 66ebff9b89..22f75bc7bd 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/constants.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/constants.dart @@ -201,8 +201,9 @@ class AndroidSemanticsAction { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is AndroidSemanticsAction && other.id == id; } diff --git a/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart b/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart index 626364b26b..ea36302266 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/matcher.dart @@ -100,53 +100,74 @@ class _AndroidSemanticsMatcher extends Matcher { @override Description describe(Description description) { description.add('AndroidSemanticsNode'); - if (text != null) + if (text != null) { description.add(' with text: $text'); - if (contentDescription != null) + } + if (contentDescription != null) { description.add( 'with contentDescription $contentDescription'); - if (className != null) + } + if (className != null) { description.add(' with className: $className'); - if (id != null) + } + if (id != null) { description.add(' with id: $id'); - if (actions != null) + } + if (actions != null) { description.add(' with actions: $actions'); - if (rect != null) + } + if (rect != null) { description.add(' with rect: $rect'); - if (size != null) + } + if (size != null) { description.add(' with size: $size'); - if (isChecked != null) + } + if (isChecked != null) { description.add(' with flag isChecked: $isChecked'); - if (isEditable != null) + } + if (isEditable != null) { description.add(' with flag isEditable: $isEditable'); - if (isEnabled != null) + } + if (isEnabled != null) { description.add(' with flag isEnabled: $isEnabled'); - if (isFocusable != null) + } + if (isFocusable != null) { description.add(' with flag isFocusable: $isFocusable'); - if (isFocused != null) + } + if (isFocused != null) { description.add(' with flag isFocused: $isFocused'); - if (isHeading != null) + } + if (isHeading != null) { description.add(' with flag isHeading: $isHeading'); - if (isPassword != null) + } + if (isPassword != null) { description.add(' with flag isPassword: $isPassword'); - if (isLongClickable != null) + } + if (isLongClickable != null) { description.add(' with flag isLongClickable: $isLongClickable'); + } return description; } @override bool matches(covariant AndroidSemanticsNode item, Map matchState) { - if (text != null && text != item.text) + if (text != null && text != item.text) { return _failWithMessage('Expected text: $text', matchState); - if (contentDescription != null && contentDescription != item.contentDescription) + } + if (contentDescription != null && contentDescription != item.contentDescription) { return _failWithMessage('Expected contentDescription: $contentDescription', matchState); - if (className != null && className != item.className) + } + if (className != null && className != item.className) { return _failWithMessage('Expected className: $className', matchState); - if (id != null && id != item.id) + } + if (id != null && id != item.id) { return _failWithMessage('Expected id: $id', matchState); - if (rect != null && rect != item.getRect()) + } + if (rect != null && rect != item.getRect()) { return _failWithMessage('Expected rect: $rect', matchState); - if (size != null && size != item.getSize()) + } + if (size != null && size != item.getSize()) { return _failWithMessage('Expected size: $size', matchState); + } if (actions != null) { final List itemActions = item.getActions(); if (!unorderedEquals(actions).matches(itemActions, matchState)) { @@ -161,25 +182,34 @@ class _AndroidSemanticsMatcher extends Matcher { return _failWithMessage('Expected actions: $actionsString\nActual actions: $itemActionsString\nUnexpected: $unexpectedInString\nMissing: $missingInString', matchState); } } - if (isChecked != null && isChecked != item.isChecked) + if (isChecked != null && isChecked != item.isChecked) { return _failWithMessage('Expected isChecked: $isChecked', matchState); - if (isCheckable != null && isCheckable != item.isCheckable) + } + if (isCheckable != null && isCheckable != item.isCheckable) { return _failWithMessage('Expected isCheckable: $isCheckable', matchState); - if (isEditable != null && isEditable != item.isEditable) + } + if (isEditable != null && isEditable != item.isEditable) { return _failWithMessage('Expected isEditable: $isEditable', matchState); - if (isEnabled != null && isEnabled != item.isEnabled) + } + if (isEnabled != null && isEnabled != item.isEnabled) { return _failWithMessage('Expected isEnabled: $isEnabled', matchState); - if (isFocusable != null && isFocusable != item.isFocusable) + } + if (isFocusable != null && isFocusable != item.isFocusable) { return _failWithMessage('Expected isFocusable: $isFocusable', matchState); - if (isFocused != null && isFocused != item.isFocused) + } + if (isFocused != null && isFocused != item.isFocused) { return _failWithMessage('Expected isFocused: $isFocused', matchState); + } // Heading is not available in all Android versions, so match anything if it is not set by the platform - if (isHeading != null && isHeading != item.isHeading && item.isHeading != null) + if (isHeading != null && isHeading != item.isHeading && item.isHeading != null) { return _failWithMessage('Expected isHeading: $isHeading', matchState); - if (isPassword != null && isPassword != item.isPassword) + } + if (isPassword != null && isPassword != item.isPassword) { return _failWithMessage('Expected isPassword: $isPassword', matchState); - if (isLongClickable != null && isLongClickable != item.isLongClickable) + } + if (isLongClickable != null && isLongClickable != item.isLongClickable) { return _failWithMessage('Expected longClickable: $isLongClickable', matchState); + } return true; } diff --git a/dev/integration_tests/android_views/lib/motion_event_diff.dart b/dev/integration_tests/android_views/lib/motion_event_diff.dart index 7dacd1e87f..217d0ebcc9 100644 --- a/dev/integration_tests/android_views/lib/motion_event_diff.dart +++ b/dev/integration_tests/android_views/lib/motion_event_diff.dart @@ -47,17 +47,19 @@ void diffActions(StringBuffer diffBuffer, Map originalEvent, final String originalActionName = getActionName(originalActionMasked, originalEvent['action'] as int); - if (synthesizedActionMasked != originalActionMasked) + if (synthesizedActionMasked != originalActionMasked) { diffBuffer.write( 'action (expected: $originalActionName actual: $synthesizedActionName) '); + } if (kPointerActions.contains(originalActionMasked) && originalActionMasked == synthesizedActionMasked) { final int originalPointer = getPointerIdx(originalEvent['action'] as int); final int synthesizedPointer = getPointerIdx(synthesizedEvent['action'] as int); - if (originalPointer != synthesizedPointer) + if (originalPointer != synthesizedPointer) { diffBuffer.write( 'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName '); + } } } @@ -123,10 +125,12 @@ void diffMaps( return; } for (final String key in expected.keys) { - if (excludeKeys.contains(key)) + if (excludeKeys.contains(key)) { continue; - if (doublesApproximatelyMatch(expected[key], actual[key])) + } + if (doublesApproximatelyMatch(expected[key], actual[key])) { continue; + } if (expected[key] != actual[key]) { diffBuffer.write( @@ -155,10 +159,11 @@ String getActionName(int actionMasked, int action) { 'BUTTON_PRESS', 'BUTTON_RELEASE', ]; - if (actionMasked < actionNames.length) + if (actionMasked < actionNames.length) { return '${actionNames[actionMasked]}($action)'; - else + } else { return 'ACTION_$actionMasked'; + } } bool doublesApproximatelyMatch(dynamic a, dynamic b) => diff --git a/dev/integration_tests/android_views/lib/motion_events_page.dart b/dev/integration_tests/android_views/lib/motion_events_page.dart index db629fae52..7978a32e2c 100644 --- a/dev/integration_tests/android_views/lib/motion_events_page.dart +++ b/dev/integration_tests/android_views/lib/motion_events_page.dart @@ -146,16 +146,19 @@ class MotionEventsBodyState extends State { await channel.invokeMethod('stopFlutterViewEvents'); await viewChannel?.invokeMethod('stopTouchEvents'); - if (flutterViewEvents.length != embeddedViewEvents.length) + if (flutterViewEvents.length != embeddedViewEvents.length) { return 'Synthesized ${flutterViewEvents.length} events but the embedded view received ${embeddedViewEvents.length} events'; + } final StringBuffer diff = StringBuffer(); for (int i = 0; i < flutterViewEvents.length; ++i) { final String currentDiff = diffMotionEvents(flutterViewEvents[i], embeddedViewEvents[i]); - if (currentDiff.isEmpty) + if (currentDiff.isEmpty) { continue; - if (diff.isNotEmpty) + } + if (diff.isNotEmpty) { diff.write(', '); + } diff.write(currentDiff); } return diff.toString(); @@ -229,8 +232,9 @@ class MotionEventsBodyState extends State { case 'onTouch': final Map map = call.arguments as Map; flutterViewEvents.insert(0, map.cast()); - if (flutterViewEvents.length > kEventsBufferSize) + if (flutterViewEvents.length > kEventsBufferSize) { flutterViewEvents.removeLast(); + } setState(() {}); break; } @@ -242,8 +246,9 @@ class MotionEventsBodyState extends State { case 'onTouch': final Map map = call.arguments as Map; embeddedViewEvents.insert(0, map.cast()); - if (embeddedViewEvents.length > kEventsBufferSize) + if (embeddedViewEvents.length > kEventsBufferSize) { embeddedViewEvents.removeLast(); + } setState(() {}); break; } @@ -251,9 +256,10 @@ class MotionEventsBodyState extends State { } Widget buildEventTile(BuildContext context, int index) { - if (embeddedViewEvents.length > index) + if (embeddedViewEvents.length > index) { return TouchEventDiff( flutterViewEvents[index], embeddedViewEvents[index]); + } return Text( 'Unmatched event, action: ${flutterViewEvents[index]['action']}'); } diff --git a/dev/integration_tests/channels/lib/main.dart b/dev/integration_tests/channels/lib/main.dart index cccfdf2e39..fdd1a25c58 100644 --- a/dev/integration_tests/channels/lib/main.dart +++ b/dev/integration_tests/channels/lib/main.dart @@ -172,10 +172,11 @@ class _TestAppState extends State { void _executeNextStep() { setState(() { - if (_step < steps.length) + if (_step < steps.length) { _result = steps[_step++](); - else + } else { _result = Future.value(TestStepResult.complete); + } }); } diff --git a/dev/integration_tests/channels/lib/src/basic_messaging.dart b/dev/integration_tests/channels/lib/src/basic_messaging.dart index f52dd377b3..08392fc5d4 100644 --- a/dev/integration_tests/channels/lib/src/basic_messaging.dart +++ b/dev/integration_tests/channels/lib/src/basic_messaging.dart @@ -169,10 +169,11 @@ Future _basicMessageToUnknownChannel( } String toString(dynamic message) { - if (message is ByteData) + if (message is ByteData) { return message.buffer .asUint8List(message.offsetInBytes, message.lengthInBytes) .toString(); - else + } else { return '$message'; + } } diff --git a/dev/integration_tests/channels/lib/src/test_step.dart b/dev/integration_tests/channels/lib/src/test_step.dart index 19e848f705..6702560ebf 100644 --- a/dev/integration_tests/channels/lib/src/test_step.dart +++ b/dev/integration_tests/channels/lib/src/test_step.dart @@ -101,8 +101,9 @@ Future resultOfHandshake( dynamic error, ) async { assert(message != nothing); - while (received.length < 2) + while (received.length < 2) { received.add(nothing); + } TestStatus status; if (!_deepEquals(messageEcho, message) || received.length != 2 || @@ -127,27 +128,34 @@ Future resultOfHandshake( } String _toString(dynamic message) { - if (message is ByteData) + if (message is ByteData) { return message.buffer .asUint8List(message.offsetInBytes, message.lengthInBytes) .toString(); - else + } else { return '$message'; + } } bool _deepEquals(dynamic a, dynamic b) { - if (a == b) + if (a == b) { return true; - if (a is double && a.isNaN) + } + if (a is double && a.isNaN) { return b is double && b.isNaN; - if (a is ByteData) + } + if (a is ByteData) { return b is ByteData && _deepEqualsByteData(a, b); - if (a is List) + } + if (a is List) { return b is List && _deepEqualsList(a, b); - if (a is Map) + } + if (a is Map) { return b is Map && _deepEqualsMap(a, b); - if (a is Pair) + } + if (a is Pair) { return b is Pair && _deepEqualsPair(a, b); + } return false; } @@ -159,21 +167,25 @@ bool _deepEqualsByteData(ByteData a, ByteData b) { } bool _deepEqualsList(List a, List b) { - if (a.length != b.length) + if (a.length != b.length) { return false; + } for (int i = 0; i < a.length; i++) { - if (!_deepEquals(a[i], b[i])) + if (!_deepEquals(a[i], b[i])) { return false; + } } return true; } bool _deepEqualsMap(Map a, Map b) { - if (a.length != b.length) + if (a.length != b.length) { return false; + } for (final dynamic key in a.keys) { - if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) + if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) { return false; + } } return true; } diff --git a/dev/integration_tests/external_ui/lib/main.dart b/dev/integration_tests/external_ui/lib/main.dart index 8d133ddb72..bbbc59a856 100644 --- a/dev/integration_tests/external_ui/lib/main.dart +++ b/dev/integration_tests/external_ui/lib/main.dart @@ -115,8 +115,9 @@ Press play to produce texture frames.'''; _state = FrameState.initial; }); } else { - if ((tickCount % (calibrationTickCount ~/ 20)) == 0) + if ((tickCount % (calibrationTickCount ~/ 20)) == 0) { debugPrint('Calibrating... ${(100.0 * tickCount / calibrationTickCount).floor()}%'); + } } }); ticker.start(); diff --git a/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart b/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart index 6804386ad2..3803e9ea15 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/animation/home.dart @@ -44,8 +44,9 @@ class _RenderStatusBarPaddingSliver extends RenderSliver { double _maxHeight; set maxHeight(double value) { assert(maxHeight >= 0.0); - if (_maxHeight == value) + if (_maxHeight == value) { return; + } _maxHeight = value; markNeedsLayout(); } @@ -56,8 +57,9 @@ class _RenderStatusBarPaddingSliver extends RenderSliver { double _scrollFactor; set scrollFactor(double value) { assert(scrollFactor >= 1.0); - if (_scrollFactor == value) + if (_scrollFactor == value) { return; + } _scrollFactor = value; markNeedsLayout(); } @@ -390,22 +392,27 @@ class _SnappingScrollPhysics extends ClampingScrollPhysics { // then snap it there. Similarly if the simulation is headed down past // midScrollOffset but will not reach zero, then snap it to zero. final double simulationEnd = simulation.x(double.infinity); - if (simulationEnd >= midScrollOffset) + if (simulationEnd >= midScrollOffset) { return simulation; - if (dragVelocity > 0.0) + } + if (dragVelocity > 0.0) { return _toMidScrollOffsetSimulation(offset, dragVelocity); - if (dragVelocity < 0.0) + } + if (dragVelocity < 0.0) { return _toZeroScrollOffsetSimulation(offset, dragVelocity); + } } else { // The user ended the drag with little or no velocity. If they // didn't leave the offset above midScrollOffset, then // snap to midScrollOffset if they're more than halfway there, // otherwise snap to zero. final double snapThreshold = midScrollOffset / 2.0; - if (offset >= snapThreshold && offset < midScrollOffset) + if (offset >= snapThreshold && offset < midScrollOffset) { return _toMidScrollOffsetSimulation(offset, dragVelocity); - if (offset > 0.0 && offset < snapThreshold) + } + if (offset > 0.0 && offset < snapThreshold) { return _toZeroScrollOffsetSimulation(offset, dragVelocity); + } } return simulation; } @@ -439,10 +446,11 @@ class _AnimationDemoHomeState extends State { } void _handleBackButton(double midScrollOffset) { - if (_scrollController.offset >= midScrollOffset) + if (_scrollController.offset >= midScrollOffset) { _scrollController.animateTo(0.0, curve: _kScrollCurve, duration: _kScrollDuration); - else + } else { Navigator.maybePop(context); + } } // Only enable paging for the heading when the user has scrolled to midScrollOffset. @@ -478,8 +486,9 @@ class _AnimationDemoHomeState extends State { bool _handlePageNotification(ScrollNotification notification, PageController leader, PageController follower) { if (notification.depth == 0 && notification is ScrollUpdateNotification) { selectedIndex.value = leader.page; - if (follower.page != leader.page) + if (follower.page != leader.page) { follower.position.jumpToWithoutSettling(leader.position.pixels); // ignore: deprecated_member_use + } } return false; } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart b/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart index 61ba88fe8d..f5f0a1f9b8 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart @@ -35,10 +35,12 @@ class FloatToken extends NumberToken { static double _parse(String stringRep) { String toParse = stringRep; - if (toParse.startsWith('.')) + if (toParse.startsWith('.')) { toParse = '0$toParse'; - if (toParse.endsWith('.')) + } + if (toParse.endsWith('.')) { toParse = '${toParse}0'; + } return double.parse(toParse); } } @@ -51,8 +53,9 @@ class ResultToken extends NumberToken { /// floating point number is guaranteed to have at least this many /// decimal digits of precision. static num round(num number) { - if (number is int) + if (number is int) { return number; + } return double.parse(number.toStringAsPrecision(14)); } } @@ -330,10 +333,11 @@ class CalcExpression { // Remove the next number token. final NumberToken nextNumToken = list.removeAt(0)! as NumberToken; final num nextNumber = nextNumToken.number; - if (isDivision) + if (isDivision) { currentValue /= nextNumber; - else + } else { currentValue *= nextNumber; + } } return currentValue; } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/backdrop_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/backdrop_demo.dart index d7ba44099e..060d21c013 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/backdrop_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/backdrop_demo.dart @@ -294,23 +294,26 @@ class _BackdropDemoState extends State with SingleTickerProviderSt // the user must either tap its heading or the backdrop's menu icon. void _handleDragUpdate(DragUpdateDetails details) { - if (_controller.isAnimating || _controller.status == AnimationStatus.completed) + if (_controller.isAnimating || _controller.status == AnimationStatus.completed) { return; + } _controller.value -= details.primaryDelta! / _backdropHeight; } void _handleDragEnd(DragEndDetails details) { - if (_controller.isAnimating || _controller.status == AnimationStatus.completed) + if (_controller.isAnimating || _controller.status == AnimationStatus.completed) { return; + } final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; - if (flingVelocity < 0.0) + if (flingVelocity < 0.0) { _controller.fling(velocity: math.max(2.0, -flingVelocity)); - else if (flingVelocity > 0.0) + } else if (flingVelocity > 0.0) { _controller.fling(velocity: math.min(-2.0, -flingVelocity)); - else + } else { _controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0); + } } // Stacks a BackdropPanel, which displays the selected category, on top diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart index ae7453ea21..81ec130797 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart @@ -204,12 +204,15 @@ class _BottomAppBarDemoState extends State { } NotchedShape? _selectNotch() { - if (!_showNotch.value!) + if (!_showNotch.value!) { return null; - if (_fabShape == kCircularFab) + } + if (_fabShape == kCircularFab) { return const CircularNotchedRectangle(); - if (_fabShape == kDiamondFab) + } + if (_fabShape == kDiamondFab) { return const _DiamondNotchedRectangle(); + } return null; } } @@ -452,8 +455,9 @@ class _DiamondNotchedRectangle implements NotchedShape { @override Path getOuterPath(Rect host, Rect? guest) { - if (!host.overlaps(guest!)) + if (!host.overlaps(guest!)) { return Path()..addRect(host); + } assert(guest.width > 0.0); final Rect intersection = guest.intersect(host); diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart index 9fe16397a9..df1a559c01 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart @@ -165,8 +165,9 @@ class _BottomNavigationDemoState extends State @override void dispose() { - for (final NavigationIconView view in _navigationViews) + for (final NavigationIconView view in _navigationViews) { view.controller.dispose(); + } super.dispose(); } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart index c01463d9ab..4547738a59 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/data_table_demo.dart @@ -97,8 +97,9 @@ class DessertDataSource extends DataTableSource { @override DataRow? getRow(int index) { assert(index >= 0); - if (index >= _desserts.length) + if (index >= _desserts.length) { return null; + } final Dessert dessert = _desserts[index]; return DataRow.byIndex( index: index, @@ -134,8 +135,9 @@ class DessertDataSource extends DataTableSource { int get selectedRowCount => _selectedCount; void _selectAll(bool? checked) { - for (final Dessert dessert in _desserts) + for (final Dessert dessert in _desserts) { dessert.selected = checked; + } _selectedCount = checked! ? _desserts.length : 0; notifyListeners(); } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/date_and_time_picker_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/date_and_time_picker_demo.dart index 9737040fb3..6349bdf160 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/date_and_time_picker_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/date_and_time_picker_demo.dart @@ -66,8 +66,9 @@ class _DateTimePicker extends StatelessWidget { firstDate: DateTime(2015, 8), lastDate: DateTime(2101), ); - if (picked != null && picked != selectedDate) + if (picked != null && picked != selectedDate) { selectDate!(picked); + } } Future _selectTime(BuildContext context) async { @@ -75,8 +76,9 @@ class _DateTimePicker extends StatelessWidget { context: context, initialTime: selectedTime!, ); - if (picked != null && picked != selectedTime) + if (picked != null && picked != selectedTime) { selectTime!(picked); + } } @override diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart index 5049bf6773..695d164da7 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/drawer_demo.dart @@ -144,10 +144,11 @@ class _DrawerDemoState extends State with TickerProviderStateMixin { margin: EdgeInsets.zero, onDetailsPressed: () { _showDrawerContents = !_showDrawerContents; - if (_showDrawerContents) + if (_showDrawerContents) { _controller.reverse(); - else + } else { _controller.forward(); + } }, ), MediaQuery.removePadding( diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart index 4c0c111610..8918dfb668 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart @@ -46,8 +46,9 @@ class DateTimeItem extends StatelessWidget { lastDate: date.add(const Duration(days: 30)), ) .then((DateTime? value) { - if (value != null) + if (value != null) { onChanged(DateTime(value.year, value.month, value.day, time.hour, time.minute)); + } }); }, child: Row( @@ -73,8 +74,9 @@ class DateTimeItem extends StatelessWidget { initialTime: time, ) .then((TimeOfDay? value) { - if (value != null) + if (value != null) { onChanged(DateTime(date.year, date.month, date.day, value.hour, value.minute)); + } }); }, child: Row( @@ -109,8 +111,9 @@ class FullScreenDialogDemoState extends State { Future _onWillPop() async { _saveNeeded = _hasLocation || _hasName || _saveNeeded; - if (!_saveNeeded) + if (!_saveNeeded) { return true; + } final ThemeData theme = Theme.of(context); final TextStyle dialogTextStyle = theme.textTheme.subtitle1!.copyWith(color: theme.textTheme.caption!.color); diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart index 6a0c1e1925..8635871c87 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/grid_list_demo.dart @@ -118,8 +118,9 @@ class _GridPhotoViewerState extends State with SingleTickerProv void _handleOnScaleEnd(ScaleEndDetails details) { final double magnitude = details.velocity.pixelsPerSecond.distance; - if (magnitude < _kMinFlingVelocity) + if (magnitude < _kMinFlingVelocity) { return; + } final Offset direction = details.velocity.pixelsPerSecond / magnitude; final double distance = (Offset.zero & context.size!).shortestSide; _flingAnimation = _controller.drive(Tween( diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/leave_behind_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/leave_behind_demo.dart index 5392bfb35c..e6e9035d50 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/leave_behind_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/leave_behind_demo.dart @@ -222,10 +222,11 @@ class _LeaveBehindListItem extends StatelessWidget { key: ObjectKey(item), direction: dismissDirection, onDismissed: (DismissDirection direction) { - if (direction == DismissDirection.endToStart) + if (direction == DismissDirection.endToStart) { _handleArchive(); - else + } else { _handleDelete(); + } }, confirmDismiss: !confirmDismiss ? null : (DismissDirection dismissDirection) async { switch(dismissDirection) { diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart index c12b00c2e7..7890874c0f 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart @@ -224,8 +224,9 @@ class _ListDemoState extends State { } Iterable listTiles = items.map((String item) => buildListTile(context, item)); - if (_showDividers != null) + if (_showDividers != null) { listTiles = ListTile.divideTiles(context: context, tiles: listTiles); + } return Scaffold( key: scaffoldKey, diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart index 359337d4f8..4fdd96cce0 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/menu_demo.dart @@ -42,16 +42,18 @@ class MenuDemoState extends State { } void showMenuSelection(String value) { - if ([_simpleValue1, _simpleValue2, _simpleValue3].contains(value)) + if ([_simpleValue1, _simpleValue2, _simpleValue3].contains(value)) { setState(() => _simpleValue = value); + } showInSnackBar('You selected: $value'); } void showCheckedMenuSelections(String value) { - if (_checkedValues.contains(value)) + if (_checkedValues.contains(value)) { _checkedValues.remove(value); - else + } else { _checkedValues.add(value); + } showInSnackBar('Checked $_checkedValues'); } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart index ec456d3c4a..b9cc7bfb3c 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/overscroll_demo.dart @@ -29,8 +29,9 @@ class OverscrollDemoState extends State { final Completer completer = Completer(); Timer(const Duration(seconds: 3), () => completer.complete()); return completer.future.then((_) { - if (!mounted) + if (!mounted) { return; + } ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: const Text('Refresh complete'), action: SnackBarAction( diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart index b6a257470c..dc8a068f99 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/page_selector_demo.dart @@ -13,8 +13,9 @@ class _PageSelector extends StatelessWidget { void _handleArrowButtonPress(BuildContext context, int delta) { final TabController controller = DefaultTabController.of(context)!; - if (!controller.indexIsChanging) + if (!controller.indexIsChanging) { controller.animateTo((controller.index + delta).clamp(0, icons!.length - 1)); + } } @override diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart index 2d5b6e1676..c4788786c9 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/progress_indicator_demo.dart @@ -33,10 +33,11 @@ class _ProgressIndicatorDemoState extends State with Sing curve: const Interval(0.0, 0.9, curve: Curves.fastOutSlowIn), reverseCurve: Curves.fastOutSlowIn, )..addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed) + if (status == AnimationStatus.dismissed) { _controller.forward(); - else if (status == AnimationStatus.completed) + } else if (status == AnimationStatus.completed) { _controller.reverse(); + } }); } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/scrollable_tabs_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/scrollable_tabs_demo.dart index f7cbdcff75..e96d792966 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/scrollable_tabs_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/scrollable_tabs_demo.dart @@ -68,8 +68,9 @@ class ScrollableTabsDemoState extends State with SingleTicke } Decoration? getIndicator() { - if (!_customIndicator) + if (!_customIndicator) { return const UnderlineTabIndicator(); + } switch(_demoStyle) { case TabsDemoStyle.iconsAndText: diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_fab_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_fab_demo.dart index c787a0ec91..582651d81c 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_fab_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/tabs_fab_demo.dart @@ -107,8 +107,9 @@ class _TabsFabDemoState extends State with SingleTickerProviderStat } Widget? buildFloatingActionButton(_Page page) { - if (!page.fabDefined) + if (!page.fabDefined) { return null; + } if (_extendedButtons) { return FloatingActionButton.extended( diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart index 4ef742e238..bcf5288a4a 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/text_form_field_demo.dart @@ -112,36 +112,42 @@ class TextFormFieldDemoState extends State { String? _validateName(String? value) { _formWasEdited = true; - if (value!.isEmpty) + if (value!.isEmpty) { return 'Name is required.'; + } final RegExp nameExp = RegExp(r'^[A-Za-z ]+$'); - if (!nameExp.hasMatch(value)) + if (!nameExp.hasMatch(value)) { return 'Please enter only alphabetical characters.'; + } return null; } String? _validatePhoneNumber(String? value) { _formWasEdited = true; final RegExp phoneExp = RegExp(r'^\(\d\d\d\) \d\d\d\-\d\d\d\d$'); - if (!phoneExp.hasMatch(value!)) + if (!phoneExp.hasMatch(value!)) { return '(###) ###-#### - Enter a US phone number.'; + } return null; } String? _validatePassword(String? value) { _formWasEdited = true; final FormFieldState passwordField = _passwordFieldKey.currentState!; - if (passwordField.value == null || passwordField.value!.isEmpty) + if (passwordField.value == null || passwordField.value!.isEmpty) { return 'Please enter a password.'; - if (passwordField.value != value) + } + if (passwordField.value != value) { return "The passwords don't match"; + } return null; } Future _warnUserAboutInvalidData() async { final FormState? form = _formKey.currentState; - if (form == null || !_formWasEdited || form.validate()) + if (form == null || !_formWasEdited || form.validate()) { return true; + } final bool? result = await showDialog( context: context, @@ -313,30 +319,35 @@ class _UsNumberTextInputFormatter extends TextInputFormatter { final StringBuffer newText = StringBuffer(); if (newTextLength >= 1) { newText.write('('); - if (newValue.selection.end >= 1) + if (newValue.selection.end >= 1) { selectionIndex++; + } } if (newTextLength >= 4) { final String value = newValue.text.substring(0, usedSubstringIndex = 3); newText.write('$value) '); - if (newValue.selection.end >= 3) + if (newValue.selection.end >= 3) { selectionIndex += 2; + } } if (newTextLength >= 7) { final String value = newValue.text.substring(3, usedSubstringIndex = 6); newText.write('$value-'); - if (newValue.selection.end >= 6) + if (newValue.selection.end >= 6) { selectionIndex++; + } } if (newTextLength >= 11) { final String value = newValue.text.substring(6, usedSubstringIndex = 10); newText.write('$value '); - if (newValue.selection.end >= 10) + if (newValue.selection.end >= 10) { selectionIndex++; + } } // Dump the rest. - if (newTextLength >= usedSubstringIndex) + if (newTextLength >= usedSubstringIndex) { newText.write(newValue.text.substring(usedSubstringIndex)); + } return TextEditingValue( text: newText.toString(), selection: TextSelection.collapsed(offset: selectionIndex), diff --git a/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart index 8dc170f2eb..fd36fe6c69 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/pesto_demo.dart @@ -418,10 +418,11 @@ class _RecipePageState extends State { void _toggleFavorite() { setState(() { - if (_favoriteRecipes.contains(widget.recipe)) + if (_favoriteRecipes.contains(widget.recipe)) { _favoriteRecipes.remove(widget.recipe); - else + } else { _favoriteRecipes.add(widget.recipe); + } }); } } diff --git a/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart b/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart index e27688ad9b..34eede5e5c 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart @@ -533,8 +533,9 @@ class ExtraProductsNumber extends StatelessWidget { } Widget _buildOverflow(AppStateModel model, BuildContext context) { - if (model.productsInCart.length <= 3) + if (model.productsInCart.length <= 3) { return Container(); + } final int numOverflowProducts = _calculateOverflow(model); // Maximum of 99 so padding doesn't get messy. diff --git a/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart index 10cb886678..e48b3f69f4 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/video_demo.dart @@ -148,8 +148,9 @@ class VideoPlayPause extends StatefulWidget { class _VideoPlayPauseState extends State { _VideoPlayPauseState() { listener = () { - if (mounted) + if (mounted) { setState(() { }); + } }; } diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart b/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart index 4beec4d288..6c1e296155 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart @@ -241,16 +241,18 @@ class _BackdropState extends State with SingleTickerProviderStateMixin } void _handleDragEnd(DragEndDetails details) { - if (_controller!.isAnimating || _controller!.status == AnimationStatus.completed) + if (_controller!.isAnimating || _controller!.status == AnimationStatus.completed) { return; + } final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; - if (flingVelocity < 0.0) + if (flingVelocity < 0.0) { _controller!.fling(velocity: math.max(2.0, -flingVelocity)); - else if (flingVelocity > 0.0) + } else if (flingVelocity > 0.0) { _controller!.fling(velocity: math.min(-2.0, -flingVelocity)); - else + } else { _controller!.fling(velocity: _controller!.value < 0.5 ? -2.0 : 2.0); + } } void _toggleFrontLayer() { diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/demo.dart b/dev/integration_tests/flutter_gallery/lib/gallery/demo.dart index c8fe83c904..9c9d115238 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/demo.dart @@ -28,8 +28,9 @@ class ComponentDemoTabData { @override bool operator==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is ComponentDemoTabData && other.tabName == tabName && other.description == description @@ -67,8 +68,9 @@ class TabbedComponentDemoScaffold extends StatelessWidget { Future _showApiDocumentation(BuildContext context) async { final String? url = demos![DefaultTabController.of(context)!.index].documentationUrl; - if (url == null) + if (url == null) { return; + } final Uri uri = Uri.parse(url); if (await canLaunchUrl(uri)) { diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart b/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart index 13af7693c3..dc025cfcec 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/demos.dart @@ -19,10 +19,12 @@ class GalleryDemoCategory { @override bool operator ==(Object other) { - if (identical(this, other)) + if (identical(this, other)) { return true; - if (other.runtimeType != runtimeType) + } + if (other.runtimeType != runtimeType) { return false; + } return other is GalleryDemoCategory && other.name == name && other.icon == icon; diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart b/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart index 0b335bd2c2..67f062d1f3 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart @@ -99,8 +99,9 @@ DropdownButton( // null indicates the user didn't select a // new value. setState(() { - if (newValue != null) + if (newValue != null) { dropdownValue = newValue; + } }); }, items: ['One', 'Two', 'Free', 'Four'] diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart b/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart index cab344adcf..1f06984ec0 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/example_code_parser.dart @@ -10,8 +10,9 @@ const String _kEndTag = '// END'; Map? _exampleCode; Future getExampleCode(String? tag, AssetBundle bundle) async { - if (_exampleCode == null) + if (_exampleCode == null) { await _parseExampleCode(bundle); + } return _exampleCode![tag]; } diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/options.dart b/dev/integration_tests/flutter_gallery/lib/gallery/options.dart index 5e1530083a..7c408f2199 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/options.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/options.dart @@ -57,8 +57,9 @@ class GalleryOptions { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is GalleryOptions && other.themeMode == themeMode && other.textScaleFactor == textScaleFactor @@ -480,8 +481,9 @@ class GalleryOptionsPage extends StatelessWidget { List _enabledDiagnosticItems() { // Boolean showFoo options with a value of null: don't display // the showFoo option at all. - if (options == null) + if (options == null) { return const []; + } return [ const Divider(), diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/scales.dart b/dev/integration_tests/flutter_gallery/lib/gallery/scales.dart index 09c490932a..ba2dc28b0b 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/scales.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/scales.dart @@ -13,8 +13,9 @@ class GalleryTextScaleValue { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is GalleryTextScaleValue && other.scale == scale && other.label == label; @@ -47,8 +48,9 @@ class GalleryVisualDensityValue { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is GalleryVisualDensityValue && other.visualDensity == visualDensity && other.label == label; diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart b/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart index dea3bf6825..d81430e5f9 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart @@ -95,16 +95,18 @@ class DartSyntaxHighlighter extends SyntaxHighlighter { int currentPosition = 0; for (final _HighlightSpan span in _spans) { - if (currentPosition != span.start) + if (currentPosition != span.start) { formattedText.add(TextSpan(text: _src!.substring(currentPosition, span.start))); + } formattedText.add(TextSpan(style: span.textStyle(_style), text: span.textForSpan(_src!))); currentPosition = span.end; } - if (currentPosition != _src!.length) + if (currentPosition != _src!.length) { formattedText.add(TextSpan(text: _src!.substring(currentPosition, _src!.length))); + } return TextSpan(style: _style!.baseStyle, children: formattedText); } else { @@ -149,8 +151,9 @@ class DartSyntaxHighlighter extends SyntaxHighlighter { endComment, )); - if (eof) + if (eof) { break; + } continue; } @@ -260,17 +263,19 @@ class DartSyntaxHighlighter extends SyntaxHighlighter { _HighlightType? type; String word = _scanner.lastMatch![0]!; - if (word.startsWith('_')) + if (word.startsWith('_')) { word = word.substring(1); + } - if (_keywords.contains(word)) + if (_keywords.contains(word)) { type = _HighlightType.keyword; - else if (_builtInTypes.contains(word)) + } else if (_builtInTypes.contains(word)) { type = _HighlightType.keyword; - else if (_firstLetterIsUpperCase(word)) + } else if (_firstLetterIsUpperCase(word)) { type = _HighlightType.klass; - else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1))) + } else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1))) { type = _HighlightType.constant; + } if (type != null) { _spans.add(_HighlightSpan( @@ -336,21 +341,22 @@ class _HighlightSpan { } TextStyle? textStyle(SyntaxHighlighterStyle? style) { - if (type == _HighlightType.number) + if (type == _HighlightType.number) { return style!.numberStyle; - else if (type == _HighlightType.comment) + } else if (type == _HighlightType.comment) { return style!.commentStyle; - else if (type == _HighlightType.keyword) + } else if (type == _HighlightType.keyword) { return style!.keywordStyle; - else if (type == _HighlightType.string) + } else if (type == _HighlightType.string) { return style!.stringStyle; - else if (type == _HighlightType.punctuation) + } else if (type == _HighlightType.punctuation) { return style!.punctuationStyle; - else if (type == _HighlightType.klass) + } else if (type == _HighlightType.klass) { return style!.classStyle; - else if (type == _HighlightType.constant) + } else if (type == _HighlightType.constant) { return style!.constantStyle; - else + } else { return style!.baseStyle; + } } } diff --git a/dev/integration_tests/flutter_gallery/lib/gallery/updater.dart b/dev/integration_tests/flutter_gallery/lib/gallery/updater.dart index 90787fc614..befb271e73 100644 --- a/dev/integration_tests/flutter_gallery/lib/gallery/updater.dart +++ b/dev/integration_tests/flutter_gallery/lib/gallery/updater.dart @@ -36,8 +36,9 @@ class UpdaterState extends State { final String? updateUrl = await widget.updateUrlFetcher(); final bool? wantsUpdate = await showDialog(context: context, builder: _buildDialog); - if (wantsUpdate != null && updateUrl != null && wantsUpdate) + if (wantsUpdate != null && updateUrl != null && wantsUpdate) { launchUrl(Uri.parse(updateUrl)); + } } Widget _buildDialog(BuildContext context) { diff --git a/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart b/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart index 0fbb5de08b..3a53a022b3 100644 --- a/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart +++ b/dev/integration_tests/flutter_gallery/test/calculator/smoke_test.dart @@ -8,8 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } // We press the "1" and the "2" buttons and check that the display // reads "12". diff --git a/dev/integration_tests/flutter_gallery/test/drawer_test.dart b/dev/integration_tests/flutter_gallery/test/drawer_test.dart index 0ba0894fa5..3dc6e93675 100644 --- a/dev/integration_tests/flutter_gallery/test/drawer_test.dart +++ b/dev/integration_tests/flutter_gallery/test/drawer_test.dart @@ -9,8 +9,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } testWidgets('Flutter Gallery drawer item test', (WidgetTester tester) async { bool hasFeedback = false; diff --git a/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart b/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart index b39bc1c56b..eba2996d43 100644 --- a/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart +++ b/dev/integration_tests/flutter_gallery/test/example_code_display_test.dart @@ -8,8 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } testWidgets('Flutter gallery button example code displays', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/6147 diff --git a/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart b/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart index 1200dcba3c..94276fb38e 100644 --- a/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart +++ b/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart @@ -45,8 +45,9 @@ class TestAssetBundle extends AssetBundle { @override Future loadString(String key, { bool cache = true }) async { - if (key == 'lib/gallery/example_code.dart') + if (key == 'lib/gallery/example_code.dart') { return testCodeFile; + } return ''; } diff --git a/dev/integration_tests/flutter_gallery/test/live_smoketest.dart b/dev/integration_tests/flutter_gallery/test/live_smoketest.dart index e8b5150e92..26aae16dec 100644 --- a/dev/integration_tests/flutter_gallery/test/live_smoketest.dart +++ b/dev/integration_tests/flutter_gallery/test/live_smoketest.dart @@ -51,10 +51,12 @@ Future main() async { // Verify that _kUnsynchronizedDemos and _kSkippedDemos identify // demos that actually exist. final List allDemoTitles = kAllGalleryDemos.map((GalleryDemo demo) => demo.title).toList(); - if (!Set.from(allDemoTitles).containsAll(_kUnsynchronizedDemoTitles)) + if (!Set.from(allDemoTitles).containsAll(_kUnsynchronizedDemoTitles)) { fail('Unrecognized demo titles in _kUnsynchronizedDemosTitles: $_kUnsynchronizedDemoTitles'); - if (!Set.from(allDemoTitles).containsAll(_kSkippedDemoTitles)) + } + if (!Set.from(allDemoTitles).containsAll(_kSkippedDemoTitles)) { fail('Unrecognized demo names in _kSkippedDemoTitles: $_kSkippedDemoTitles'); + } print('Starting app...'); runApp(const GalleryApp(testMode: true)); @@ -66,8 +68,9 @@ Future main() async { final Finder demoItem = find.text(demo.title); print('Scrolling to "${demo.title}"...'); await controller.scrollIntoView(demoItem, alignment: 0.5); - if (_kSkippedDemoTitles.contains(demo.title)) + if (_kSkippedDemoTitles.contains(demo.title)) { continue; + } for (int i = 0; i < 2; i += 1) { print('Tapping "${demo.title}"...'); await controller.tap(demoItem); // Launch the demo @@ -91,10 +94,12 @@ Future main() async { final Finder backFinder = find.byElementPredicate( (Element element) { final Widget widget = element.widget; - if (widget is Tooltip) + if (widget is Tooltip) { return widget.message == 'Back'; - if (widget is CupertinoNavigationBarBackButton) + } + if (widget is CupertinoNavigationBarBackButton) { return true; + } return false; }, description: 'Material or Cupertino back button', @@ -122,11 +127,13 @@ class _LiveWidgetController extends LiveWidgetController { /// Runs `finder` repeatedly until it finds one or more [Element]s. Future _waitForElement(Finder finder) async { - if (frameSync) + if (frameSync) { await _waitUntilFrame(() => binding.transientCallbackCount == 0); + } await _waitUntilFrame(() => finder.precache()); - if (frameSync) + if (frameSync) { await _waitUntilFrame(() => binding.transientCallbackCount == 0); + } return finder; } diff --git a/dev/integration_tests/flutter_gallery/test/pesto_test.dart b/dev/integration_tests/flutter_gallery/test/pesto_test.dart index 817f490737..de3886e4d1 100644 --- a/dev/integration_tests/flutter_gallery/test/pesto_test.dart +++ b/dev/integration_tests/flutter_gallery/test/pesto_test.dart @@ -8,8 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } // Regression test for https://github.com/flutter/flutter/pull/5168 testWidgets('Pesto appbar heroics', (WidgetTester tester) async { diff --git a/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart b/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart index 050cb12aed..2744ea2e65 100644 --- a/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart +++ b/dev/integration_tests/flutter_gallery/test/simple_smoke_test.dart @@ -8,8 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } testWidgets('Flutter Gallery app simple smoke test', (WidgetTester tester) async { await tester.pumpWidget( diff --git a/dev/integration_tests/flutter_gallery/test/smoke_test.dart b/dev/integration_tests/flutter_gallery/test/smoke_test.dart index ba9e5bb33f..1f58e5b52d 100644 --- a/dev/integration_tests/flutter_gallery/test/smoke_test.dart +++ b/dev/integration_tests/flutter_gallery/test/smoke_test.dart @@ -40,8 +40,9 @@ void reportToStringError(String name, String route, int lineNumber, List void verifyToStringOutput(String name, String route, String testString) { int lineNumber = 0; final List lines = testString.split('\n'); - if (!testString.endsWith('\n')) + if (!testString.endsWith('\n')) { reportToStringError(name, route, lines.length, lines, 'does not end with a line feed'); + } for (final String line in lines) { lineNumber += 1; if (line == '' && lineNumber != lines.length) { diff --git a/dev/integration_tests/flutter_gallery/test/update_test.dart b/dev/integration_tests/flutter_gallery/test/update_test.dart index 160bb96690..82b8002d7d 100644 --- a/dev/integration_tests/flutter_gallery/test/update_test.dart +++ b/dev/integration_tests/flutter_gallery/test/update_test.dart @@ -12,8 +12,9 @@ Future mockUpdateUrlFetcher() { void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - if (binding is LiveTestWidgetsFlutterBinding) + if (binding is LiveTestWidgetsFlutterBinding) { binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + } // Regression test for https://github.com/flutter/flutter/pull/5168 testWidgets('update dialog', (WidgetTester tester) async { diff --git a/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart b/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart index 064c66b17b..475e0eeb80 100644 --- a/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart +++ b/dev/integration_tests/flutter_gallery/test_driver/run_demos.dart @@ -23,8 +23,9 @@ Future runDemos(List demos, WidgetController controller) async { String? currentDemoCategory; for (final String demo in demos) { - if (kSkippedDemos.contains(demo)) + if (kSkippedDemos.contains(demo)) { continue; + } final String demoName = demo.substring(0, demo.indexOf('@')); final String demoCategory = demo.substring(demo.indexOf('@') + 1); diff --git a/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart b/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart index 058aabe35e..acea40463a 100644 --- a/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart +++ b/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart @@ -60,8 +60,9 @@ Future saveDurationsHistogram(List> events, String ou } // Verify that the durations data is valid. - if (durations.keys.isEmpty) + if (durations.keys.isEmpty) { throw 'no "Start Transition" timeline events found'; + } final Map unexpectedValueCounts = {}; durations.forEach((String routeName, List values) { if (values.length != 2) { @@ -83,8 +84,9 @@ Future saveDurationsHistogram(List> events, String ou while (eventIter.moveNext()) { final String eventName = eventIter.current['name'] as String; - if (!['Start Transition', 'Frame'].contains(eventName)) + if (!['Start Transition', 'Frame'].contains(eventName)) { continue; + } final String routeName = eventName == 'Start Transition' ? (eventIter.current['args'] as Map)['to'] as String @@ -114,8 +116,9 @@ Future runDemos(List demos, FlutterDriver driver) async { String? currentDemoCategory; for (final String demo in demos) { - if (kSkippedDemos.contains(demo)) + if (kSkippedDemos.contains(demo)) { continue; + } final String demoName = demo.substring(0, demo.indexOf('@')); final String demoCategory = demo.substring(demo.indexOf('@') + 1); @@ -176,8 +179,9 @@ void main([List args = const []]) { // See _handleMessages() in transitions_perf.dart. _allDemos = List.from(json.decode(await driver.requestData('demoNames')) as List); - if (_allDemos.isEmpty) + if (_allDemos.isEmpty) { throw 'no demo names found'; + } }); tearDownAll(() async { diff --git a/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart b/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart index 7cfa842fe3..c2879e4a48 100644 --- a/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart +++ b/dev/integration_tests/hybrid_android_views/lib/motion_event_diff.dart @@ -46,17 +46,19 @@ void diffActions(StringBuffer diffBuffer, Map originalEvent, final String originalActionName = getActionName(originalActionMasked, originalEvent['action'] as int); - if (synthesizedActionMasked != originalActionMasked) + if (synthesizedActionMasked != originalActionMasked) { diffBuffer.write( 'action (expected: $originalActionName actual: $synthesizedActionName) '); + } if (kPointerActions.contains(originalActionMasked) && originalActionMasked == synthesizedActionMasked) { final int originalPointer = getPointerIdx(originalEvent['action'] as int); final int synthesizedPointer = getPointerIdx(synthesizedEvent['action'] as int); - if (originalPointer != synthesizedPointer) + if (originalPointer != synthesizedPointer) { diffBuffer.write( 'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName '); + } } } @@ -122,10 +124,12 @@ void diffMaps( return; } for (final String key in expected.keys) { - if (excludeKeys.contains(key)) + if (excludeKeys.contains(key)) { continue; - if (doublesApproximatelyMatch(expected[key], actual[key])) + } + if (doublesApproximatelyMatch(expected[key], actual[key])) { continue; + } if (expected[key] != actual[key]) { diffBuffer.write( @@ -154,10 +158,11 @@ String getActionName(int actionMasked, int action) { 'BUTTON_PRESS', 'BUTTON_RELEASE', ]; - if (actionMasked < actionNames.length) + if (actionMasked < actionNames.length) { return '${actionNames[actionMasked]}($action)'; - else + } else { return 'ACTION_$actionMasked'; + } } bool doublesApproximatelyMatch(dynamic a, dynamic b) => diff --git a/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart b/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart index abc69022e7..261185f46b 100644 --- a/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart +++ b/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart @@ -128,16 +128,19 @@ class MotionEventsBodyState extends State { await viewChannel!.invokeMethod('stopTouchEvents'); - if (flutterViewEvents.length != embeddedViewEvents.length) + if (flutterViewEvents.length != embeddedViewEvents.length) { return 'Synthesized ${flutterViewEvents.length} events but the embedded view received ${embeddedViewEvents.length} events'; + } final StringBuffer diff = StringBuffer(); for (int i = 0; i < flutterViewEvents.length; ++i) { final String currentDiff = diffMotionEvents(flutterViewEvents[i], embeddedViewEvents[i]); - if (currentDiff.isEmpty) + if (currentDiff.isEmpty) { continue; - if (diff.isNotEmpty) + } + if (diff.isNotEmpty) { diff.write(', '); + } diff.write(currentDiff); } return diff.toString(); @@ -201,8 +204,9 @@ class MotionEventsBodyState extends State { case 'onTouch': final Map map = call.arguments as Map; flutterViewEvents.insert(0, map.cast()); - if (flutterViewEvents.length > kEventsBufferSize) + if (flutterViewEvents.length > kEventsBufferSize) { flutterViewEvents.removeLast(); + } setState(() {}); break; } @@ -214,8 +218,9 @@ class MotionEventsBodyState extends State { case 'onTouch': final Map map = call.arguments as Map; embeddedViewEvents.insert(0, map.cast()); - if (embeddedViewEvents.length > kEventsBufferSize) + if (embeddedViewEvents.length > kEventsBufferSize) { embeddedViewEvents.removeLast(); + } setState(() {}); break; } @@ -223,9 +228,10 @@ class MotionEventsBodyState extends State { } Widget buildEventTile(BuildContext context, int index) { - if (embeddedViewEvents.length > index) + if (embeddedViewEvents.length > index) { return TouchEventDiff( flutterViewEvents[index], embeddedViewEvents[index]); + } return Text( 'Unmatched event, action: ${flutterViewEvents[index]['action']}'); } diff --git a/dev/integration_tests/platform_interaction/lib/main.dart b/dev/integration_tests/platform_interaction/lib/main.dart index b5deae2dad..fdfe0854ae 100644 --- a/dev/integration_tests/platform_interaction/lib/main.dart +++ b/dev/integration_tests/platform_interaction/lib/main.dart @@ -31,10 +31,11 @@ class _TestAppState extends State { void _executeNextStep() { setState(() { - if (_step < steps.length) + if (_step < steps.length) { _result = steps[_step++](); - else + } else { _result = Future.value(TestStepResult.complete); + } }); } diff --git a/dev/integration_tests/ui/lib/overflow.dart b/dev/integration_tests/ui/lib/overflow.dart index ffea335d91..882f9525e3 100644 --- a/dev/integration_tests/ui/lib/overflow.dart +++ b/dev/integration_tests/ui/lib/overflow.dart @@ -26,8 +26,9 @@ class _TestState extends State { @override Widget build(BuildContext context) { - if (!_triggered) + if (!_triggered) { return const SizedBox.shrink(); + } return Row(children: const [ SizedBox(width: 10000.0), SizedBox(width: 10000.0), diff --git a/dev/manual_tests/lib/actions.dart b/dev/manual_tests/lib/actions.dart index 50e3c30816..385cace542 100644 --- a/dev/manual_tests/lib/actions.dart +++ b/dev/manual_tests/lib/actions.dart @@ -342,10 +342,12 @@ class _DemoButtonState extends State { style: ButtonStyle( foregroundColor: MaterialStateProperty.all(Colors.black), overlayColor: MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.focused)) + if (states.contains(MaterialState.focused)) { return Colors.red; - if (states.contains(MaterialState.hovered)) + } + if (states.contains(MaterialState.hovered)) { return Colors.blue; + } return Colors.transparent; }), ), diff --git a/dev/manual_tests/lib/card_collection.dart b/dev/manual_tests/lib/card_collection.dart index 0f4afe1969..89378491de 100644 --- a/dev/manual_tests/lib/card_collection.dart +++ b/dev/manual_tests/lib/card_collection.dart @@ -50,8 +50,9 @@ class CardCollectionState extends State { bool _varyFontSizes = false; void _updateCardSizes() { - if (_fixedSizeCards) + if (_fixedSizeCards) { return; + } _cardModels = List.generate( _cardModels.length, (int i) { @@ -77,10 +78,11 @@ class CardCollectionState extends State { } void _initCardModels() { - if (_fixedSizeCards) + if (_fixedSizeCards) { _initFixedSizedCardModels(); - else + } else { _initVariableSizedCardModels(); + } } @override @@ -301,13 +303,15 @@ class CardCollectionState extends State { // This icon is wrong in RTL. Widget leftArrowIcon = const Icon(Icons.arrow_back, size: 36.0); - if (_dismissDirection == DismissDirection.startToEnd) + if (_dismissDirection == DismissDirection.startToEnd) { leftArrowIcon = Opacity(opacity: 0.1, child: leftArrowIcon); + } // This icon is wrong in RTL. Widget rightArrowIcon = const Icon(Icons.arrow_forward, size: 36.0); - if (_dismissDirection == DismissDirection.endToStart) + if (_dismissDirection == DismissDirection.endToStart) { rightArrowIcon = Opacity(opacity: 0.1, child: rightArrowIcon); + } final ThemeData theme = Theme.of(context); final TextStyle? backgroundTextStyle = theme.primaryTextTheme.headline6; diff --git a/dev/manual_tests/lib/drag_and_drop.dart b/dev/manual_tests/lib/drag_and_drop.dart index f0d9ce1f27..e54ab87c1c 100644 --- a/dev/manual_tests/lib/drag_and_drop.dart +++ b/dev/manual_tests/lib/drag_and_drop.dart @@ -96,8 +96,9 @@ class ExampleDragSource extends StatelessWidget { @override Widget build(BuildContext context) { double size = kDotSize; - if (heavy) + if (heavy) { size *= kHeavyMultiplier; + } final Widget contents = DefaultTextStyle( style: Theme.of(context).textTheme.bodyText2!, @@ -166,8 +167,9 @@ class DashOutlineCirclePainter extends CustomPainter { ..strokeWidth = radius / 10.0; final Path path = Path(); final Rect box = Offset.zero & size; - for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) + for (double theta = 0.0; theta < math.pi * 2.0; theta += deltaTheta) { path.addArc(box, theta + startOffset, segmentArc); + } canvas.drawPath(path, paint); } diff --git a/dev/manual_tests/lib/focus.dart b/dev/manual_tests/lib/focus.dart index a248b10d59..0b281526a6 100644 --- a/dev/manual_tests/lib/focus.dart +++ b/dev/manual_tests/lib/focus.dart @@ -54,10 +54,12 @@ class _DemoButtonState extends State { autofocus: widget.autofocus, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.focused)) + if (states.contains(MaterialState.focused)) { return Colors.red.withOpacity(0.25); - if (states.contains(MaterialState.hovered)) + } + if (states.contains(MaterialState.hovered)) { return Colors.blue.withOpacity(0.25); + } return Colors.transparent; }), ), diff --git a/dev/manual_tests/lib/material_arc.dart b/dev/manual_tests/lib/material_arc.dart index dba072f609..3c1e4b8b4c 100644 --- a/dev/manual_tests/lib/material_arc.dart +++ b/dev/manual_tests/lib/material_arc.dart @@ -68,18 +68,20 @@ class _PointDemoPainter extends CustomPainter { void paint(Canvas canvas, Size size) { final Paint paint = Paint(); - if (arc.center != null) + if (arc.center != null) { drawPoint(canvas, arc.center!, Colors.grey.shade400); + } paint ..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720 ..color = Colors.green.withOpacity(0.25) ..strokeWidth = 4.0 ..style = PaintingStyle.stroke; - if (arc.center != null && arc.radius != null) + if (arc.center != null && arc.radius != null) { canvas.drawCircle(arc.center!, arc.radius!, paint); - else + } else { canvas.drawLine(arc.begin!, arc.end!, paint); + } drawPoint(canvas, arc.begin!, Colors.green); drawPoint(canvas, arc.end!, Colors.red); @@ -132,19 +134,21 @@ class _PointDemoState extends State<_PointDemo> { Drag _handleOnStart(Offset position) { // TODO(hansmuller): allow the user to drag both points at the same time. - if (_dragTarget != null) + if (_dragTarget != null) { return _IgnoreDrag(); + } final RenderBox? box = _painterKey.currentContext!.findRenderObject() as RenderBox?; final double startOffset = (box!.localToGlobal(_begin!) - position).distanceSquared; final double endOffset = (box.localToGlobal(_end!) - position).distanceSquared; setState(() { - if (startOffset < endOffset && startOffset < _kTargetSlop) + if (startOffset < endOffset && startOffset < _kTargetSlop) { _dragTarget = _DragTarget.start; - else if (endOffset < _kTargetSlop) + } else if (endOffset < _kTargetSlop) { _dragTarget = _DragTarget.end; - else + } else { _dragTarget = null; + } }); return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd); @@ -293,19 +297,21 @@ class _RectangleDemoState extends State<_RectangleDemo> { Drag _handleOnStart(Offset position) { // TODO(hansmuller): allow the user to drag both points at the same time. - if (_dragTarget != null) + if (_dragTarget != null) { return _IgnoreDrag(); + } final RenderBox? box = _painterKey.currentContext?.findRenderObject() as RenderBox?; final double startOffset = (box!.localToGlobal(_begin!.center) - position).distanceSquared; final double endOffset = (box.localToGlobal(_end!.center) - position).distanceSquared; setState(() { - if (startOffset < endOffset && startOffset < _kTargetSlop) + if (startOffset < endOffset && startOffset < _kTargetSlop) { _dragTarget = _DragTarget.start; - else if (endOffset < _kTargetSlop) + } else if (endOffset < _kTargetSlop) { _dragTarget = _DragTarget.end; - else + } else { _dragTarget = null; + } }); return _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd); } @@ -424,8 +430,9 @@ class _AnimationDemoState extends State with TickerProviderStateM Future _play(_ArcDemo demo) async { await demo.controller.forward(); - if (demo.key.currentState != null && demo.key.currentState!.mounted) + if (demo.key.currentState != null && demo.key.currentState!.mounted) { demo.controller.reverse(); + } } @override diff --git a/dev/manual_tests/lib/overlay_geometry.dart b/dev/manual_tests/lib/overlay_geometry.dart index c60ab37ce3..5fb9d8b97d 100644 --- a/dev/manual_tests/lib/overlay_geometry.dart +++ b/dev/manual_tests/lib/overlay_geometry.dart @@ -105,8 +105,9 @@ class CardBuilder extends SliverChildDelegate { @override Widget? build(BuildContext context, int index) { - if (index >= cardModels.length) + if (index >= cardModels.length) { return null; + } final CardModel cardModel = cardModels[index]; return GestureDetector( key: cardModel.key, diff --git a/dev/manual_tests/lib/text.dart b/dev/manual_tests/lib/text.dart index 8fe670829c..2040cefc36 100644 --- a/dev/manual_tests/lib/text.dart +++ b/dev/manual_tests/lib/text.dart @@ -158,8 +158,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { } String? _fiddleWithText(String? text) { - if (_random.nextInt(10) > 0) + if (_random.nextInt(10) > 0) { return text; + } return _createRandomText(); } @@ -175,8 +176,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { return null; } } - if (_random.nextInt(200) == 0) + if (_random.nextInt(200) == 0) { return null; + } return TextStyle( color: _fiddleWithColor(style.color), decoration: _fiddleWithDecoration(style.decoration), @@ -196,8 +198,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { Color? _fiddleWithColor(Color? value) { switch (_random.nextInt(10)) { case 0: - if (value == null) + if (value == null) { return pickFromList(_random, Colors.primaries)[(_random.nextInt(9) + 1) * 100]; + } switch (_random.nextInt(4)) { case 0: return value.withAlpha(value.alpha + _random.nextInt(10) - 5); @@ -216,8 +219,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { } TextDecoration? _fiddleWithDecoration(TextDecoration? value) { - if (_random.nextInt(10) > 0) + if (_random.nextInt(10) > 0) { return value; + } switch (_random.nextInt(100)) { case 10: return TextDecoration.underline; @@ -300,8 +304,9 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { double? _fiddleWithDouble(double? value, double defaultValue, double max) { switch (_random.nextInt(10)) { case 0: - if (value == null) + if (value == null) { return math.min(defaultValue * (0.95 + _random.nextDouble() * 0.1), max); + } return math.min(value * (0.51 + _random.nextDouble()), max); case 1: return null; @@ -322,26 +327,32 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { children = children.reversed.toList(); break; case 20: - if (children.isEmpty) + if (children.isEmpty) { break; - if (_random.nextInt(10) > 0) + } + if (_random.nextInt(10) > 0) { break; + } final int index = _random.nextInt(children.length); - if (depthOf(children[index]) < 3) + if (depthOf(children[index]) < 3) { children.removeAt(index); + } break; } - if (children.isEmpty && _random.nextBool()) + if (children.isEmpty && _random.nextBool()) { return null; + } return children; } int depthOf(TextSpan node) { - if (node.children == null || (node.children?.isEmpty ?? false)) + if (node.children == null || (node.children?.isEmpty ?? false)) { return 0; + } int result = 0; - for (final TextSpan child in node.children!.cast()) + for (final TextSpan child in node.children!.cast()) { result = math.max(result, depthOf(child)); + } return result; } @@ -1057,8 +1068,9 @@ class _PaintingState extends State with SingleTickerProviderStateMixin setState(() { _ellipsize = value; _random = math.Random(widget.seed); // reset for reproducibility - if (!_ticker.isActive) + if (!_ticker.isActive) { _update(null); + } }); }, ), @@ -1419,8 +1431,9 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin ]; final Set these = {}; int combiningCount = enclosingCombiningMarks.length + nonspacingCombiningMarks.length; - if (includeSpacingCombiningMarks) + if (includeSpacingCombiningMarks) { combiningCount += spacingCombiningMarks.length; + } for (int count = 0; count < targetLength; count += 1) { int characterCode = random.nextInt(combiningCount); if (characterCode < enclosingCombiningMarks.length) { @@ -2144,7 +2157,8 @@ int randomCharacter(math.Random random) { Range(0x2f800, 0x2fa1d), ]; final Range range = pickFromList(random, characterRanges); - if (range.start == range.end) + if (range.start == range.end) { return range.start; + } return range.start + random.nextInt(range.end - range.start); } diff --git a/dev/manual_tests/test/card_collection_test.dart b/dev/manual_tests/test/card_collection_test.dart index 8632508039..8c07deb68b 100644 --- a/dev/manual_tests/test/card_collection_test.dart +++ b/dev/manual_tests/test/card_collection_test.dart @@ -18,8 +18,9 @@ void main() { await tester.pump(); // triggers a frame final Finder navigationMenu = find.byWidgetPredicate((Widget widget) { - if (widget is Tooltip) + if (widget is Tooltip) { return widget.message == 'Open navigation menu'; + } return false; }); diff --git a/dev/tools/bin/find_commit.dart b/dev/tools/bin/find_commit.dart index 1ac7c1ce48..27e6ab6b6d 100644 --- a/dev/tools/bin/find_commit.dart +++ b/dev/tools/bin/find_commit.dart @@ -13,8 +13,9 @@ import 'dart:io'; const bool debugLogging = false; void log(String message) { - if (debugLogging) + if (debugLogging) { print(message); + } } class Commit { @@ -49,15 +50,17 @@ String findCommit({ } else { final List branchCommits = Commit.parseList(git(primaryRepoDirectory, ['log', Commit.formatArgument, primaryBranch, '--'])); final List trunkCommits = Commit.parseList(git(primaryRepoDirectory, ['log', Commit.formatArgument, primaryTrunk, '--'])); - if (branchCommits.isEmpty || trunkCommits.isEmpty || branchCommits.first.hash != trunkCommits.first.hash) + if (branchCommits.isEmpty || trunkCommits.isEmpty || branchCommits.first.hash != trunkCommits.first.hash) { throw StateError('Branch $primaryBranch does not seem to have a common history with trunk $primaryTrunk.'); + } if (branchCommits.last.hash == trunkCommits.last.hash) { log('$primaryBranch is even with $primaryTrunk, using last commit as anchor'); anchor = trunkCommits.last; } else { int index = 0; - while (branchCommits.length > index && trunkCommits.length > index && branchCommits[index].hash == trunkCommits[index].hash) + while (branchCommits.length > index && trunkCommits.length > index && branchCommits[index].hash == trunkCommits[index].hash) { index += 1; + } log('$primaryBranch branched from $primaryTrunk ${branchCommits.length - index} commits ago, trunk has advanced by ${trunkCommits.length - index} commits since then.'); anchor = trunkCommits[index - 1]; } @@ -74,8 +77,9 @@ String findCommit({ String git(String workingDirectory, List arguments) { final ProcessResult result = Process.runSync('git', arguments, workingDirectory: workingDirectory); - if (result.exitCode != 0 || '${result.stderr}'.isNotEmpty) + if (result.exitCode != 0 || '${result.stderr}'.isNotEmpty) { throw ProcessException('git', arguments, '${result.stdout}${result.stderr}', result.exitCode); + } return '${result.stdout}'; } diff --git a/dev/tools/bin/generate_gradle_lockfiles.dart b/dev/tools/bin/generate_gradle_lockfiles.dart index 3c71dcc8cd..f15b23239a 100644 --- a/dev/tools/bin/generate_gradle_lockfiles.dart +++ b/dev/tools/bin/generate_gradle_lockfiles.dart @@ -24,8 +24,9 @@ void main(List arguments) { for (final String androidDirectoryPath in androidDirectories) { final Directory androidDirectory = fileSystem.directory(path.normalize(androidDirectoryPath)); - if (!androidDirectory.existsSync()) + if (!androidDirectory.existsSync()) { throw '$androidDirectory does not exist'; + } final File rootBuildGradle = androidDirectory.childFile('build.gradle'); if (!rootBuildGradle.existsSync()) { @@ -125,9 +126,10 @@ void exec( String? workingDirectory, }) { final ProcessResult result = Process.runSync(cmd, args, workingDirectory: workingDirectory); - if (result.exitCode != 0) + if (result.exitCode != 0) { throw ProcessException( cmd, args, '${result.stdout}${result.stderr}', result.exitCode); + } } const String rootGradleFileContent = r''' diff --git a/dev/tools/dartdoc.dart b/dev/tools/dartdoc.dart index 4a070cb040..28e95c179c 100644 --- a/dev/tools/dartdoc.dart +++ b/dev/tools/dartdoc.dart @@ -42,13 +42,15 @@ Future main(List arguments) async { exit(0); } // If we're run from the `tools` dir, set the cwd to the repo root. - if (path.basename(Directory.current.path) == 'tools') + if (path.basename(Directory.current.path) == 'tools') { Directory.current = Directory.current.parent.parent; + } final ProcessResult flutter = Process.runSync('flutter', []); final File versionFile = File('version'); - if (flutter.exitCode != 0 || !versionFile.existsSync()) + if (flutter.exitCode != 0 || !versionFile.existsSync()) { throw Exception('Failed to determine Flutter version.'); + } final String version = versionFile.readAsStringSync(); // Create the pubspec.yaml file. @@ -102,8 +104,9 @@ Future main(List arguments) async { printStream(process.stdout, prefix: 'pub:stdout: '); printStream(process.stderr, prefix: 'pub:stderr: '); final int code = await process.done; - if (code != 0) + if (code != 0) { exit(code); + } createFooter('$kDocsRoot/lib/', version); copyAssets(); @@ -236,8 +239,9 @@ Future main(List arguments) async { ); final int exitCode = await process.done; - if (exitCode != 0) + if (exitCode != 0) { exit(exitCode); + } sanityCheckDocs(); checkForUnresolvedDirectives('$kPublishRoot/api'); @@ -279,8 +283,9 @@ String getBranchName({ return luciBranch.trim(); } final ProcessResult gitResult = processManager.runSync(['git', 'status', '-b', '--porcelain']); - if (gitResult.exitCode != 0) + if (gitResult.exitCode != 0) { throw 'git status exit with non-zero exit code: ${gitResult.exitCode}'; + } final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch( (gitResult.stdout as String).trim().split('\n').first); return gitBranchMatch == null ? '' : gitBranchMatch.group(1)!.split('...').first; @@ -290,8 +295,9 @@ String gitRevision() { const int kGitRevisionLength = 10; final ProcessResult gitResult = Process.runSync('git', ['rev-parse', 'HEAD']); - if (gitResult.exitCode != 0) + if (gitResult.exitCode != 0) { throw 'git rev-parse exit with non-zero exit code: ${gitResult.exitCode}'; + } final String gitRevision = (gitResult.stdout as String).trim(); return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision; @@ -338,11 +344,13 @@ void createSearchMetadata(String templatePath, String metadataPath) { /// /// Creates `destDir` if needed. void copyDirectorySync(Directory srcDir, Directory destDir, [void Function(File srcFile, File destFile)? onFileCopied]) { - if (!srcDir.existsSync()) + if (!srcDir.existsSync()) { throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy'); + } - if (!destDir.existsSync()) + if (!destDir.existsSync()) { destDir.createSync(recursive: true); + } for (final FileSystemEntity entity in srcDir.listSync()) { final String newPath = path.join(destDir.path, path.basename(entity.path)); @@ -412,8 +420,9 @@ void sanityCheckDocs() { '$kPublishRoot/api/widgets/Widget-class.html', ]; for (final String canary in canaries) { - if (!File(canary).existsSync()) + if (!File(canary).existsSync()) { throw Exception('Missing "$canary", which probably means the documentation failed to build correctly.'); + } } // Make sure at least one example of each kind includes source code. @@ -523,8 +532,9 @@ List findPackages() { return Directory('packages') .listSync() .where((FileSystemEntity entity) { - if (entity is! Directory) + if (entity is! Directory) { return false; + } final File pubspec = File('${entity.path}/pubspec.yaml'); if (!pubspec.existsSync()) { print("Unexpected package '${entity.path}' found in packages directory"); @@ -560,8 +570,9 @@ void printStream(Stream> stream, { String prefix = '', List f .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { - if (!filter.any((Pattern pattern) => line.contains(pattern))) + if (!filter.any((Pattern pattern) => line.contains(pattern))) { print('$prefix$line'.trim()); + } }); } diff --git a/dev/tools/gen_defaults/lib/template.dart b/dev/tools/gen_defaults/lib/template.dart index a3f032d6cc..c21a8b2f6d 100644 --- a/dev/tools/gen_defaults/lib/template.dart +++ b/dev/tools/gen_defaults/lib/template.dart @@ -121,8 +121,9 @@ abstract class TokenTemplate { /// * [color], that provides support for looking up a raw color token. String componentColor(String componentToken) { final String colorToken = '$componentToken.color'; - if (!tokens.containsKey(colorToken)) + if (!tokens.containsKey(colorToken)) { return 'null'; + } String value = color(colorToken); final String opacityToken = '$componentToken.opacity'; if (tokens.containsKey(opacityToken)) { diff --git a/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart b/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart index c0c793e840..20a032b65d 100644 --- a/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart +++ b/dev/tools/gen_keycodes/lib/keyboard_maps_code_gen.dart @@ -13,8 +13,9 @@ import 'physical_key_data.dart'; import 'utils.dart'; bool _isAsciiLetter(String? char) { - if (char == null) + if (char == null) { return false; + } const int charUpperA = 0x41; const int charUpperZ = 0x5A; const int charLowerA = 0x61; @@ -26,8 +27,9 @@ bool _isAsciiLetter(String? char) { } bool _isDigit(String? char) { - if (char == null) + if (char == null) { return false; + } final int charDigit0 = '0'.codeUnitAt(0); final int charDigit9 = '9'.codeUnitAt(0); assert(char.length == 1); diff --git a/dev/tools/gen_keycodes/lib/logical_key_data.dart b/dev/tools/gen_keycodes/lib/logical_key_data.dart index 183ec4e4b0..4585c7f6e1 100644 --- a/dev/tools/gen_keycodes/lib/logical_key_data.dart +++ b/dev/tools/gen_keycodes/lib/logical_key_data.dart @@ -327,8 +327,9 @@ class LogicalKeyData { static void _readFuchsiaKeyCodes(Map data, PhysicalKeyData physicalData) { for (final LogicalKeyEntry entry in data.values) { final int? value = (() { - if (entry.value == 0) // "None" key + if (entry.value == 0) { return 0; + } final String? keyLabel = printable[entry.constantName]; if (keyLabel != null && !entry.constantName.startsWith('numpad')) { return toPlane(keyLabel.codeUnitAt(0), kUnicodePlane.value); @@ -339,8 +340,9 @@ class LogicalKeyData { } } })(); - if (value != null) + if (value != null) { entry.fuchsiaValues.add(value); + } } } @@ -429,8 +431,9 @@ class LogicalKeyData { })(); static int _sourceToPlane(String source, bool isPrintable) { - if (isPrintable) + if (isPrintable) { return kUnicodePlane.value; + } switch (source) { case 'DOM': return kUnprintablePlane.value; diff --git a/dev/tools/gen_keycodes/lib/utils.dart b/dev/tools/gen_keycodes/lib/utils.dart index 9e9b0b8603..1717712c74 100644 --- a/dev/tools/gen_keycodes/lib/utils.dart +++ b/dev/tools/gen_keycodes/lib/utils.dart @@ -153,8 +153,9 @@ String wrapString(String input, {required String prefix}) { /// /// An null list is considered a list with length 0. void zipStrict(Iterable list1, Iterable list2, void Function(T1, T2) fn) { - if (list1 == null && list2 == null) + if (list1 == null && list2 == null) { return; + } assert(list1.length == list2.length); final Iterator it1 = list1.iterator; final Iterator it2 = list2.iterator; @@ -208,8 +209,9 @@ Map reverseMapOfListOfString(Map> inMap, vo /// Will modify the input map. Map removeEmptyValues(Map map) { return map..removeWhere((String key, dynamic value) { - if (value == null) + if (value == null) { return true; + } if (value is Map) { final Map regularizedMap = removeEmptyValues(value); return regularizedMap.isEmpty; diff --git a/dev/tools/localization/bin/encode_kn_arb_files.dart b/dev/tools/localization/bin/encode_kn_arb_files.dart index f974215c54..541b3016d2 100644 --- a/dev/tools/localization/bin/encode_kn_arb_files.dart +++ b/dev/tools/localization/bin/encode_kn_arb_files.dart @@ -21,8 +21,9 @@ import 'package:path/path.dart' as path; import '../localizations_utils.dart'; Map _loadBundle(File file) { - if (!FileSystemEntity.isFileSync(file.path)) + if (!FileSystemEntity.isFileSync(file.path)) { exitWithError('Unable to find input file: ${file.path}'); + } return json.decode(file.readAsStringSync()) as Map; } @@ -30,8 +31,9 @@ void _encodeBundleTranslations(Map bundle) { for (final String key in bundle.keys) { // The ARB file resource "attributes" for foo are called @foo. Don't need // to encode them. - if (key.startsWith('@')) + if (key.startsWith('@')) { continue; + } final String translation = bundle[key] as String; // Rewrite the string as a series of unicode characters in JSON format. // Like "\u0012\u0123\u1234". @@ -51,8 +53,9 @@ void _checkEncodedTranslations(Map encodedBundle, Map bundle) { diff --git a/dev/tools/localization/bin/gen_date_localizations.dart b/dev/tools/localization/bin/gen_date_localizations.dart index b5954ad71a..3dd922bda5 100644 --- a/dev/tools/localization/bin/gen_date_localizations.dart +++ b/dev/tools/localization/bin/gen_date_localizations.dart @@ -101,8 +101,9 @@ import 'package:intl/date_symbols.dart' as intl; final Map objData = json.decode(data.readAsStringSync()) as Map; buffer.writeln("'$locale': intl.DateSymbols("); objData.forEach((String key, Object? value) { - if (value == null) + if (value == null) { return; + } buffer.writeln(_jsonToConstructorEntry(key, value)); }); buffer.writeln('),'); @@ -157,11 +158,13 @@ String _jsonToMapEntry(String key, dynamic value) { } String _jsonToObject(dynamic json) { - if (json == null || json is num || json is bool) + if (json == null || json is num || json is bool) { return '$json'; + } - if (json is String) + if (json is String) { return generateEncodedString(currentLocale, json); + } if (json is Iterable) { final String type = json.first.runtimeType.toString(); @@ -186,11 +189,13 @@ String _jsonToObject(dynamic json) { } String _jsonToMap(dynamic json) { - if (json == null || json is num || json is bool) + if (json == null || json is num || json is bool) { return '$json'; + } - if (json is String) + if (json is String) { return generateEncodedString(currentLocale, json); + } if (json is Iterable) { final StringBuffer buffer = StringBuffer('['); diff --git a/dev/tools/localization/bin/gen_localizations.dart b/dev/tools/localization/bin/gen_localizations.dart index fad3dc1f15..30d627088c 100644 --- a/dev/tools/localization/bin/gen_localizations.dart +++ b/dev/tools/localization/bin/gen_localizations.dart @@ -163,8 +163,9 @@ String generateArbBasedLocalizationSubclasses({ output.writeln(generateConstructor(scriptBaseLocale)); final Map scriptResources = localeToResources[scriptBaseLocale]!; for (final String key in scriptResources.keys.toList()..sort()) { - if (languageResources[key] == scriptResources[key]) + if (languageResources[key] == scriptResources[key]) { continue; + } final Map? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map?; output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale)); } @@ -172,12 +173,15 @@ String generateArbBasedLocalizationSubclasses({ final List localeCodes = languageToLocales[languageName]!..sort(); for (final LocaleInfo locale in localeCodes) { - if (locale.originalString == languageName) + if (locale.originalString == languageName) { continue; - if (locale.originalString == '${languageName}_$scriptCode') + } + if (locale.originalString == '${languageName}_$scriptCode') { continue; - if (locale.scriptCode != scriptCode) + } + if (locale.scriptCode != scriptCode) { continue; + } countryCodeCount += 1; output.writeln(generateClassDeclaration( locale, @@ -188,8 +192,9 @@ String generateArbBasedLocalizationSubclasses({ final Map localeResources = localeToResources[locale]!; for (final String key in localeResources.keys) { // When script fallback contains the key, we compare to it instead of language fallback. - if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key]) + if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key]) { continue; + } final Map? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map?; output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale)); } @@ -201,8 +206,9 @@ String generateArbBasedLocalizationSubclasses({ // doesn't exist). final List localeCodes = languageToLocales[languageName]!..sort(); for (final LocaleInfo locale in localeCodes) { - if (locale.originalString == languageName) + if (locale.originalString == languageName) { continue; + } countryCodeCount += 1; final Map localeResources = localeToResources[locale]!; output.writeln(generateClassDeclaration( @@ -212,8 +218,9 @@ String generateArbBasedLocalizationSubclasses({ )); output.writeln(generateConstructor(locale)); for (final String key in localeResources.keys) { - if (languageResources[key] == localeResources[key]) + if (languageResources[key] == localeResources[key]) { continue; + } final Map? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map?; output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale)); } @@ -223,10 +230,11 @@ String generateArbBasedLocalizationSubclasses({ final String scriptCodeMessage = scriptCodeCount == 0 ? '' : ' and $scriptCodeCount script${scriptCodeCount == 1 ? '' : 's'}'; if (countryCodeCount == 0) { - if (scriptCodeCount == 0) + if (scriptCodeCount == 0) { supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)}'); - else + } else { supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $scriptCodeCount script${scriptCodeCount == 1 ? '' : 's'})'); + } } else if (countryCodeCount == 1) { supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus one country variation$scriptCodeMessage)'); @@ -281,8 +289,9 @@ $factoryDeclaration case '$language': { switch (locale.countryCode) {'''); for (final LocaleInfo locale in languageToLocales[language]!) { - if (locale.originalString == language) + if (locale.originalString == language) { continue; + } assert(locale.length > 1); final String countryCode = locale.countryCode!; output.writeln(''' @@ -306,14 +315,17 @@ $factoryDeclaration output.writeln(''' switch (locale.countryCode) {'''); for (final LocaleInfo locale in languageToLocales[language]!) { - if (locale.countryCode == null) + if (locale.countryCode == null) { continue; - else + } else { hasCountryCode = true; - if (locale.originalString == language) + } + if (locale.originalString == language) { continue; - if (locale.scriptCode != scriptCode && locale.scriptCode != null) + } + if (locale.scriptCode != scriptCode && locale.scriptCode != null) { continue; + } final String countryCode = locale.countryCode!; output.writeln(''' case '$countryCode': @@ -335,8 +347,9 @@ $factoryDeclaration // Not Explicitly defined, fallback to first locale with the same language and // script: for (final LocaleInfo locale in languageToLocales[language]!) { - if (locale.scriptCode != scriptCode) + if (locale.scriptCode != scriptCode) { continue; + } if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) { output.writeln(''' }'''); @@ -354,11 +367,13 @@ $factoryDeclaration output.writeln(''' switch (locale.countryCode) {'''); for (final LocaleInfo locale in languageToLocales[language]!) { - if (locale.originalString == language) + if (locale.originalString == language) { continue; + } assert(locale.length > 1); - if (locale.countryCode == null) + if (locale.countryCode == null) { continue; + } final String countryCode = locale.countryCode!; output.writeln(''' case '$countryCode': @@ -412,17 +427,20 @@ String generateType(Map? attributes) { /// Used by [generateGetter] below. String generateKey(String key, Map? attributes) { if (attributes != null) { - if (attributes.containsKey('parameters')) + if (attributes.containsKey('parameters')) { return '${key}Raw'; + } switch (attributes['x-flutter-type'] as String?) { case 'icuShortTimePattern': return '${key}Raw'; } } - if (key == 'datePickerDateOrder') + if (key == 'datePickerDateOrder') { return 'datePickerDateOrderString'; - if (key == 'datePickerDateTimeOrder') + } + if (key == 'datePickerDateTimeOrder') { return 'datePickerDateTimeOrderString'; + } return key; } @@ -452,8 +470,9 @@ const Map _scriptCategoryToEnum = { /// /// Used by [generateGetter] below. String? generateValue(String? value, Map? attributes, LocaleInfo locale) { - if (value == null) + if (value == null) { return null; + } // cupertino_en.arb doesn't use x-flutter-type. if (attributes != null) { switch (attributes['x-flutter-type'] as String?) { diff --git a/dev/tools/localization/bin/gen_missing_localizations.dart b/dev/tools/localization/bin/gen_missing_localizations.dart index 98ceee274a..12ddec762d 100644 --- a/dev/tools/localization/bin/gen_missing_localizations.dart +++ b/dev/tools/localization/bin/gen_missing_localizations.dart @@ -39,8 +39,9 @@ Future main(List rawArgs) async { } Map loadBundle(File file) { - if (!FileSystemEntity.isFileSync(file.path)) + if (!FileSystemEntity.isFileSync(file.path)) { exitWithError('Unable to find input file: ${file.path}'); + } return json.decode(file.readAsStringSync()) as Map; } @@ -71,8 +72,9 @@ bool intentionallyOmitted(String key, Map bundle) { /// the same prefix and suffix "Other". bool isPluralVariation(String key, Map bundle) { final Match? pluralMatch = kPluralRegexp.firstMatch(key); - if (pluralMatch == null) + if (pluralMatch == null) { return false; + } final String prefix = pluralMatch[1]!; return bundle.containsKey('${prefix}Other'); } diff --git a/dev/tools/localization/localizations_utils.dart b/dev/tools/localization/localizations_utils.dart index 6de8bca70e..67abed175b 100644 --- a/dev/tools/localization/localizations_utils.dart +++ b/dev/tools/localization/localizations_utils.dart @@ -93,10 +93,12 @@ class LocaleInfo implements Comparable { } // Update the base string to reflect assumed scriptCodes. originalString = languageCode; - if (scriptCode != null) + if (scriptCode != null) { originalString += '_$scriptCode'; - if (countryCode != null) + } + if (countryCode != null) { originalString += '_$countryCode'; + } } return LocaleInfo( @@ -175,10 +177,11 @@ void loadMatchingArbsIntoBundleMaps({ final Map bundle = json.decode(file.readAsStringSync()) as Map; for (final String key in bundle.keys) { // The ARB file resource "attributes" for foo are called @foo. - if (key.startsWith('@')) + if (key.startsWith('@')) { attributes[key.substring(1)] = bundle[key]; - else + } else { resources[key] = bundle[key] as String; + } } } // Only pre-assume scriptCode if there is a country or script code to assume off of. @@ -288,15 +291,17 @@ Map> _parseSection(String section) { final Map> result = >{}; late List lastHeading; for (final String line in section.split('\n')) { - if (line == '') + if (line == '') { continue; + } if (line.startsWith(' ')) { lastHeading[lastHeading.length - 1] = '${lastHeading.last}${line.substring(1)}'; continue; } final int colon = line.indexOf(':'); - if (colon <= 0) + if (colon <= 0) { throw 'not sure how to deal with "$line"'; + } final String name = line.substring(0, colon); final String value = line.substring(colon + 2); lastHeading = result.putIfAbsent(name, () => []); @@ -324,14 +329,18 @@ void precacheLanguageAndRegionTags() { assert(section.containsKey('Subtag') && section.containsKey('Description'), section.toString()); final String subtag = section['Subtag']!.single; String description = section['Description']!.join(' '); - if (description.startsWith('United ')) + if (description.startsWith('United ')) { description = 'the $description'; - if (description.contains(kParentheticalPrefix)) + } + if (description.contains(kParentheticalPrefix)) { description = description.substring(0, description.indexOf(kParentheticalPrefix)); - if (description.contains(kProvincePrefix)) + } + if (description.contains(kProvincePrefix)) { description = description.substring(0, description.indexOf(kProvincePrefix)); - if (description.endsWith(' Republic')) + } + if (description.endsWith(' Republic')) { description = 'the $description'; + } switch (type) { case 'language': _languages[subtag] = description; @@ -364,10 +373,12 @@ String describeLocale(String tag) { script = _scripts[subtags[1]]; assert(region != null && script != null); } - if (region != null) + if (region != null) { output += ', as used in $region'; - if (script != null) + } + if (script != null) { output += ', using the $script script'; + } return output; } @@ -450,8 +461,9 @@ String generateString(String value) { /// some of the localized strings contain characters that can crash Emacs on Linux. /// See packages/flutter_localizations/lib/src/l10n/README for more information. String generateEncodedString(String? locale, String value) { - if (locale != 'kn' || value.runes.every((int code) => code <= 0xFF)) + if (locale != 'kn' || value.runes.every((int code) => code <= 0xFF)) { return generateString(value); + } final String unicodeEscapes = value.runes.map((int code) => '\\u{${code.toRadixString(16)}}').join(); return "'$unicodeEscapes'"; diff --git a/dev/tools/localization/localizations_validator.dart b/dev/tools/localization/localizations_validator.dart index 0d82ab2249..4b374fc686 100644 --- a/dev/tools/localization/localizations_validator.dart +++ b/dev/tools/localization/localizations_validator.dart @@ -39,25 +39,29 @@ void validateEnglishLocalizations(File file) { final Map bundle = json.decode(file.readAsStringSync()) as Map; for (final String resourceId in bundle.keys) { - if (resourceId.startsWith('@')) + if (resourceId.startsWith('@')) { continue; + } - if (bundle['@$resourceId'] != null) + if (bundle['@$resourceId'] != null) { continue; + } bool checkPluralResource(String suffix) { final int suffixIndex = resourceId.indexOf(suffix); return suffixIndex != -1 && bundle['@${resourceId.substring(0, suffixIndex)}'] != null; } - if (kPluralSuffixes.any(checkPluralResource)) + if (kPluralSuffixes.any(checkPluralResource)) { continue; + } errorMessages.writeln('A value was not specified for @$resourceId'); } for (final String atResourceId in bundle.keys) { - if (!atResourceId.startsWith('@')) + if (!atResourceId.startsWith('@')) { continue; + } final dynamic atResourceValue = bundle[atResourceId]; final Map? atResource = @@ -69,23 +73,27 @@ void validateEnglishLocalizations(File file) { final bool optional = atResource.containsKey('optional'); final String? description = atResource['description'] as String?; - if (description == null && !optional) + if (description == null && !optional) { errorMessages.writeln('No description specified for $atResourceId'); + } final String? plural = atResource['plural'] as String?; final String resourceId = atResourceId.substring(1); if (plural != null) { final String resourceIdOther = '${resourceId}Other'; - if (!bundle.containsKey(resourceIdOther)) + if (!bundle.containsKey(resourceIdOther)) { errorMessages.writeln('Default plural resource $resourceIdOther undefined'); + } } else { - if (!optional && !bundle.containsKey(resourceId)) + if (!optional && !bundle.containsKey(resourceId)) { errorMessages.writeln('No matching $resourceId defined for $atResourceId'); + } } } - if (errorMessages.isNotEmpty) + if (errorMessages.isNotEmpty) { throw ValidationError(errorMessages.toString()); + } } /// This removes undefined localizations (localizations that aren't present in @@ -108,8 +116,9 @@ void removeUndefinedLocalizations( localeToResources.forEach((LocaleInfo locale, Map resources) { bool isPluralVariation(String key) { final Match? pluralMatch = kPluralRegexp.firstMatch(key); - if (pluralMatch == null) + if (pluralMatch == null) { return false; + } final String? prefix = pluralMatch[1]; return resources.containsKey('${prefix}Other'); } @@ -151,8 +160,9 @@ void validateLocalizations( // require them so long as the "Other" variation exists. bool isPluralVariation(String key) { final Match? pluralMatch = kPluralRegexp.firstMatch(key); - if (pluralMatch == null) + if (pluralMatch == null) { return false; + } final String? prefix = pluralMatch[1]; return resources.containsKey('${prefix}Other'); } @@ -176,8 +186,9 @@ void validateLocalizations( for (final String missingKey in canonicalKeys.difference(keys)) { final dynamic attribute = attributes?[missingKey]; final bool intentionallyOmitted = attribute is Map && attribute.containsKey('notUsed'); - if (!intentionallyOmitted && !isPluralVariation(missingKey)) + if (!intentionallyOmitted && !isPluralVariation(missingKey)) { missingKeys.add(missingKey); + } } if (missingKeys.isNotEmpty) { explainMissingKeys = true; diff --git a/dev/tools/mega_gallery.dart b/dev/tools/mega_gallery.dart index cf478beb2c..c0d0d69ab9 100644 --- a/dev/tools/mega_gallery.dart +++ b/dev/tools/mega_gallery.dart @@ -14,8 +14,9 @@ const int kTargetLineCount = 60 * 1024; void main(List args) { // If we're run from the `tools` dir, set the cwd to the repo root. - if (path.basename(Directory.current.path) == 'tools') + if (path.basename(Directory.current.path) == 'tools') { Directory.current = Directory.current.parent.parent; + } final ArgParser argParser = ArgParser(); argParser.addOption('out'); @@ -65,15 +66,17 @@ void main(List args) { print(' dev/integration_tests/flutter_gallery : ${getStatsFor(Directory("dev/integration_tests/flutter_gallery"))}'); final Directory lib = _dir(out, 'lib'); - if (lib.existsSync()) + if (lib.existsSync()) { lib.deleteSync(recursive: true); + } // Copy everything that's not a symlink, dot directory, or build/. _copy(source, out); // Make n - 1 copies. - for (int i = 1; i < copies; i++) + for (int i = 1; i < copies; i++) { _copyGallery(out, i); + } // Create a new entry-point. _createEntry(_file(out, 'lib/main.dart'), copies); @@ -131,19 +134,22 @@ void _copyGallery(Directory galleryDir, int index) { } void _copy(Directory source, Directory target) { - if (!target.existsSync()) + if (!target.existsSync()) { target.createSync(recursive: true); + } for (final FileSystemEntity entity in source.listSync(followLinks: false)) { final String name = path.basename(entity.path); if (entity is Directory) { - if (name == 'build' || name.startsWith('.')) + if (name == 'build' || name.startsWith('.')) { continue; + } _copy(entity, Directory(path.join(target.path, name))); } else if (entity is File) { - if (name == '.packages' || name == 'pubspec.lock') + if (name == '.packages' || name == 'pubspec.lock') { continue; + } final File dest = File(path.join(target.path, name)); dest.writeAsBytesSync(entity.readAsBytesSync()); } @@ -181,15 +187,17 @@ SourceStats getStatsFor(Directory dir, [SourceStats? stats]) { int _lineCount(File file) { return file.readAsLinesSync().where((String line) { line = line.trim(); - if (line.isEmpty || line.startsWith('//')) + if (line.isEmpty || line.startsWith('//')) { return false; + } return true; }).length; } String _comma(int count) { final String str = count.toString(); - if (str.length > 3) + if (str.length > 3) { return '${str.substring(0, str.length - 3)},${str.substring(str.length - 3)}'; + } return str; } diff --git a/dev/tools/update_icons.dart b/dev/tools/update_icons.dart index 371056b155..41bf6745e0 100644 --- a/dev/tools/update_icons.dart +++ b/dev/tools/update_icons.dart @@ -165,8 +165,9 @@ const Set _iconsMirroredWhenRTL = { void main(List args) { // If we're run from the `tools` dir, set the cwd to the repo root. - if (path.basename(Directory.current.path) == 'tools') + if (path.basename(Directory.current.path) == 'tools') { Directory.current = Directory.current.parent.parent; + } final ArgResults argResults = _handleArguments(args); diff --git a/dev/tools/vitool/bin/main.dart b/dev/tools/vitool/bin/main.dart index 21208ff5c6..2b95399f13 100644 --- a/dev/tools/vitool/bin/main.dart +++ b/dev/tools/vitool/bin/main.dart @@ -75,11 +75,13 @@ void main(List args) { generatedSb.write('\n'); } - if (argResults['codegen_comment'] as bool) + if (argResults['codegen_comment'] as bool) { generatedSb.write(kCodegenComment); + } - if (argResults.wasParsed('part-of')) + if (argResults.wasParsed('part-of')) { generatedSb.write('part of ${argResults['part-of']};\n'); + } final Animation animation = Animation.fromFrameData(frames); generatedSb.write(animation.toDart('_AnimatedIconData', argResults['asset-name'] as String)); diff --git a/dev/tools/vitool/lib/vitool.dart b/dev/tools/vitool/lib/vitool.dart index 087b4ff8c9..90aab80aa7 100644 --- a/dev/tools/vitool/lib/vitool.dart +++ b/dev/tools/vitool/lib/vitool.dart @@ -38,18 +38,20 @@ class Animation { final int numPaths = frames[0].paths.length; for (int i = 0; i < frames.length; i += 1) { final FrameData frame = frames[i]; - if (size != frame.size) + if (size != frame.size) { throw Exception( 'All animation frames must have the same size,\n' 'first frame size was: (${size.x}, ${size.y})\n' 'frame $i size was: (${frame.size.x}, ${frame.size.y})' ); - if (numPaths != frame.paths.length) + } + if (numPaths != frame.paths.length) { throw Exception( 'All animation frames must have the same number of paths,\n' 'first frame has $numPaths paths\n' 'frame $i has ${frame.paths.length} paths' ); + } } } @@ -58,8 +60,9 @@ class Animation { sb.write('const $className $varName = const $className(\n'); sb.write('${kIndent}const Size(${size.x}, ${size.y}),\n'); sb.write('${kIndent}const <_PathFrames>[\n'); - for (final PathAnimation path in paths) + for (final PathAnimation path in paths) { sb.write(path.toDart()); + } sb.write('$kIndent],\n'); sb.write(');'); return sb.toString(); @@ -71,8 +74,9 @@ class PathAnimation { const PathAnimation(this.commands, {required this.opacities}); factory PathAnimation.fromFrameData(List frames, int pathIdx) { - if (frames.isEmpty) + if (frames.isEmpty) { return const PathAnimation([], opacities: []); + } final List commands = []; for (int commandIdx = 0; commandIdx < frames[0].paths[pathIdx].commands.length; commandIdx += 1) { @@ -82,14 +86,16 @@ class PathAnimation { for (int i = 0; i < frames.length; i += 1) { final FrameData frame = frames[i]; final String currentCommandType = frame.paths[pathIdx].commands[commandIdx].type; - if (commandType != currentCommandType) + if (commandType != currentCommandType) { throw Exception( 'Paths must be built from the same commands in all frames ' "command $commandIdx at frame 0 was of type '$commandType' " "command $commandIdx at frame $i was of type '$currentCommandType'" ); - for (int j = 0; j < numPointsInCommand; j += 1) + } + for (int j = 0; j < numPointsInCommand; j += 1) { points[j].add(frame.paths[pathIdx].commands[commandIdx].points[j]); + } } commands.add(PathCommandAnimation(commandType, points)); } @@ -114,12 +120,14 @@ class PathAnimation { final StringBuffer sb = StringBuffer(); sb.write('${kIndent * 2}const _PathFrames(\n'); sb.write('${kIndent * 3}opacities: const [\n'); - for (final double opacity in opacities) + for (final double opacity in opacities) { sb.write('${kIndent * 4}$opacity,\n'); + } sb.write('${kIndent * 3}],\n'); sb.write('${kIndent * 3}commands: const <_PathCommand>[\n'); - for (final PathCommandAnimation command in commands) + for (final PathCommandAnimation command in commands) { sb.write(command.toDart()); + } sb.write('${kIndent * 3}],\n'); sb.write('${kIndent * 2}),\n'); return sb.toString(); @@ -165,8 +173,9 @@ class PathCommandAnimation { sb.write('${kIndent * 4}const $dartCommandClass(\n'); for (final List> pointFrames in points) { sb.write('${kIndent * 5}const [\n'); - for (final Point point in pointFrames) + for (final Point point in pointFrames) { sb.write('${kIndent * 6}const Offset(${point.x}, ${point.y}),\n'); + } sb.write('${kIndent * 5}],\n'); } sb.write('${kIndent * 4}),\n'); @@ -199,8 +208,9 @@ FrameData interpretSvg(String svgFilePath) { List _interpretSvgGroup(List children, _Transform transform) { final List paths = []; for (final XmlNode node in children) { - if (node.nodeType != XmlNodeType.ELEMENT) + if (node.nodeType != XmlNodeType.ELEMENT) { continue; + } final XmlElement element = node as XmlElement; if (element.name.local == 'path') { @@ -209,13 +219,15 @@ List _interpretSvgGroup(List children, _Transform transform) { if (element.name.local == 'g') { double opacity = transform.opacity; - if (_hasAttr(element, 'opacity')) + if (_hasAttr(element, 'opacity')) { opacity *= double.parse(_extractAttr(element, 'opacity')); + } Matrix3 transformMatrix = transform.transformMatrix; - if (_hasAttr(element, 'transform')) + if (_hasAttr(element, 'transform')) { transformMatrix = transformMatrix.multiplied( _parseSvgTransform(_extractAttr(element, 'transform'))); + } final _Transform subtreeTransform = _Transform( transformMatrix: transformMatrix, @@ -266,8 +278,9 @@ class FrameData { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is FrameData && other.size == size && const ListEquality().equals(other.paths, paths); @@ -301,8 +314,9 @@ class SvgPath { final String dAttr = _extractAttr(pathElement, 'd'); final List commands = []; final SvgPathCommandBuilder commandsBuilder = SvgPathCommandBuilder(); - if (!_pathCommandValidator.hasMatch(dAttr)) + if (!_pathCommandValidator.hasMatch(dAttr)) { throw Exception('illegal or unsupported path d expression: $dAttr'); + } for (final Match match in _pathCommandMatcher.allMatches(dAttr)) { final String commandType = match.group(1)!; final String pointStr = match.group(2)!; @@ -319,8 +333,9 @@ class SvgPath { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is SvgPath && other.id == id && other.opacity == opacity @@ -369,8 +384,9 @@ class SvgPathCommand { @override bool operator ==(Object other) { - if (other.runtimeType != runtimeType) + if (other.runtimeType != runtimeType) { return false; + } return other is SvgPathCommand && other.type == type && const ListEquality>().equals(other.points, points); @@ -403,13 +419,15 @@ class SvgPathCommandBuilder { absPoints = points.map>((Point p) => p + lastPoint).toList(); } - if (type == 'M' || type == 'm') + if (type == 'M' || type == 'm') { subPathStartPoint = absPoints.last; + } - if (type == 'Z' || type == 'z') + if (type == 'Z' || type == 'z') { lastPoint = subPathStartPoint; - else + } else { lastPoint = absPoints.last; + } return SvgPathCommand(type.toUpperCase(), absPoints); } @@ -465,8 +483,9 @@ final RegExp _transformValidator = RegExp('^($_transformCommandAtom)*\$'); final RegExp _transformCommand = RegExp(_transformCommandAtom); Matrix3 _parseSvgTransform(String transform) { - if (!_transformValidator.hasMatch(transform)) + if (!_transformValidator.hasMatch(transform)) { throw Exception('illegal or unsupported transform: $transform'); + } final Iterable matches =_transformCommand.allMatches(transform).toList().reversed; Matrix3 result = Matrix3.identity(); for (final Match m in matches) { @@ -527,10 +546,11 @@ final RegExp _pixelsExp = RegExp(r'^([0-9]+)px$'); /// Parses a pixel expression, e.g "14px", and returns the number. /// Throws an [ArgumentError] if the given string doesn't match the pattern. int parsePixels(String pixels) { - if (!_pixelsExp.hasMatch(pixels)) + if (!_pixelsExp.hasMatch(pixels)) { throw ArgumentError( "illegal pixels expression: '$pixels'" ' (the tool currently only support pixel units).'); + } return int.parse(_pixelsExp.firstMatch(pixels)!.group(1)!); } diff --git a/dev/tools/vitool/test/vitool_test.dart b/dev/tools/vitool/test/vitool_test.dart index c8458badb8..a5491e9c1b 100644 --- a/dev/tools/vitool/test/vitool_test.dart +++ b/dev/tools/vitool/test/vitool_test.dart @@ -614,35 +614,43 @@ class PathMatcher extends Matcher { @override bool matches(dynamic item, Map matchState) { - if (item == null || actual == null) + if (item == null || actual == null) { return item == actual; + } - if (item.runtimeType != actual.runtimeType) + if (item.runtimeType != actual.runtimeType) { return false; + } final SvgPath other = item as SvgPath; - if (other.id != actual.id || other.opacity != actual.opacity) + if (other.id != actual.id || other.opacity != actual.opacity) { return false; + } - if (other.commands.length != actual.commands.length) + if (other.commands.length != actual.commands.length) { return false; + } for (int i = 0; i < other.commands.length; i += 1) { - if (!commandsMatch(actual.commands[i], other.commands[i])) + if (!commandsMatch(actual.commands[i], other.commands[i])) { return false; + } } return true; } bool commandsMatch(SvgPathCommand actual, SvgPathCommand other) { - if (other.points.length != actual.points.length) + if (other.points.length != actual.points.length) { return false; + } for (int i = 0; i < other.points.length; i += 1) { - if ((other.points[i].x - actual.points[i].x).abs() > margin) + if ((other.points[i].x - actual.points[i].x).abs() > margin) { return false; - if ((other.points[i].y - actual.points[i].y).abs() > margin) + } + if ((other.points[i].y - actual.points[i].y).abs() > margin) { return false; + } } return true; } @@ -658,34 +666,42 @@ class PathAnimationMatcher extends Matcher { @override bool matches(dynamic item, Map matchState) { - if (item == null || expected == null) + if (item == null || expected == null) { return item == expected; + } - if (item.runtimeType != expected.runtimeType) + if (item.runtimeType != expected.runtimeType) { return false; + } final PathAnimation other = item as PathAnimation; - if (!const ListEquality().equals(other.opacities, expected.opacities)) + if (!const ListEquality().equals(other.opacities, expected.opacities)) { return false; + } - if (other.commands.length != expected.commands.length) + if (other.commands.length != expected.commands.length) { return false; + } for (int i = 0; i < other.commands.length; i += 1) { - if (!commandsMatch(expected.commands[i], other.commands[i])) + if (!commandsMatch(expected.commands[i], other.commands[i])) { return false; + } } return true; } bool commandsMatch(PathCommandAnimation expected, PathCommandAnimation other) { - if (other.points.length != expected.points.length) + if (other.points.length != expected.points.length) { return false; + } - for (int i = 0; i < other.points.length; i += 1) - if (!const ListEquality>().equals(other.points[i], expected.points[i])) + for (int i = 0; i < other.points.length; i += 1) { + if (!const ListEquality>().equals(other.points[i], expected.points[i])) { return false; + } + } return true; } diff --git a/examples/api/analysis_options.yaml b/examples/api/analysis_options.yaml index 0b0b77874b..76be938a6b 100644 --- a/examples/api/analysis_options.yaml +++ b/examples/api/analysis_options.yaml @@ -4,7 +4,5 @@ include: ../../analysis_options.yaml linter: rules: - # Developer-facing code - curly_braces_in_flow_control_structures: true # Samples want to print things pretty often. avoid_print: false diff --git a/examples/layers/rendering/src/sector_layout.dart b/examples/layers/rendering/src/sector_layout.dart index a21533790a..11b9995634 100644 --- a/examples/layers/rendering/src/sector_layout.dart +++ b/examples/layers/rendering/src/sector_layout.dart @@ -91,8 +91,9 @@ abstract class RenderSector extends RenderObject { @override void setupParentData(RenderObject child) { - if (child.parentData is! SectorParentData) + if (child.parentData is! SectorParentData) { child.parentData = SectorParentData(); + } } // RenderSectors always use SectorParentData subclasses, as they need to be @@ -143,8 +144,9 @@ abstract class RenderSector extends RenderObject { bool hitTest(SectorHitTestResult result, { required double radius, required double theta }) { if (radius < parentData!.radius || radius >= parentData!.radius + deltaRadius || - theta < parentData!.theta || theta >= parentData!.theta + deltaTheta) + theta < parentData!.theta || theta >= parentData!.theta + deltaTheta) { return false; + } hitTestChildren(result, radius: radius, theta: theta); result.add(SectorHitTestEntry(this, radius: radius, theta: theta)); return true; @@ -162,8 +164,9 @@ abstract class RenderDecoratedSector extends RenderSector { BoxDecoration? _decoration; BoxDecoration? get decoration => _decoration; set decoration(BoxDecoration? value) { - if (value == _decoration) + if (value == _decoration) { return; + } _decoration = value; markNeedsPaint(); } @@ -175,8 +178,9 @@ abstract class RenderDecoratedSector extends RenderSector { assert(deltaTheta != null); assert(parentData is SectorParentData); - if (_decoration == null) + if (_decoration == null) { return; + } if (_decoration!.color != null) { final Canvas canvas = context.canvas; @@ -204,8 +208,9 @@ class RenderSectorWithChildren extends RenderDecoratedSector with ContainerRende void hitTestChildren(SectorHitTestResult result, { required double radius, required double theta }) { RenderSector? child = lastChild; while (child != null) { - if (child.hitTest(result, radius: radius, theta: theta)) + if (child.hitTest(result, radius: radius, theta: theta)) { return; + } final SectorChildListParentData childParentData = child.parentData! as SectorChildListParentData; child = childParentData.previousSibling; } @@ -259,8 +264,9 @@ class RenderSectorRing extends RenderSectorWithChildren { @override void setupParentData(RenderObject child) { // TODO(ianh): avoid code duplication - if (child.parentData is! SectorChildListParentData) + if (child.parentData is! SectorChildListParentData) { child.parentData = SectorChildListParentData(); + } } @override @@ -375,8 +381,9 @@ class RenderSectorSlice extends RenderSectorWithChildren { @override void setupParentData(RenderObject child) { // TODO(ianh): avoid code duplication - if (child.parentData is! SectorChildListParentData) + if (child.parentData is! SectorChildListParentData) { child.parentData = SectorChildListParentData(); + } } @override @@ -469,35 +476,40 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil @override void setupParentData(RenderObject child) { - if (child.parentData is! SectorParentData) + if (child.parentData is! SectorParentData) { child.parentData = SectorParentData(); + } } @override double computeMinIntrinsicWidth(double height) { - if (child == null) + if (child == null) { return 0.0; + } return getIntrinsicDimensions(height: height).width; } @override double computeMaxIntrinsicWidth(double height) { - if (child == null) + if (child == null) { return 0.0; + } return getIntrinsicDimensions(height: height).width; } @override double computeMinIntrinsicHeight(double width) { - if (child == null) + if (child == null) { return 0.0; + } return getIntrinsicDimensions(width: width).height; } @override double computeMaxIntrinsicHeight(double width) { - if (child == null) + if (child == null) { return 0.0; + } return getIntrinsicDimensions(width: width).height; } @@ -509,8 +521,9 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil assert(child!.parentData is SectorParentData); assert(width != null); assert(height != null); - if (!width.isFinite && !height.isFinite) + if (!width.isFinite && !height.isFinite) { return Size.zero; + } final double maxChildDeltaRadius = math.max(0.0, math.min(width, height) / 2.0 - innerRadius); final SectorDimensions childDimensions = child!.getIntrinsicDimensions(SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), innerRadius); final double dimension = (innerRadius + childDimensions.deltaRadius) * 2.0; @@ -546,8 +559,9 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil @override bool hitTest(BoxHitTestResult result, { required Offset position }) { - if (child == null) + if (child == null) { return false; + } double x = position.dx; double y = position.dy; // translate to our origin @@ -556,12 +570,15 @@ class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChil // convert to radius/theta final double radius = math.sqrt(x * x + y * y); final double theta = (math.atan2(x, -y) - math.pi / 2.0) % kTwoPi; - if (radius < innerRadius) + if (radius < innerRadius) { return false; - if (radius >= innerRadius + child!.deltaRadius) + } + if (radius >= innerRadius + child!.deltaRadius) { return false; - if (theta > child!.deltaTheta) + } + if (theta > child!.deltaTheta) { return false; + } child!.hitTest(SectorHitTestResult.wrap(result), radius: radius, theta: theta); result.add(BoxHitTestEntry(this, position)); return true; diff --git a/examples/layers/rendering/touch_input.dart b/examples/layers/rendering/touch_input.dart index 0cf9bb6e69..3747eb43df 100644 --- a/examples/layers/rendering/touch_input.dart +++ b/examples/layers/rendering/touch_input.dart @@ -94,8 +94,9 @@ class RenderDots extends RenderBox { canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFFFFFF)); // We iterate through our model and paint each dot. - for (final Dot dot in _dots.values) + for (final Dot dot in _dots.values) { dot.paint(canvas, offset); + } } } diff --git a/examples/layers/services/isolate.dart b/examples/layers/services/isolate.dart index 28fe6c9a0f..2110cc7b6b 100644 --- a/examples/layers/services/isolate.dart +++ b/examples/layers/services/isolate.dart @@ -37,8 +37,9 @@ class Calculator { int i = 0; final JsonDecoder decoder = JsonDecoder( (dynamic key, dynamic value) { - if (key is int && i++ % _NOTIFY_INTERVAL == 0) + if (key is int && i++ % _NOTIFY_INTERVAL == 0) { onProgressListener(i.toDouble(), _NUM_ITEMS.toDouble()); + } return value; }, ); @@ -56,8 +57,9 @@ class Calculator { final StringBuffer buffer = StringBuffer()..write('['); for (int i = 0; i < count; i++) { buffer.write(data); - if (i < count - 1) + if (i < count - 1) { buffer.write(','); + } } buffer.write(']'); return buffer.toString(); @@ -267,10 +269,11 @@ class IsolateExampleState extends State with SingleTickerProvide } void _handleButtonPressed() { - if (_calculationManager.isRunning) + if (_calculationManager.isRunning) { _calculationManager.stop(); - else + } else { _calculationManager.start(); + } _updateState(' ', 0.0); } diff --git a/examples/layers/services/lifecycle.dart b/examples/layers/services/lifecycle.dart index 27adcecaa4..5a60b86304 100644 --- a/examples/layers/services/lifecycle.dart +++ b/examples/layers/services/lifecycle.dart @@ -36,8 +36,9 @@ class _LifecycleWatcherState extends State @override Widget build(BuildContext context) { - if (_lastLifecycleState == null) + if (_lastLifecycleState == null) { return const Text('This widget has not observed any lifecycle changes.'); + } return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.'); } } diff --git a/examples/layers/widgets/custom_render_box.dart b/examples/layers/widgets/custom_render_box.dart index d45716c5c1..8838cbdcf9 100644 --- a/examples/layers/widgets/custom_render_box.dart +++ b/examples/layers/widgets/custom_render_box.dart @@ -31,8 +31,9 @@ class RenderDots extends RenderConstrainedBox { canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF)); final Paint paint = Paint()..color = const Color(0xFF00FF00); - for (final Offset point in _dots.values) + for (final Offset point in _dots.values) { canvas.drawCircle(point, 50.0, paint); + } super.paint(context, offset); } diff --git a/examples/layers/widgets/gestures.dart b/examples/layers/widgets/gestures.dart index 1152d4d092..c8594d97a7 100644 --- a/examples/layers/widgets/gestures.dart +++ b/examples/layers/widgets/gestures.dart @@ -130,8 +130,9 @@ class GestureDemoState extends State { void _handleColorChange() { setState(() { _swatchIndex += 1; - if (_swatchIndex == kSwatches.length) + if (_swatchIndex == kSwatches.length) { _swatchIndex = 0; + } _swatch = kSwatches[_swatchIndex]; }); } diff --git a/examples/layers/widgets/sectors.dart b/examples/layers/widgets/sectors.dart index fa3047ea22..74c7fc1975 100644 --- a/examples/layers/widgets/sectors.dart +++ b/examples/layers/widgets/sectors.dart @@ -35,10 +35,11 @@ class SectorAppState extends State { final double currentTheta = this.currentTheta; if (currentTheta < kTwoPi) { double deltaTheta; - if (currentTheta >= kTwoPi - (math.pi * 0.2 + 0.05)) + if (currentTheta >= kTwoPi - (math.pi * 0.2 + 0.05)) { deltaTheta = kTwoPi - currentTheta; - else + } else { deltaTheta = math.pi * rand.nextDouble() / 5.0 + 0.05; + } wantedSectorSizes.add(deltaTheta); updateEnabledState(); } @@ -53,8 +54,9 @@ class SectorAppState extends State { void doUpdates() { int index = 0; - while (index < actualSectorSizes.length && index < wantedSectorSizes.length && actualSectorSizes[index] == wantedSectorSizes[index]) + while (index < actualSectorSizes.length && index < wantedSectorSizes.length && actualSectorSizes[index] == wantedSectorSizes[index]) { index += 1; + } final RenderSectorRing ring = sectors.child! as RenderSectorRing; while (index < actualSectorSizes.length) { ring.remove(ring.lastChild!); diff --git a/packages/analysis_options.yaml b/packages/analysis_options.yaml index e2f23b14f0..3f0e82867e 100644 --- a/packages/analysis_options.yaml +++ b/packages/analysis_options.yaml @@ -5,6 +5,5 @@ include: ../analysis_options.yaml linter: rules: - - curly_braces_in_flow_control_structures # Developer-facing code - public_member_api_docs # see https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#documentation-dartdocs-javadocs-etc - no_runtimeType_toString # use objectRuntimeType from package:foundation diff --git a/packages/flutter_tools/analysis_options.yaml b/packages/flutter_tools/analysis_options.yaml index e2608f7084..ad36811716 100644 --- a/packages/flutter_tools/analysis_options.yaml +++ b/packages/flutter_tools/analysis_options.yaml @@ -4,7 +4,6 @@ linter: rules: avoid_catches_without_on_clauses: true avoid_catching_errors: false # TODO(ianh): we should refactor the tool codebase to avoid relying on this so much - curly_braces_in_flow_control_structures: true library_private_types_in_public_api: false # Tool does not have any public API. no_runtimeType_toString: false # We use runtimeType for debugging in the tool. only_throw_errors: true diff --git a/packages/flutter_tools/test/integration.shard/overall_experience_test.dart b/packages/flutter_tools/test/integration.shard/overall_experience_test.dart index d43da2b545..c373871f94 100644 --- a/packages/flutter_tools/test/integration.shard/overall_experience_test.dart +++ b/packages/flutter_tools/test/integration.shard/overall_experience_test.dart @@ -518,7 +518,7 @@ void main() { 'A RenderFlex overflowed by 69200 pixels on the right.', '', 'The relevant error-causing widget was:', - matches(RegExp(r'^ Row .+flutter/dev/integration_tests/ui/lib/overflow\.dart:31:12$')), + matches(RegExp(r'^ Row .+flutter/dev/integration_tests/ui/lib/overflow\.dart:32:12$')), '', 'To inspect this widget in Flutter DevTools, visit:', startsWith('http'),