diff --git a/analysis_options.yaml b/analysis_options.yaml index c5d8facf6bc..5c20c572edb 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -141,7 +141,7 @@ linter: - prefer_equal_for_default_values # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods - prefer_final_fields - # - prefer_final_in_for_each # not yet tested + - prefer_final_in_for_each - prefer_final_locals # - prefer_for_elements_to_map_fromIterable # not yet tested - prefer_foreach diff --git a/dev/benchmarks/macrobenchmarks/lib/src/cubic_bezier.dart b/dev/benchmarks/macrobenchmarks/lib/src/cubic_bezier.dart index 766c69794d4..90ca20afd6d 100644 --- a/dev/benchmarks/macrobenchmarks/lib/src/cubic_bezier.dart +++ b/dev/benchmarks/macrobenchmarks/lib/src/cubic_bezier.dart @@ -146,7 +146,7 @@ class AnimatedBezierState extends State path.moveTo(100.0, 97.0); - for (Point p in pointList[0]) { + for (final Point p in pointList[0]) { path.lineTo(p.x, p.y); } @@ -167,7 +167,7 @@ class AnimatedBezierState extends State bezier2Path.moveTo(0.0, 70.55); - for (Point p in pointList[1]) { + for (final Point p in pointList[1]) { bezier2Path.lineTo(p.x, p.y); } @@ -188,7 +188,7 @@ class AnimatedBezierState extends State bezier3Path.moveTo(0.0, 69.48); - for (Point p in pointList[2]) { + for (final Point p in pointList[2]) { bezier3Path.lineTo(p.x, p.y); } @@ -210,7 +210,7 @@ class AnimatedBezierState extends State bezier4Path.moveTo(0.0, 69.48); - for (Point p in pointList[3]) { + for (final Point p in pointList[3]) { bezier4Path.lineTo(p.x, p.y); } @@ -221,7 +221,7 @@ class AnimatedBezierState extends State } List _playReversed() { - for (List list in pointList) { + for (final List list in pointList) { if (list.isNotEmpty) { list.removeLast(); } @@ -232,7 +232,7 @@ class AnimatedBezierState extends State path.moveTo(100.0, 97.0); - for (Point point in points) { + for (final Point point in points) { path.lineTo(point.x, point.y); } @@ -240,14 +240,14 @@ class AnimatedBezierState extends State bezier2Path.moveTo(0.0, 70.55); - for (Point p in pointList[1]) { + for (final Point p in pointList[1]) { bezier2Path.lineTo(p.x, p.y); } final Path bezier3Path = Path(); bezier3Path.moveTo(0.0, 69.48); - for (Point p in pointList[2]) { + for (final Point p in pointList[2]) { bezier3Path.lineTo(p.x, p.y); } @@ -255,7 +255,7 @@ class AnimatedBezierState extends State bezier4Path.moveTo(0.0, 69.48); - for (Point p in pointList[3]) { + for (final Point p in pointList[3]) { bezier4Path.lineTo(p.x, p.y); } @@ -287,7 +287,7 @@ class AnimatedBezierState extends State void playAnimation() { isPlaying = true; isReversed = false; - for (List list in pointList) { + for (final List list in pointList) { list.clear(); } controller.reset(); @@ -297,7 +297,7 @@ class AnimatedBezierState extends State void stopAnimation() { isPlaying = false; controller.stop(); - for (List list in pointList) { + for (final List list in pointList) { list.clear(); } } diff --git a/dev/benchmarks/microbenchmarks/lib/common.dart b/dev/benchmarks/microbenchmarks/lib/common.dart index 0fa0e8adc3a..62a08fd4675 100644 --- a/dev/benchmarks/microbenchmarks/lib/common.dart +++ b/dev/benchmarks/microbenchmarks/lib/common.dart @@ -51,7 +51,7 @@ class BenchmarkResultPrinter { String _printJson() { final Map results = {}; - for (_BenchmarkResult result in _results) { + for (final _BenchmarkResult result in _results) { results[result.name] = result.value; } return json.encode(results); @@ -59,7 +59,7 @@ class BenchmarkResultPrinter { String _printPlainText() { final StringBuffer buf = StringBuffer(); - for (_BenchmarkResult result in _results) { + for (final _BenchmarkResult result in _results) { buf.writeln('${result.description}: ${result.value.toStringAsFixed(1)} ${result.unit}'); } return buf.toString(); diff --git a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart index 93a4c2f6ef6..cfd1546fb10 100644 --- a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart @@ -16,7 +16,7 @@ void main() { print('Velocity tracker benchmark...'); watch.start(); for (int i = 0; i < _kNumIters; i += 1) { - for (PointerEvent event in velocityEventData) { + for (final PointerEvent event in velocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) tracker.addPosition(event.timeStamp, event.position); if (event is PointerUpEvent) diff --git a/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart b/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart index b7572215014..dba12ac1b71 100644 --- a/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/language/sync_star_bench.dart @@ -84,7 +84,7 @@ Iterable generateIterableList() { int sumIterable(Iterable values) { int result = 0; - for (int value in values) { + for (final int value in values) { result += value; } return result; diff --git a/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart b/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart index c5ffc2f7f61..0672841bfde 100644 --- a/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/language/sync_star_semantics_bench.dart @@ -71,7 +71,7 @@ void main() { String consumeSpan(Iterable items) { String result = ''; - for (InlineSpanSemanticsInformation span in items) { + for (final InlineSpanSemanticsInformation span in items) { result += span.text; } return result; @@ -81,7 +81,7 @@ String consumeSpan(Iterable items) { Iterable combineSemanticsInfoSyncStar(List inputs) sync* { String workingText = ''; String workingLabel; - for (InlineSpanSemanticsInformation info in inputs) { + for (final InlineSpanSemanticsInformation info in inputs) { if (info.requiresOwnNode) { if (workingText != null) { yield InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText); @@ -110,7 +110,7 @@ Iterable combineSemanticsInfoList(List result = []; - for (InlineSpanSemanticsInformation info in inputs) { + for (final InlineSpanSemanticsInformation info in inputs) { if (info.requiresOwnNode) { if (workingText != null) { result.add(InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText)); diff --git a/dev/bots/analyze-sample-code.dart b/dev/bots/analyze-sample-code.dart index f4422340f7d..2957f26ccf1 100644 --- a/dev/bots/analyze-sample-code.dart +++ b/dev/bots/analyze-sample-code.dart @@ -193,7 +193,7 @@ class SampleChecker { "import 'dart:typed_data';", "import 'dart:ui' as ui;", "import 'package:flutter_test/flutter_test.dart';", - for (File file in _listDartFiles(Directory(_defaultFlutterPackage))) ...[ + for (final File file in _listDartFiles(Directory(_defaultFlutterPackage))) ...[ '', '// ${file.path}', "import 'package:flutter/${path.basename(file.path)}';", @@ -214,7 +214,7 @@ class SampleChecker { errors = _analyze(_tempDirectory, sections, snippets); } finally { if (errors.isNotEmpty) { - for (String filePath in errors.keys) { + for (final String filePath in errors.keys) { errors[filePath].forEach(stderr.writeln); } stderr.writeln('\nFound ${errors.length} sample code errors.'); @@ -310,7 +310,7 @@ class SampleChecker { final List
sections =
[]; final List snippets = []; - for (File file in _listDartFiles(_flutterPackage, recursive: true)) { + for (final File file in _listDartFiles(_flutterPackage, recursive: true)) { final String relativeFilePath = path.relative(file.path, from: _flutterPackage.path); final List sampleLines = file.readAsLinesSync(); final List
preambleSections =
[]; @@ -326,7 +326,7 @@ class SampleChecker { final List block = []; List snippetArgs = []; Line startLine; - for (String line in sampleLines) { + for (final String line in sampleLines) { lineNumber += 1; final String trimmedLine = line.trim(); if (inSnippet) { @@ -434,10 +434,10 @@ class SampleChecker { } } print('Found ${sections.length} sample code sections.'); - for (Section section in sections) { + for (final Section section in sections) { sectionMap[_writeSection(section).path] = section; } - for (Snippet snippet in snippets) { + for (final Snippet snippet in snippets) { final File snippetFile = _writeSnippet(snippet); snippet.contents = snippetFile.readAsLinesSync(); snippetMap[snippetFile.absolute.path] = snippet; @@ -576,7 +576,7 @@ linter: ); bool unknownAnalyzerErrors = false; final int headerLength = headers.length + 2; - for (String error in errors) { + for (final String error in errors) { final Match parts = errorPattern.matchAsPrefix(error); if (parts != null) { final String message = parts[2]; @@ -860,7 +860,7 @@ class Snippet { String toString() { final StringBuffer buf = StringBuffer('snippet ${args.join(' ')}\n'); int count = start.line; - for (String line in input) { + for (final String line in input) { buf.writeln(' ${count.toString().padLeft(4, ' ')}: $line'); count++; } diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index 1da04580298..f4a703c146a 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -147,11 +147,11 @@ final RegExp _grandfatheredDeprecation = RegExp(r' // ignore: flutter_deprecatio Future verifyDeprecations(String workingDirectory, { int minimumMatches = 2000 }) async { final List errors = []; - for (File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { + for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { int lineNumber = 0; final List lines = file.readAsLinesSync(); final List linesWithDeprecations = []; - for (String line in lines) { + for (final String line in lines) { if (line.contains(_findDeprecationPattern) && !line.endsWith(_ignoreDeprecation) && !line.contains(_grandfatheredDeprecation)) { @@ -239,7 +239,7 @@ Future _verifyNoMissingLicenseForExtension(String workingDirectory, String assert(!license.endsWith('\n')); final String licensePattern = license + '\n' + (trailingBlank ? '\n' : ''); final List errors = []; - for (File file in _allFiles(workingDirectory, extension, minimumMatches: minimumMatches)) { + for (final File file in _allFiles(workingDirectory, extension, minimumMatches: minimumMatches)) { final String contents = file.readAsStringSync().replaceAll('\r\n', '\n'); if (contents.isEmpty) continue; // let's not go down the /bin/true rabbit hole @@ -270,8 +270,8 @@ Future verifyNoTestImports(String workingDirectory) async { final List errors = []; assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern)); final List dartFiles = _allFiles(path.join(workingDirectory, 'packages'), 'dart', minimumMatches: 1500).toList(); - for (File file in dartFiles) { - for (String line in file.readAsLinesSync()) { + 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))) errors.add(file.path); @@ -365,7 +365,7 @@ Future verifyGeneratedPluginRegistrants(String flutterRoot) async { final Map> packageToRegistrants = >{}; - for (File file in flutterRootDir.listSync(recursive: true).whereType().where(_isGeneratedPluginRegistrant)) { + for (final File file in flutterRootDir.listSync(recursive: true).whereType().where(_isGeneratedPluginRegistrant)) { final String package = _getPackageFor(file, flutterRootDir); final List registrants = packageToRegistrants.putIfAbsent(package, () => []); registrants.add(file); @@ -373,16 +373,16 @@ Future verifyGeneratedPluginRegistrants(String flutterRoot) async { final Set outOfDate = {}; - for (String package in packageToRegistrants.keys) { + for (final String package in packageToRegistrants.keys) { final Map fileToContent = {}; - for (File f in packageToRegistrants[package]) { + for (final File f in packageToRegistrants[package]) { fileToContent[f] = f.readAsStringSync(); } await runCommand(flutter, ['inject-plugins'], workingDirectory: package, outputMode: OutputMode.discard, ); - for (File registrant in fileToContent.keys) { + for (final File registrant in fileToContent.keys) { if (registrant.readAsStringSync() != fileToContent[registrant]) { outOfDate.add(registrant.path); } @@ -422,20 +422,20 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { } // Verify that the imports are well-ordered. final Map> dependencyMap = >{}; - for (String directory in directories) { + for (final String directory in directories) { dependencyMap[directory] = _findFlutterDependencies(path.join(srcPath, directory), errors, checkForMeta: directory != 'foundation'); } assert(dependencyMap['material'].contains('widgets') && dependencyMap['widgets'].contains('rendering') && dependencyMap['rendering'].contains('painting')); // to make sure we're convinced _findFlutterDependencies is finding some - for (String package in dependencyMap.keys) { + for (final String package in dependencyMap.keys) { if (dependencyMap[package].contains(package)) { errors.add( 'One of the files in the $yellow$package$reset package imports that package recursively.' ); } } - for (String package in dependencyMap.keys) { + for (final String package in dependencyMap.keys) { final List loop = _deepSearch(dependencyMap, package); if (loop != null) { errors.add( @@ -459,7 +459,7 @@ Future verifyNoBadImportsInFlutter(String workingDirectory) async { Future verifyNoBadImportsInFlutterTools(String workingDirectory) async { final List errors = []; final List files = _allFiles(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'), 'dart', minimumMatches: 200).toList(); - for (File file in files) { + for (final File file in files) { if (file.readAsStringSync().contains('package:flutter_tools/')) { errors.add('$yellow${file.path}$reset imports flutter_tools.'); } @@ -535,7 +535,7 @@ Future verifyNoTrailingSpaces(String workingDirectory, { int minimumMatche .where((File file) => path.extension(file.path) != '.jar') .toList(); final List problems = []; - for (File file in files) { + for (final File file in files) { final List lines = file.readAsLinesSync(); for (int index = 0; index < lines.length; index += 1) { if (lines[index].endsWith(' ')) { @@ -1004,7 +1004,7 @@ Future verifyNoBinaries(String workingDirectory, { Set grandfathe .map((String filename) => File(path.join(workingDirectory, filename))) .toList(); final List problems = []; - for (File file in files) { + for (final File file in files) { final Uint8List bytes = file.readAsBytesSync(); try { utf8.decode(bytes); @@ -1156,7 +1156,7 @@ Set _findFlutterDependencies(String srcPath, List errors, { bool return _allFiles(srcPath, 'dart', minimumMatches: 1) .map>((File file) { final Set result = {}; - for (String line in file.readAsLinesSync()) { + for (final String line in file.readAsLinesSync()) { Match match = _importPattern.firstMatch(line); if (match != null) result.add(match.group(2)); @@ -1180,7 +1180,7 @@ Set _findFlutterDependencies(String srcPath, List errors, { bool } List _deepSearch(Map> map, T start, [ Set seen ]) { - for (T key in map[start]) { + for (final T key in map[start]) { if (key == start) continue; // we catch these separately if (seen != null && seen.contains(key)) diff --git a/dev/bots/flutter_compact_formatter.dart b/dev/bots/flutter_compact_formatter.dart index 5a4bbf62154..0b5552c1ee1 100644 --- a/dev/bots/flutter_compact_formatter.dart +++ b/dev/bots/flutter_compact_formatter.dart @@ -160,7 +160,7 @@ class FlutterCompactFormatter { void finish() { final List skipped = []; final List failed = []; - for (TestResult result in _tests.values) { + for (final TestResult result in _tests.values) { switch (result.status) { case TestStatus.started: failed.add('${_red}Unexpectedly failed to complete a test!'); diff --git a/dev/bots/prepare_package.dart b/dev/bots/prepare_package.dart index ce9bad72e67..b45bb1d6d66 100644 --- a/dev/bots/prepare_package.dart +++ b/dev/bots/prepare_package.dart @@ -354,7 +354,7 @@ class ArchiveCreator { // Create each of the templates, since they will call 'pub get' on // themselves when created, and this will warm the cache with their // dependencies too. - for (String template in ['app', 'package', 'plugin']) { + for (final String template in ['app', 'package', 'plugin']) { final String createName = path.join(tempDir.path, 'create_$template'); await _runFlutter( ['create', '--template=$template', createName], @@ -528,7 +528,7 @@ class ArchivePublisher { // Search for any entries with the same hash and channel and remove them. final List releases = jsonData['releases'] as List; jsonData['releases'] = >[ - for (Map entry in releases.cast>()) + for (final Map entry in releases.cast>()) if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel']) entry, newEntry, diff --git a/dev/bots/run_command.dart b/dev/bots/run_command.dart index 14070670576..2577433f36b 100644 --- a/dev/bots/run_command.dart +++ b/dev/bots/run_command.dart @@ -37,7 +37,7 @@ Stream runAndGetStdout(String executable, List arguments, { stderr.addStream(process.stderr); final Stream lines = process.stdout.transform(utf8.decoder).transform(const LineSplitter()); - await for (String line in lines) + await for (final String line in lines) yield line; final int exitCode = await process.exitCode; diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 05fee88c753..92fd621b060 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -295,7 +295,7 @@ const List _excludedExampleApplications = [ /// target app. Future _runBuildTests() async { final Stream exampleDirectories = Directory(path.join(flutterRoot, 'examples')).list(); - await for (FileSystemEntity fileEntity in exampleDirectories) { + await for (final FileSystemEntity fileEntity in exampleDirectories) { if (fileEntity is! Directory) { continue; } @@ -817,7 +817,7 @@ Future _runHostOnlyDeviceLabTests() async { last = '_last'; } subshards['$subshard$last'] = () async { - for (ShardRunner test in sublist) + for (final ShardRunner test in sublist) await test(); }; } @@ -1020,7 +1020,7 @@ Future _runFromList(Map items, String key, String nam item = parts[positionInTaskName]; } if (item == null) { - for (String currentItem in items.keys) { + for (final String currentItem in items.keys) { print('$bold$key=$currentItem$reset'); await items[currentItem](); print(''); diff --git a/dev/bots/test/fake_process_manager.dart b/dev/bots/test/fake_process_manager.dart index 521e8c25e63..04d2317225c 100644 --- a/dev/bots/test/fake_process_manager.dart +++ b/dev/bots/test/fake_process_manager.dart @@ -34,7 +34,7 @@ class FakeProcessManager extends Mock implements ProcessManager { Map> get fakeResults => _fakeResults; set fakeResults(Map> value) { _fakeResults = >{}; - for (String key in value.keys) { + for (final String key in value.keys) { _fakeResults[key] = (value[key] ?? [ProcessResult(0, 0, '', '')]).toList(); } } @@ -46,7 +46,7 @@ class FakeProcessManager extends Mock implements ProcessManager { /// parameters were in the same order. void verifyCalls(List calls) { int index = 0; - for (String call in calls) { + for (final String call in calls) { expect(call.split(' '), orderedEquals(invocations[index].positionalArguments[0] as Iterable)); index++; } @@ -178,7 +178,7 @@ class StringStreamConsumer implements StreamConsumer> { @override Future close() async { - for (Completer completer in completers) { + for (final Completer completer in completers) { await completer.future; } completers.clear(); diff --git a/dev/bots/test/fake_process_manager_test.dart b/dev/bots/test/fake_process_manager_test.dart index b74576c83af..6782c02d34c 100644 --- a/dev/bots/test/fake_process_manager_test.dart +++ b/dev/bots/test/fake_process_manager_test.dart @@ -34,7 +34,7 @@ void main() { ], }; processManager.fakeResults = calls; - for (String key in calls.keys) { + for (final String key in calls.keys) { final Process process = await processManager.start(key.split(' ')); String output = ''; process.stdout.listen((List item) { @@ -56,7 +56,7 @@ void main() { ], }; processManager.fakeResults = calls; - for (String key in calls.keys) { + for (final String key in calls.keys) { final ProcessResult result = await processManager.run(key.split(' ')); expect(result.stdout, equals(calls[key][0].stdout)); } @@ -73,7 +73,7 @@ void main() { ], }; processManager.fakeResults = calls; - for (String key in calls.keys) { + for (final String key in calls.keys) { final ProcessResult result = processManager.runSync(key.split(' ')); expect(result.stdout, equals(calls[key][0].stdout)); } @@ -90,7 +90,7 @@ void main() { ], }; processManager.fakeResults = calls; - for (String key in calls.keys) { + for (final String key in calls.keys) { final Process process = await processManager.start(key.split(' ')); String output = ''; process.stdout.listen((List item) { diff --git a/dev/bots/test/prepare_package_test.dart b/dev/bots/test/prepare_package_test.dart index b7054fecae1..9f4a122fc6c 100644 --- a/dev/bots/test/prepare_package_test.dart +++ b/dev/bots/test/prepare_package_test.dart @@ -35,7 +35,7 @@ void main() { ); } }); - for (String platformName in ['macos', 'linux', 'windows']) { + for (final String platformName in ['macos', 'linux', 'windows']) { final FakePlatform platform = FakePlatform( operatingSystem: platformName, environment: { diff --git a/dev/bots/test/test_test.dart b/dev/bots/test/test_test.dart index ce2e3fb7b3e..debf9ca52ed 100644 --- a/dev/bots/test/test_test.dart +++ b/dev/bots/test/test_test.dart @@ -27,7 +27,7 @@ void main() { '1.2.3+hotfix.1', '1.2.3+hotfix.12-pre.12', ]; - for (String version in valid_versions) { + for (final String version in valid_versions) { when(file.readAsString()).thenAnswer((Invocation invocation) => Future.value(version)); expect( await verifyVersion(file), @@ -47,7 +47,7 @@ void main() { ' 1.2.3', '1.2.3-hotfix.1', ]; - for (String version in invalid_versions) { + for (final String version in invalid_versions) { when(file.readAsString()).thenAnswer((Invocation invocation) => Future.value(version)); expect( await verifyVersion(file), diff --git a/dev/bots/unpublish_package.dart b/dev/bots/unpublish_package.dart index 3da5bf6f00e..581cd8f66c9 100644 --- a/dev/bots/unpublish_package.dart +++ b/dev/bots/unpublish_package.dart @@ -254,7 +254,7 @@ class ArchiveUnpublisher { return bDate.compareTo(aDate); }); jsonData['releases'] = releases; - for (Channel channel in channels) { + for (final Channel channel in channels) { if (!revisionsBeingRemoved.contains(jsonData['current_release'][getChannelName(channel)])) { // Don't replace the current release if it's not one of the revisions we're removing. continue; @@ -276,7 +276,7 @@ class ArchiveUnpublisher { Future>> _getArchivePaths(List> releases) async { final Set hashes = {}; final Map> paths = >{}; - for (Map revision in releases) { + for (final Map revision in releases) { final String hash = revision['hash']; final Channel channel = fromChannelName(revision['channel']); hashes.add(hash); @@ -350,9 +350,9 @@ class ArchiveUnpublisher { Future _cloudRemoveArchive(Map> paths) async { final List files = []; print('${confirmed ? 'Removing' : 'Would remove'} the following release archives:'); - for (Channel channel in paths.keys) { + for (final Channel channel in paths.keys) { final Map hashes = paths[channel]; - for (String hash in hashes.keys) { + for (final String hash in hashes.keys) { final String file = '$gsReleaseFolder/${hashes[hash]}'; files.add(file); print(' $file'); @@ -464,7 +464,7 @@ Future main(List rawArguments) async { if (revisions.isEmpty) { errorExit('Invalid argument: at least one --revision must be specified.'); } - for (String revision in revisions) { + for (final String revision in revisions) { if (revision.length != 40) { errorExit('Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.'); } @@ -500,7 +500,7 @@ Future main(List rawArguments) async { String message; String stack; try { - for (PublishedPlatform platform in platforms) { + for (final PublishedPlatform platform in platforms) { final ArchiveUnpublisher publisher = ArchiveUnpublisher( tempDir, revisions.toSet(), diff --git a/dev/customer_testing/run_tests.dart b/dev/customer_testing/run_tests.dart index 008789206c0..62133a4fd9e 100644 --- a/dev/customer_testing/run_tests.dart +++ b/dev/customer_testing/run_tests.dart @@ -102,7 +102,7 @@ Future run(List arguments) async { print(''); } - for (File file in files) { + for (final File file in files) { if (verbose) print('Processing ${file.path}...'); TestFile instructions; @@ -127,7 +127,7 @@ Future run(List arguments) async { try { bool success; bool showContacts = false; - for (String fetchCommand in instructions.fetch) { + for (final String fetchCommand in instructions.fetch) { success = await shell(fetchCommand, checkout, verbose: verbose, silentFailure: skipOnFetchFailure); if (!success) { if (skipOnFetchFailure) { @@ -153,7 +153,7 @@ Future run(List arguments) async { for (int iteration = 0; iteration < repeat; iteration += 1) { if (verbose && repeat > 1) print('Round ${iteration + 1} of $repeat.'); - for (String testCommand in instructions.tests) { + for (final String testCommand in instructions.tests) { success = await shell(testCommand, tests, verbose: verbose); if (!success) { print('ERROR: One or more tests from ${path.basenameWithoutExtension(file.path)} failed.'); @@ -197,7 +197,7 @@ class TestFile { final List fetch = []; final List update = []; final List test = []; - for (String line in file.readAsLinesSync().map((String line) => line.trim())) { + for (final String line in file.readAsLinesSync().map((String line) => line.trim())) { if (line.isEmpty) { // blank line } else if (line.startsWith('#')) { @@ -228,7 +228,7 @@ class TestFile { } if (contacts.isEmpty) throw FormatException('${errorPrefix}No contacts specified. At least one contact e-mail address must be specified.'); - for (String email in contacts) { + 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'); } diff --git a/dev/devicelab/bin/run.dart b/dev/devicelab/bin/run.dart index 9eaa691f399..cc2af6221c9 100644 --- a/dev/devicelab/bin/run.dart +++ b/dev/devicelab/bin/run.dart @@ -59,7 +59,7 @@ Future main(List rawArgs) async { final String localEngine = args['local-engine'] as String; final String localEngineSrcPath = args['local-engine-src-path'] as String; - for (String taskName in _taskNames) { + for (final String taskName in _taskNames) { section('Running task "$taskName"'); final Map result = await runTask( taskName, @@ -95,7 +95,7 @@ void addTasks({ } // Only start skipping if user specified a task to continue from final String stage = args['stage'] as String; - for (ManifestTask task in tasks) { + for (final ManifestTask task in tasks) { final bool isQualifyingStage = stage == null || task.stage == stage; final bool isQualifyingHost = !(args['match-host-platform'] as bool) || task.isSupportedByHost(); if (isQualifyingHost && isQualifyingStage) { @@ -116,7 +116,7 @@ final ArgParser _argParser = ArgParser() '\n' 'This option may be repeated to specify multiple tasks.', callback: (List value) { - for (String nameOrPath in value) { + for (final String nameOrPath in value) { final List fragments = path.split(nameOrPath); final bool isDartFile = fragments.last.endsWith('.dart'); diff --git a/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart b/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart index 99e6c0e5a59..726ea1708dc 100644 --- a/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart +++ b/dev/devicelab/bin/tasks/build_ios_framework_module_test.dart @@ -114,7 +114,7 @@ Future main() async { section('Check profile, release builds has Dart AOT dylib'); - for (String mode in ['Profile', 'Release']) { + for (final String mode in ['Profile', 'Release']) { final String appFrameworkPath = path.join( outputPath, mode, @@ -159,7 +159,7 @@ Future main() async { section("Check all modes' engine dylib"); - for (String mode in ['Debug', 'Profile', 'Release']) { + for (final String mode in ['Debug', 'Profile', 'Release']) { final String engineFrameworkPath = path.join( outputPath, mode, @@ -194,7 +194,7 @@ Future main() async { section("Check all modes' engine header"); - for (String mode in ['Debug', 'Profile', 'Release']) { + for (final String mode in ['Debug', 'Profile', 'Release']) { checkFileContains( ['#include "FlutterEngine.h"'], path.join(outputPath, mode, 'Flutter.framework', 'Headers', 'Flutter.h'), @@ -203,7 +203,7 @@ Future main() async { section("Check all modes' have plugin dylib"); - for (String mode in ['Debug', 'Profile', 'Release']) { + for (final String mode in ['Debug', 'Profile', 'Release']) { final String pluginFrameworkPath = path.join( outputPath, mode, @@ -237,7 +237,7 @@ Future main() async { section("Check all modes' have generated plugin registrant"); - for (String mode in ['Debug', 'Profile', 'Release']) { + for (final String mode in ['Debug', 'Profile', 'Release']) { final String registrantFrameworkPath = path.join( outputPath, mode, diff --git a/dev/devicelab/bin/tasks/dartdocs.dart b/dev/devicelab/bin/tasks/dartdocs.dart index 3bcaff66484..4173a7b54bd 100644 --- a/dev/devicelab/bin/tasks/dartdocs.dart +++ b/dev/devicelab/bin/tasks/dartdocs.dart @@ -40,7 +40,7 @@ Future main() async { print('^ not sure what to do with that line ^'); } } - await for (String entry in analysis.stderr.transform(utf8.decoder).transform(const LineSplitter())) { + await for (final String entry in analysis.stderr.transform(utf8.decoder).transform(const LineSplitter())) { print('analyzer stderr: $entry'); if (entry.contains(' (ran in ') && !sawFinalLine) { // ignore this line once diff --git a/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart b/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart index e201e52d10c..8bf7c0a96fc 100644 --- a/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart +++ b/dev/devicelab/bin/tasks/flutter_gallery__transition_perf_with_semantics.dart @@ -16,7 +16,7 @@ Future main() async { final List benchmarkScoreKeys = []; final Map data = {}; - for (String key in withSemantics.benchmarkScoreKeys) { + for (final String key in withSemantics.benchmarkScoreKeys) { final String deltaKey = 'delta_$key'; data[deltaKey] = withSemantics.data[key] - withoutSemantics.data[key]; data['semantics_$key'] = withSemantics.data[key]; diff --git a/dev/devicelab/bin/tasks/flutter_test_performance.dart b/dev/devicelab/bin/tasks/flutter_test_performance.dart index cba5b254176..540fdb5a3e4 100644 --- a/dev/devicelab/bin/tasks/flutter_test_performance.dart +++ b/dev/devicelab/bin/tasks/flutter_test_performance.dart @@ -49,7 +49,7 @@ Future runTest({bool coverage = false}) async { ); int badLines = 0; TestStep step = TestStep.starting; - await for (String entry in analysis.stdout.transform(utf8.decoder).transform(const LineSplitter())) { + await for (final String entry in analysis.stdout.transform(utf8.decoder).transform(const LineSplitter())) { print('test stdout ($step): $entry'); if (step == TestStep.starting && entry == 'Building flutter tool...') { // ignore this line @@ -82,7 +82,7 @@ Future runTest({bool coverage = false}) async { } } } - await for (String entry in analysis.stderr.transform(utf8.decoder).transform(const LineSplitter())) { + await for (final String entry in analysis.stderr.transform(utf8.decoder).transform(const LineSplitter())) { print('test stderr: $entry'); badLines += 1; } diff --git a/dev/devicelab/bin/tasks/gradle_non_android_plugin_test.dart b/dev/devicelab/bin/tasks/gradle_non_android_plugin_test.dart index 594644fe7cf..56f9faa2649 100644 --- a/dev/devicelab/bin/tasks/gradle_non_android_plugin_test.dart +++ b/dev/devicelab/bin/tasks/gradle_non_android_plugin_test.dart @@ -50,7 +50,7 @@ Future main() async { final String pubspecString = pubspecFile.readAsStringSync(); final StringBuffer iosOnlyPubspec = StringBuffer(); - for (String line in pubspecString.split('\n')) { + for (final String line in pubspecString.split('\n')) { if (line.startsWith(' androidPackage:')) { continue; } diff --git a/dev/devicelab/bin/tasks/technical_debt__cost.dart b/dev/devicelab/bin/tasks/technical_debt__cost.dart index c22f834d883..8f04c69a0c2 100644 --- a/dev/devicelab/bin/tasks/technical_debt__cost.dart +++ b/dev/devicelab/bin/tasks/technical_debt__cost.dart @@ -37,7 +37,7 @@ Future findCostsForFile(File file) async { return 0.0; final bool isTest = file.path.endsWith('_test.dart'); double total = 0.0; - for (String line in await file.readAsLines()) { + for (final String line in await file.readAsLines()) { if (line.contains(todoPattern)) total += todoCost; if (line.contains(ignorePattern)) @@ -60,7 +60,7 @@ Future findGlobalsForFile(File file) async { if (path.extension(file.path) != '.dart') return 0; int total = 0; - for (String line in await file.readAsLines()) { + for (final String line in await file.readAsLines()) { if (line.contains(globalsPattern)) total += 1; } @@ -74,7 +74,7 @@ Future findCostsForRepo() async { workingDirectory: flutterDirectory.path, ); double total = 0.0; - await for (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) @@ -89,7 +89,7 @@ Future findGlobalsForTool() async { workingDirectory: flutterDirectory.path, ); int total = 0; - await for (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) diff --git a/dev/devicelab/bin/tasks/uncaught_image_error_linux.dart b/dev/devicelab/bin/tasks/uncaught_image_error_linux.dart index 7c647ff5f19..17f55c58bb4 100644 --- a/dev/devicelab/bin/tasks/uncaught_image_error_linux.dart +++ b/dev/devicelab/bin/tasks/uncaught_image_error_linux.dart @@ -37,7 +37,7 @@ Future main() async { .transform(utf8.decoder) .transform(const LineSplitter()); - await for (String line in lines) { + await for (final String line in lines) { print(line); if (line.contains('ERROR caught by framework')) { passed = true; diff --git a/dev/devicelab/lib/framework/adb.dart b/dev/devicelab/lib/framework/adb.dart index fa07a86ec54..ead98839590 100644 --- a/dev/devicelab/lib/framework/adb.dart +++ b/dev/devicelab/lib/framework/adb.dart @@ -144,7 +144,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { final List output = (await eval(adbPath, ['devices', '-l'], canFail: false)) .trim().split('\n'); final List results = []; - for (String line in output) { + for (final String line in output) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) continue; @@ -172,7 +172,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { @override Future> checkDevices() async { final Map results = {}; - for (String deviceId in await discoverDevices()) { + for (final String deviceId in await discoverDevices()) { try { final AndroidDevice device = AndroidDevice(deviceId: deviceId); // Just a smoke test that we can read wakefulness state @@ -432,7 +432,7 @@ class IosDeviceDiscovery implements DeviceDiscovery { @override Future> checkDevices() async { final Map results = {}; - for (String deviceId in await discoverDevices()) { + for (final String deviceId in await discoverDevices()) { // TODO(ianh): do a more meaningful connectivity check than just recording the ID results['ios-device-$deviceId'] = HealthCheckResult.success(); } diff --git a/dev/devicelab/lib/framework/apk_utils.dart b/dev/devicelab/lib/framework/apk_utils.dart index 2312672448d..ed83e839687 100644 --- a/dev/devicelab/lib/framework/apk_utils.dart +++ b/dev/devicelab/lib/framework/apk_utils.dart @@ -191,7 +191,7 @@ Future getAndroidManifest(String apk) async { /// Checks that the classes are contained in the APK, throws otherwise. Future checkApkContainsClasses(File apk, List classes) async { final ApkExtractor extractor = ApkExtractor(apk); - for (String className in classes) { + for (final String className in classes) { if (!(await extractor.containsClass(className))) { throw Exception('APK doesn\'t contain class `$className`.'); } diff --git a/dev/devicelab/lib/framework/framework.dart b/dev/devicelab/lib/framework/framework.dart index e991c344852..45381ff8f96 100644 --- a/dev/devicelab/lib/framework/framework.dart +++ b/dev/devicelab/lib/framework/framework.dart @@ -179,7 +179,7 @@ class TaskResult { message = 'success' { const JsonEncoder prettyJson = JsonEncoder.withIndent(' '); if (benchmarkScoreKeys != null) { - for (String key in benchmarkScoreKeys) { + for (final String key in benchmarkScoreKeys) { if (!data.containsKey(key)) { throw 'Invalid Golem score key "$key". It does not exist in task ' 'result data ${prettyJson.convert(data)}'; diff --git a/dev/devicelab/lib/framework/manifest.dart b/dev/devicelab/lib/framework/manifest.dart index 6263a06dbee..04b48b74eea 100644 --- a/dev/devicelab/lib/framework/manifest.dart +++ b/dev/devicelab/lib/framework/manifest.dart @@ -160,7 +160,7 @@ void _checkIsNotBlank(dynamic value, String variableName, String ownerName) { } void _checkKeys(Map map, String variableName, List allowedKeys) { - for (String key in map.keys.cast()) { + for (final String key in map.keys.cast()) { if (!allowedKeys.contains(key)) { throw ManifestError( 'Unrecognized property "$key" in $variableName. ' diff --git a/dev/devicelab/lib/framework/running_processes.dart b/dev/devicelab/lib/framework/running_processes.dart index e438b1814b2..cb09cf56c0a 100644 --- a/dev/devicelab/lib/framework/running_processes.dart +++ b/dev/devicelab/lib/framework/running_processes.dart @@ -100,7 +100,7 @@ Stream windowsRunningProcesses(String processName) async* { print(result.stdout); return; } - for (RunningProcessInfo info in processPowershellOutput(result.stdout as String)) { + for (final RunningProcessInfo info in processPowershellOutput(result.stdout as String)) { yield info; } } @@ -122,7 +122,7 @@ Iterable processPowershellOutput(String output) sync* { int creationDateHeaderEnd; int commandLineHeaderStart; bool inTableBody = false; - for (String line in output.split('\n')) { + for (final String line in output.split('\n')) { if (line.startsWith('ProcessId')) { commandLineHeaderStart = line.indexOf('CommandLine'); creationDateHeaderEnd = commandLineHeaderStart - 1; @@ -191,7 +191,7 @@ Stream posixRunningProcesses( print(result.stdout); return; } - for (RunningProcessInfo info in processPsOutput(result.stdout as String, processName)) { + for (final RunningProcessInfo info in processPsOutput(result.stdout as String, processName)) { yield info; } } diff --git a/dev/devicelab/lib/framework/utils.dart b/dev/devicelab/lib/framework/utils.dart index 9aa71be3ccb..2b54cc559b7 100644 --- a/dev/devicelab/lib/framework/utils.dart +++ b/dev/devicelab/lib/framework/utils.dart @@ -63,7 +63,7 @@ class HealthCheckResult { if (details != null && details.trim().isNotEmpty) { buf.writeln(); // Indent details by 4 spaces - for (String line in details.trim().split('\n')) { + for (final String line in details.trim().split('\n')) { buf.writeln(' $line'); } } @@ -119,7 +119,7 @@ void recursiveCopy(Directory source, Directory target) { if (!target.existsSync()) target.createSync(); - for (FileSystemEntity entity in source.listSync(followLinks: false)) { + 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')) recursiveCopy(entity, Directory(path.join(target.path, name))); @@ -286,7 +286,7 @@ Future forceQuitRunningProcesses() async { await Future.delayed(const Duration(seconds: 1)); // Whatever's left, kill it. - for (ProcessInfo p in _runningProcesses) { + for (final ProcessInfo p in _runningProcesses) { print('Force-quitting process:\n$p'); if (!p.process.kill()) { print('Failed to force quit process'); @@ -636,7 +636,7 @@ void checkFileNotExists(String file) { /// Check that `collection` contains all entries in `values`. void checkCollectionContains(Iterable values, Iterable collection) { - for (T value in values) { + for (final T value in values) { if (!collection.contains(value)) { throw TaskResult.failure('Expected to find `$value` in `${collection.toString()}`.'); } @@ -645,7 +645,7 @@ void checkCollectionContains(Iterable values, Iterable collection) { /// Check that `collection` does not contain any entries in `values` void checkCollectionDoesNotContain(Iterable values, Iterable collection) { - for (T value in values) { + for (final T value in values) { if (collection.contains(value)) { throw TaskResult.failure('Did not expect to find `$value` in `$collection`.'); } @@ -656,7 +656,7 @@ void checkCollectionDoesNotContain(Iterable values, Iterable collection /// [Pattern]s, otherwise throws a [TaskResult]. void checkFileContains(List patterns, String filePath) { final String fileContent = File(filePath).readAsStringSync(); - for (Pattern pattern in patterns) { + for (final Pattern pattern in patterns) { if (!fileContent.contains(pattern)) { throw TaskResult.failure( 'Expected to find `$pattern` in `$filePath` ' diff --git a/dev/devicelab/lib/tasks/gallery.dart b/dev/devicelab/lib/tasks/gallery.dart index e27b9bce488..ae44b771840 100644 --- a/dev/devicelab/lib/tasks/gallery.dart +++ b/dev/devicelab/lib/tasks/gallery.dart @@ -50,7 +50,7 @@ class GalleryTransitionTest { file('${galleryDirectory.path}/build/transition_durations.timeline.json').readAsStringSync(), ) as Map; final Map> transitions = >{}; - for (String key in original.keys) { + for (final String key in original.keys) { transitions[key.replaceAll('/', '')] = List.from(original[key] as List); } diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index a1ad8fd14c5..7ced54f559f 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -386,7 +386,7 @@ class CompileTest { final RegExp metricExpression = RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)'); final Map metrics = {}; - for (Match m in metricExpression.allMatches(compileLog)) { + for (final Match m in metricExpression.allMatches(compileLog)) { metrics[_sdkNameToMetricName(m.group(1))] = int.parse(m.group(2)); } if (metrics.length != _kSdkNameToMetricNameMapping.length) { diff --git a/dev/devicelab/lib/tasks/plugin_tests.dart b/dev/devicelab/lib/tasks/plugin_tests.dart index ab04539bc26..cff0a7fbb9c 100644 --- a/dev/devicelab/lib/tasks/plugin_tests.dart +++ b/dev/devicelab/lib/tasks/plugin_tests.dart @@ -12,7 +12,7 @@ import 'package:flutter_devicelab/framework/utils.dart'; /// Combines several TaskFunctions with trivial success value into one. TaskFunction combine(List tasks) { return () async { - for (TaskFunction task in tasks) { + for (final TaskFunction task in tasks) { final TaskResult result = await task(); if (result.failed) { return result; diff --git a/dev/devicelab/lib/tasks/save_catalog_screenshots.dart b/dev/devicelab/lib/tasks/save_catalog_screenshots.dart index 062c0b49e74..214e2405096 100644 --- a/dev/devicelab/lib/tasks/save_catalog_screenshots.dart +++ b/dev/devicelab/lib/tasks/save_catalog_screenshots.dart @@ -120,14 +120,14 @@ Future saveCatalogScreenshots({ String prefix, // Prefix for all file names. }) async { final List screenshots = [ - for (FileSystemEntity entity in directory.listSync()) + for (final FileSystemEntity entity in directory.listSync()) if (entity is File && entity.path.endsWith('.png')) entity.path, ]; final List largeNames = []; // Cloud storage names for the full res screenshots. final List smallNames = []; // Likewise for the scaled down screenshots. - for (String path in screenshots) { + for (final String path in screenshots) { final String name = screenshotName(path); largeNames.add('$commit/$prefix$name.png'); smallNames.add('$commit/$prefix${name}_small.png'); diff --git a/dev/devicelab/test/manifest_test.dart b/dev/devicelab/test/manifest_test.dart index 4a642fe1985..8282a9f2491 100644 --- a/dev/devicelab/test/manifest_test.dart +++ b/dev/devicelab/test/manifest_test.dart @@ -19,7 +19,7 @@ void main() { expect(task.stage, 'devicelab'); expect(task.requiredAgentCapabilities, ['linux/android']); - for (ManifestTask task in manifest.tasks) { + for (final ManifestTask task in manifest.tasks) { final File taskFile = File('bin/tasks/${task.name}.dart'); expect(taskFile.existsSync(), true, reason: 'File ${taskFile.path} corresponding to manifest task "${task.name}" not found'); diff --git a/dev/devicelab/test/run_test.dart b/dev/devicelab/test/run_test.dart index 90f43f382fc..809059001df 100644 --- a/dev/devicelab/test/run_test.dart +++ b/dev/devicelab/test/run_test.dart @@ -19,7 +19,7 @@ void main() { final ProcessResult scriptProcess = processManager.runSync([ dart, 'bin/run.dart', - for (String testName in testNames) ...['-t', testName], + for (final String testName in testNames) ...['-t', testName], ]); return scriptProcess; } 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 06fa05f0529..79cf2f47ef4 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/common.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/common.dart @@ -149,7 +149,7 @@ class AndroidSemanticsNode { /// Gets a list of [AndroidSemanticsActions] which are defined for the node. List getActions() => [ - for (int id in (_values['actions'] as List).cast()) AndroidSemanticsAction.deserialize(id), + for (final int id in (_values['actions'] as List).cast()) AndroidSemanticsAction.deserialize(id), ]; @override diff --git a/dev/integration_tests/android_semantics_testing/test_driver/main_test.dart b/dev/integration_tests/android_semantics_testing/test_driver/main_test.dart index fe759fe87d4..ef760023fb3 100644 --- a/dev/integration_tests/android_semantics_testing/test_driver/main_test.dart +++ b/dev/integration_tests/android_semantics_testing/test_driver/main_test.dart @@ -399,7 +399,7 @@ void main() { // catch up. await Future.delayed(const Duration(milliseconds: 1500)); - for (String item in popupItems) { + for (final String item in popupItems) { expect( await getSemantics(find.byValueKey('$popupKeyValue.$item')), hasAndroidSemantics( @@ -423,7 +423,7 @@ void main() { await driver.tap(find.byValueKey(popupButtonKeyValue)); await Future.delayed(const Duration(milliseconds: 1500)); - for (String item in popupItems) { + for (final String item in popupItems) { expect( await getSemantics(find.byValueKey('$popupKeyValue.$item')), hasAndroidSemantics( @@ -467,7 +467,7 @@ void main() { try { await Future.delayed(const Duration(milliseconds: 1500)); - for (String item in popupItems) { + for (final String item in popupItems) { // There are two copies of each item, so we want to find the version // that is in the overlay, not the one in the dropdown. expect( @@ -503,7 +503,7 @@ void main() { await driver.tap(find.byValueKey(dropdownButtonKeyValue)); await Future.delayed(const Duration(milliseconds: 1500)); - for (String item in popupItems) { + for (final String item in popupItems) { // There are two copies of each item, so we want to find the version // that is in the overlay, not the one in the dropdown. expect( @@ -572,7 +572,7 @@ void main() { ), reason: "Alert OK button doesn't have the right semantics"); - for (String item in ['Title', 'Body1', 'Body2']) { + for (final String item in ['Title', 'Body1', 'Body2']) { expect( await getSemantics(find.byValueKey('$alertKeyValue.$item')), hasAndroidSemantics( @@ -611,7 +611,7 @@ void main() { ), reason: "Alert OK button doesn't have the right semantics"); - for (String item in ['Title', 'Body1', 'Body2']) { + for (final String item in ['Title', 'Body1', 'Body2']) { expect( await getSemantics(find.byValueKey('$alertKeyValue.$item')), hasAndroidSemantics( 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 f5f073fd480..b42d9e88157 100644 --- a/dev/integration_tests/android_views/lib/motion_event_diff.dart +++ b/dev/integration_tests/android_views/lib/motion_event_diff.dart @@ -122,7 +122,7 @@ void diffMaps( '${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} '); return; } - for (String key in expected.keys) { + for (final String key in expected.keys) { if (excludeKeys.contains(key)) continue; if (doublesApproximatelyMatch(expected[key], actual[key])) 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 48be7dea52e..a4b508b0a1c 100644 --- a/dev/integration_tests/android_views/lib/motion_events_page.dart +++ b/dev/integration_tests/android_views/lib/motion_events_page.dart @@ -123,7 +123,7 @@ class MotionEventsBodyState extends State { await channel.invokeMethod('pipeFlutterViewEvents'); await viewChannel.invokeMethod('pipeTouchEvents'); print('replaying ${recordedEvents.length} motion events'); - for (Map event in recordedEvents.reversed) { + for (final Map event in recordedEvents.reversed) { await channel.invokeMethod('synthesizeEvent', event); } diff --git a/dev/integration_tests/channels/lib/src/test_step.dart b/dev/integration_tests/channels/lib/src/test_step.dart index 4662d0338db..2a264671873 100644 --- a/dev/integration_tests/channels/lib/src/test_step.dart +++ b/dev/integration_tests/channels/lib/src/test_step.dart @@ -174,7 +174,7 @@ bool _deepEqualsList(List a, List b) { bool _deepEqualsMap(Map a, Map b) { if (a.length != b.length) return false; - for (dynamic key in a.keys) { + for (final dynamic key in a.keys) { if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) return false; } diff --git a/dev/manual_tests/lib/actions.dart b/dev/manual_tests/lib/actions.dart index 16acf1ef121..2663b54c5ac 100644 --- a/dev/manual_tests/lib/actions.dart +++ b/dev/manual_tests/lib/actions.dart @@ -77,7 +77,7 @@ class UndoableActionDispatcher extends ActionDispatcher implements Listenable { /// May only be called by subclasses. @protected void notifyListeners() { - for (VoidCallback callback in _listeners) { + for (final VoidCallback callback in _listeners) { callback(); } } diff --git a/dev/manual_tests/lib/overlay_geometry.dart b/dev/manual_tests/lib/overlay_geometry.dart index 54f68c7667d..a223fa44e70 100644 --- a/dev/manual_tests/lib/overlay_geometry.dart +++ b/dev/manual_tests/lib/overlay_geometry.dart @@ -159,7 +159,7 @@ class OverlayGeometryAppState extends State { setState(() { final double dy = markersScrollOffset - notification.metrics.extentBefore; markersScrollOffset = notification.metrics.extentBefore; - for (MarkerType type in markers.keys) { + for (final MarkerType type in markers.keys) { final Offset oldPosition = markers[type]; markers[type] = oldPosition.translate(0.0, dy); } @@ -199,7 +199,7 @@ class OverlayGeometryAppState extends State { ), ), ), - for (MarkerType type in markers.keys) + for (final MarkerType type in markers.keys) Marker(type: type, position: markers[type]), ], ); diff --git a/dev/manual_tests/lib/raw_keyboard.dart b/dev/manual_tests/lib/raw_keyboard.dart index fabcb627733..5f78ca378b5 100644 --- a/dev/manual_tests/lib/raw_keyboard.dart +++ b/dev/manual_tests/lib/raw_keyboard.dart @@ -127,8 +127,8 @@ class _HardwareKeyDemoState extends State { if (_event.character != null) { dataText.add(Text('character: ${_event.character}')); } - for (ModifierKey modifier in data.modifiersPressed.keys) { - for (KeyboardSide side in KeyboardSide.values) { + for (final ModifierKey modifier in data.modifiersPressed.keys) { + for (final KeyboardSide side in KeyboardSide.values) { if (data.isModifierPressed(modifier, side: side)) { dataText.add( Text('${_getEnumName(side)} ${_getEnumName(modifier).replaceAll('Modifier', '')} pressed'), diff --git a/dev/manual_tests/lib/text.dart b/dev/manual_tests/lib/text.dart index 37b421c6d0f..3ca82aca286 100644 --- a/dev/manual_tests/lib/text.dart +++ b/dev/manual_tests/lib/text.dart @@ -343,7 +343,7 @@ class _FuzzerState extends State with SingleTickerProviderStateMixin { if (node.children == null || node.children.isEmpty) return 0; int result = 0; - for (TextSpan child in node.children.cast()) + for (final TextSpan child in node.children.cast()) result = math.max(result, depthOf(child)); return result; } @@ -582,7 +582,7 @@ class _UnderlinesState extends State { child: ListBody( children: [ _wrap(null), - for (TextDecorationStyle style in TextDecorationStyle.values) _wrap(style), + for (final TextDecorationStyle style in TextDecorationStyle.values) _wrap(style), ], ), ), @@ -675,7 +675,7 @@ class _FallbackState extends State { child: IntrinsicWidth( child: ListBody( children: [ - for (String font in androidFonts) + for (final String font in androidFonts) Text( multiScript, style: style.copyWith( diff --git a/dev/snippets/lib/snippets.dart b/dev/snippets/lib/snippets.dart index 3e955b08fbc..b21c795c36b 100644 --- a/dev/snippets/lib/snippets.dart +++ b/dev/snippets/lib/snippets.dart @@ -104,7 +104,7 @@ class SnippetGenerator { final List result = []; const HtmlEscape htmlEscape = HtmlEscape(); String language; - for (_ComponentTuple injection in injections) { + for (final _ComponentTuple injection in injections) { if (!injection.name.startsWith('code')) { continue; } @@ -152,7 +152,7 @@ class SnippetGenerator { final List<_ComponentTuple> components = <_ComponentTuple>[]; String language; final RegExp codeStartEnd = RegExp(r'^\s*```([-\w]+|[-\w]+ ([-\w]+))?\s*$'); - for (String line in input.split('\n')) { + for (final String line in input.split('\n')) { final Match match = codeStartEnd.firstMatch(line); if (match != null) { // If we saw the start or end of a code block inCodeBlock = !inCodeBlock; @@ -188,7 +188,7 @@ class SnippetGenerator { String _addLineNumbers(String app) { final StringBuffer buffer = StringBuffer(); int count = 0; - for (String line in app.split('\n')) { + for (final String line in app.split('\n')) { count++; buffer.writeln('${count.toString().padLeft(5, ' ')}: $line'); } diff --git a/dev/tools/dartdoc.dart b/dev/tools/dartdoc.dart index 103697e248f..7c3a436331e 100644 --- a/dev/tools/dartdoc.dart +++ b/dev/tools/dartdoc.dart @@ -57,7 +57,7 @@ Future main(List arguments) async { // https://github.com/dart-lang/dartdoc/issues/1982 buf.writeln('version: 0.0.0'); buf.writeln('dependencies:'); - for (String package in findPackageNames()) { + for (final String package in findPackageNames()) { buf.writeln(' $package:'); buf.writeln(' sdk: flutter'); } @@ -72,7 +72,7 @@ Future main(List arguments) async { libDir.createSync(); final StringBuffer contents = StringBuffer('library temp_doc;\n\n'); - for (String libraryRef in libraryRefs()) { + for (final String libraryRef in libraryRefs()) { contents.writeln('import \'package:$libraryRef\';'); } File('$kDocsRoot/lib/temp_doc.dart').writeAsStringSync(contents.toString()); @@ -313,7 +313,7 @@ void copyDirectorySync(Directory srcDir, Directory destDir, [void onFileCopied(F if (!destDir.existsSync()) destDir.createSync(recursive: true); - for (FileSystemEntity entity in srcDir.listSync()) { + for (final FileSystemEntity entity in srcDir.listSync()) { final String newPath = path.join(destDir.path, path.basename(entity.path)); if (entity is File) { final File newFile = File(newPath); @@ -361,7 +361,7 @@ void sanityCheckDocs() { '$kPublishRoot/api/material/Tooltip-class.html', '$kPublishRoot/api/widgets/Widget-class.html', ]; - for (String canary in canaries) { + for (final String canary in canaries) { if (!File(canary).existsSync()) throw Exception('Missing "$canary", which probably means the documentation failed to build correctly.'); } @@ -470,9 +470,9 @@ List findPackages() { /// Returns import or on-disk paths for all libraries in the Flutter SDK. Iterable libraryRefs() sync* { - for (Directory dir in findPackages()) { + for (final Directory dir in findPackages()) { final String dirName = path.basename(dir.path); - for (FileSystemEntity file in Directory('${dir.path}/lib').listSync()) { + for (final FileSystemEntity file in Directory('${dir.path}/lib').listSync()) { if (file is File && file.path.endsWith('.dart')) { yield '$dirName/${path.basename(file.path)}'; } diff --git a/dev/tools/gen_keycodes/lib/code_gen.dart b/dev/tools/gen_keycodes/lib/code_gen.dart index 8d7d2d25c4d..c7f006a18f8 100644 --- a/dev/tools/gen_keycodes/lib/code_gen.dart +++ b/dev/tools/gen_keycodes/lib/code_gen.dart @@ -20,7 +20,7 @@ class CodeGenerator { final StringBuffer result = StringBuffer(); final List words = input.split(RegExp(r'\s+')); String currentLine = words.removeAt(0); - for (String word in words) { + for (final String word in words) { if ((currentLine.length + word.length) < wrapWidth) { currentLine += ' $word'; } else { @@ -37,7 +37,7 @@ class CodeGenerator { /// Gets the generated definitions of PhysicalKeyboardKeys. String get physicalDefinitions { final StringBuffer definitions = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { final String firstComment = wrapString('Represents the location of the ' '"${entry.commentName}" key on a generalized keyboard.'); final String otherComments = wrapString('See the function ' @@ -73,7 +73,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK } } - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { printKey( entry.flutterId, entry.keyLabel, @@ -81,7 +81,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK entry.commentName, ); } - for (String name in Key.synonyms.keys) { + for (final String name in Key.synonyms.keys) { // Use the first item in the synonyms as a template for the ID to use. // It won't end up being the same value because it'll be in the pseudo-key // plane. @@ -99,8 +99,8 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK String get logicalSynonyms { final StringBuffer synonyms = StringBuffer(); - for (String name in Key.synonyms.keys) { - for (String synonym in Key.synonyms[name].cast()) { + for (final String name in Key.synonyms.keys) { + for (final String synonym in Key.synonyms[name].cast()) { final String keyName = upperCamelToLowerCamel(synonym); synonyms.writeln(' $keyName: $name,'); } @@ -124,7 +124,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of USB HID codes to physical keys. String get predefinedHidCodeMap { final StringBuffer scanCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { scanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: ${entry.constantName},'); } return scanCodeMap.toString().trimRight(); @@ -133,10 +133,10 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// THis generates the map of Flutter key codes to logical keys. String get predefinedKeyCodeMap { final StringBuffer keyCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { keyCodeMap.writeln(' ${toHex(entry.flutterId, digits: 10)}: ${entry.constantName},'); } - for (String entry in Key.synonyms.keys) { + for (final String entry in Key.synonyms.keys) { // Use the first item in the synonyms as a template for the ID to use. // It won't end up being the same value because it'll be in the pseudo-key // plane. @@ -152,9 +152,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of GLFW number pad key codes to logical keys. String get glfwNumpadMap { final StringBuffer glfwNumpadMap = StringBuffer(); - for (Key entry in numpadKeyData) { + for (final Key entry in numpadKeyData) { if (entry.glfwKeyCodes != null) { - for (int code in entry.glfwKeyCodes.cast()) { + for (final int code in entry.glfwKeyCodes.cast()) { glfwNumpadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); } } @@ -165,9 +165,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of GLFW key codes to logical keys. String get glfwKeyCodeMap { final StringBuffer glfwKeyCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.glfwKeyCodes != null) { - for (int code in entry.glfwKeyCodes.cast()) { + for (final int code in entry.glfwKeyCodes.cast()) { glfwKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); } } @@ -178,7 +178,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of XKB USB HID codes to physical keys. String get xkbScanCodeMap { final StringBuffer xkbScanCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.xKbScanCode != null) { xkbScanCodeMap.writeln(' ${toHex(entry.xKbScanCode)}: PhysicalKeyboardKey.${entry.constantName},'); } @@ -189,9 +189,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Android key codes to logical keys. String get androidKeyCodeMap { final StringBuffer androidKeyCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.androidKeyCodes != null) { - for (int code in entry.androidKeyCodes.cast()) { + for (final int code in entry.androidKeyCodes.cast()) { androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); } } @@ -202,9 +202,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Android number pad key codes to logical keys. String get androidNumpadMap { final StringBuffer androidKeyCodeMap = StringBuffer(); - for (Key entry in numpadKeyData) { + for (final Key entry in numpadKeyData) { if (entry.androidKeyCodes != null) { - for (int code in entry.androidKeyCodes.cast()) { + for (final int code in entry.androidKeyCodes.cast()) { androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); } } @@ -215,9 +215,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Android scan codes to physical keys. String get androidScanCodeMap { final StringBuffer androidScanCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.androidScanCodes != null) { - for (int code in entry.androidScanCodes.cast()) { + for (final int code in entry.androidScanCodes.cast()) { androidScanCodeMap.writeln(' $code: PhysicalKeyboardKey.${entry.constantName},'); } } @@ -228,7 +228,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of macOS key codes to physical keys. String get macOsScanCodeMap { final StringBuffer macOsScanCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.macOsScanCode != null) { macOsScanCodeMap.writeln(' ${toHex(entry.macOsScanCode)}: PhysicalKeyboardKey.${entry.constantName},'); } @@ -239,7 +239,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of macOS number pad key codes to logical keys. String get macOsNumpadMap { final StringBuffer macOsNumPadMap = StringBuffer(); - for (Key entry in numpadKeyData) { + for (final Key entry in numpadKeyData) { if (entry.macOsScanCode != null) { macOsNumPadMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},'); } @@ -249,7 +249,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK String get macOsFunctionKeyMap { final StringBuffer macOsFunctionKeyMap = StringBuffer(); - for (Key entry in functionKeyData) { + for (final Key entry in functionKeyData) { if (entry.macOsScanCode != null) { macOsFunctionKeyMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},'); } @@ -260,7 +260,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Fuchsia key codes to logical keys. String get fuchsiaKeyCodeMap { final StringBuffer fuchsiaKeyCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.usbHidCode != null) { fuchsiaKeyCodeMap.writeln(' ${toHex(entry.flutterId)}: LogicalKeyboardKey.${entry.constantName},'); } @@ -271,7 +271,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Fuchsia USB HID codes to physical keys. String get fuchsiaHidCodeMap { final StringBuffer fuchsiaScanCodeMap = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.usbHidCode != null) { fuchsiaScanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: PhysicalKeyboardKey.${entry.constantName},'); } @@ -282,7 +282,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Web KeyboardEvent codes to logical keys. String get webLogicalKeyMap { final StringBuffer result = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.name != null) { result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},"); } @@ -293,7 +293,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Web KeyboardEvent codes to physical keys. String get webPhysicalKeyMap { final StringBuffer result = StringBuffer(); - for (Key entry in keyData.data) { + for (final Key entry in keyData.data) { if (entry.name != null) { result.writeln(" '${entry.name}': PhysicalKeyboardKey.${entry.constantName},"); } @@ -304,7 +304,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK /// This generates the map of Web number pad codes to logical keys. String get webNumpadMap { final StringBuffer result = StringBuffer(); - for (Key entry in numpadKeyData) { + for (final Key entry in numpadKeyData) { if (entry.name != null) { result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},"); } @@ -359,7 +359,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK static String _injectDictionary(String template, Map dictionary) { String result = template; - for (String key in dictionary.keys) { + for (final String key in dictionary.keys) { result = result.replaceAll('@@@$key@@@', dictionary[key]); } return result; diff --git a/dev/tools/gen_keycodes/lib/key_data.dart b/dev/tools/gen_keycodes/lib/key_data.dart index 9c755a081b7..8853f73acca 100644 --- a/dev/tools/gen_keycodes/lib/key_data.dart +++ b/dev/tools/gen_keycodes/lib/key_data.dart @@ -53,18 +53,18 @@ class KeyData { /// Parses the given JSON data and populates the data structure from it. KeyData.fromJson(Map contentMap) { data = [ - for (String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map>), + for (final String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map>), ]; } /// Converts the data structure into a JSON structure that can be parsed by /// [KeyData.fromJson]. Map toJson() { - for (Key entry in data) { + for (final Key entry in data) { // Android Key names entry.androidKeyNames = _nameToAndroidName[entry.constantName]?.cast(); if (entry.androidKeyNames != null && entry.androidKeyNames.isNotEmpty) { - for (String androidKeyName in entry.androidKeyNames) { + for (final String androidKeyName in entry.androidKeyNames) { if (_nameToAndroidKeyCode[androidKeyName] != null) { entry.androidKeyCodes ??= []; entry.androidKeyCodes.add(_nameToAndroidKeyCode[androidKeyName]); @@ -79,7 +79,7 @@ class KeyData { // GLFW key names entry.glfwKeyNames = _nameToGlfwName[entry.constantName]?.cast(); if (entry.glfwKeyNames != null && entry.glfwKeyNames.isNotEmpty) { - for (String glfwKeyName in entry.glfwKeyNames) { + for (final String glfwKeyName in entry.glfwKeyNames) { if (_nameToGlfwKeyCode[glfwKeyName] != null) { entry.glfwKeyCodes ??= []; entry.glfwKeyCodes.add(_nameToGlfwKeyCode[glfwKeyName]); @@ -89,7 +89,7 @@ class KeyData { } final Map outputMap = {}; - for (Key entry in data) { + for (final Key entry in data) { outputMap[entry.constantName] = entry.toJson(); } return outputMap; @@ -178,7 +178,7 @@ class KeyData { headerFile = headerFile.replaceAllMapped(enumBlock, (Match match) => match.group(1)); final RegExp enumEntry = RegExp(r'''AKEYCODE_([A-Z0-9_]+)\s*=\s*([0-9]+),?'''); final Map result = {}; - for (Match match in enumEntry.allMatches(headerFile)) { + for (final Match match in enumEntry.allMatches(headerFile)) { result[match.group(1)] = int.parse(match.group(2)); } return result; @@ -193,7 +193,7 @@ class KeyData { // Only get the KEY definitions, ignore the rest (mouse, joystick, etc). final RegExp enumEntry = RegExp(r'''define GLFW_KEY_([A-Z0-9_]+)\s*([A-Z0-9_]+),?'''); final Map replaced = {}; - for (Match match in enumEntry.allMatches(headerFile)) { + for (final Match match in enumEntry.allMatches(headerFile)) { replaced[match.group(1)] = int.tryParse(match.group(2)) ?? match.group(2).replaceAll('GLFW_KEY_', ''); } final Map result = {}; diff --git a/dev/tools/java_and_objc_doc.dart b/dev/tools/java_and_objc_doc.dart index 7f41dffeeea..2a0f8367856 100644 --- a/dev/tools/java_and_objc_doc.dart +++ b/dev/tools/java_and_objc_doc.dart @@ -56,7 +56,7 @@ Future generateDocs(String url, String docName, String checkFile) async { print('Extracting $docName to ${output.path}'); output.createSync(recursive: true); - for (ArchiveFile af in archive) { + for (final ArchiveFile af in archive) { if (!af.name.endsWith('/')) { final File file = File('${output.path}/${af.name}'); file.createSync(recursive: true); diff --git a/dev/tools/localization/bin/encode_kn_arb_files.dart b/dev/tools/localization/bin/encode_kn_arb_files.dart index 805b9b3cd82..6477a5de990 100644 --- a/dev/tools/localization/bin/encode_kn_arb_files.dart +++ b/dev/tools/localization/bin/encode_kn_arb_files.dart @@ -36,7 +36,7 @@ Map loadBundle(File file) { } void encodeBundleTranslations(Map bundle) { - for (String key in bundle.keys) { + 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('@')) @@ -54,7 +54,7 @@ void encodeBundleTranslations(Map bundle) { void checkEncodedTranslations(Map encodedBundle, Map bundle) { bool errorFound = false; const JsonDecoder decoder = JsonDecoder(); - for (String key in bundle.keys) { + for (final String key in bundle.keys) { if (decoder.convert('"${encodedBundle[key]}"') != bundle[key]) { stderr.writeln(' encodedTranslation for $key does not match original value "${bundle[key]}"'); errorFound = true; @@ -67,7 +67,7 @@ void checkEncodedTranslations(Map encodedBundle, Map bundle) { final StringBuffer contents = StringBuffer(); contents.writeln('{'); - for (String key in bundle.keys) { + for (final String key in bundle.keys) { contents.writeln(' "$key": "${bundle[key]}"${key == bundle.keys.last ? '' : ','}'); } contents.writeln('}'); diff --git a/dev/tools/localization/bin/gen_date_localizations.dart b/dev/tools/localization/bin/gen_date_localizations.dart index b9c5f725f08..5c805093fc1 100644 --- a/dev/tools/localization/bin/gen_date_localizations.dart +++ b/dev/tools/localization/bin/gen_date_localizations.dart @@ -167,7 +167,7 @@ Set _supportedLocales() { final Set supportedLocales = {}; final RegExp filenameRE = RegExp(r'(?:material|cupertino)_(\w+)\.arb$'); final Directory supportedLocalesDirectory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n')); - for (FileSystemEntity entity in supportedLocalesDirectory.listSync()) { + for (final FileSystemEntity entity in supportedLocalesDirectory.listSync()) { final String filePath = entity.path; if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath)) supportedLocales.add(filenameRE.firstMatch(filePath)[1]); @@ -181,7 +181,7 @@ Map _listIntlData(Directory directory) { .listSync() .whereType() .where((File file) => file.path.endsWith('.json')); - for (File file in files) { + for (final File file in files) { final String locale = path.basenameWithoutExtension(file.path); localeFiles[locale] = file; } diff --git a/dev/tools/localization/bin/gen_localizations.dart b/dev/tools/localization/bin/gen_localizations.dart index 5b84a4a63cc..70f343c0379 100644 --- a/dev/tools/localization/bin/gen_localizations.dart +++ b/dev/tools/localization/bin/gen_localizations.dart @@ -87,7 +87,7 @@ String generateArbBasedLocalizationSubclasses({ // Used to calculate if there are any corresponding countries for a given language and script. final Map> languageAndScriptToCountryCodes = >{}; final Set allResourceIdentifiers = {}; - for (LocaleInfo locale in localeToResources.keys.toList()..sort()) { + for (final LocaleInfo locale in localeToResources.keys.toList()..sort()) { if (locale.scriptCode != null) { languageToScriptCodes[locale.languageCode] ??= {}; languageToScriptCodes[locale.languageCode].add(locale.scriptCode); @@ -129,13 +129,13 @@ String generateArbBasedLocalizationSubclasses({ final List allKeys = allResourceIdentifiers.toList()..sort(); final List languageCodes = languageToLocales.keys.toList()..sort(); final LocaleInfo canonicalLocale = LocaleInfo.fromString('en'); - for (String languageName in languageCodes) { + for (final String languageName in languageCodes) { final LocaleInfo languageLocale = LocaleInfo.fromString(languageName); output.writeln(generateClassDeclaration(languageLocale, generatedClassPrefix, baseClass)); output.writeln(generateConstructor(languageLocale)); final Map languageResources = localeToResources[languageLocale]; - for (String key in allKeys) { + for (final String key in allKeys) { final Map attributes = localeToResourceAttributes[canonicalLocale][key] as Map; output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale)); } @@ -146,7 +146,7 @@ String generateArbBasedLocalizationSubclasses({ scriptCodeCount = languageToScriptCodes[languageName].length; // Language has scriptCodes, so we need to properly fallback countries to corresponding // script default values before language default values. - for (String scriptCode in languageToScriptCodes[languageName]) { + for (final String scriptCode in languageToScriptCodes[languageName]) { final LocaleInfo scriptBaseLocale = LocaleInfo.fromString(languageName + '_' + scriptCode); output.writeln(generateClassDeclaration( scriptBaseLocale, @@ -155,7 +155,7 @@ String generateArbBasedLocalizationSubclasses({ )); output.writeln(generateConstructor(scriptBaseLocale)); final Map scriptResources = localeToResources[scriptBaseLocale]; - for (String key in scriptResources.keys.toList()..sort()) { + for (final String key in scriptResources.keys.toList()..sort()) { if (languageResources[key] == scriptResources[key]) continue; final Map attributes = localeToResourceAttributes[canonicalLocale][key] as Map; @@ -164,7 +164,7 @@ String generateArbBasedLocalizationSubclasses({ output.writeln('}'); final List localeCodes = languageToLocales[languageName]..sort(); - for (LocaleInfo locale in localeCodes) { + for (final LocaleInfo locale in localeCodes) { if (locale.originalString == languageName) continue; if (locale.originalString == languageName + '_' + scriptCode) @@ -179,7 +179,7 @@ String generateArbBasedLocalizationSubclasses({ )); output.writeln(generateConstructor(locale)); final Map localeResources = localeToResources[locale]; - for (String key in localeResources.keys) { + 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]) continue; @@ -193,7 +193,7 @@ String generateArbBasedLocalizationSubclasses({ // No scriptCode. Here, we do not compare against script default (because it // doesn't exist). final List localeCodes = languageToLocales[languageName]..sort(); - for (LocaleInfo locale in localeCodes) { + for (final LocaleInfo locale in localeCodes) { if (locale.originalString == languageName) continue; countryCodeCount += 1; @@ -204,7 +204,7 @@ String generateArbBasedLocalizationSubclasses({ '$generatedClassPrefix${camelCase(languageLocale)}', )); output.writeln(generateConstructor(locale)); - for (String key in localeResources.keys) { + for (final String key in localeResources.keys) { if (languageResources[key] == localeResources[key]) continue; final Map attributes = localeToResourceAttributes[canonicalLocale][key] as Map; @@ -262,7 +262,7 @@ $supportedLocales/// {@endtemplate} /// [$baseClass.delegate]. $factoryDeclaration switch (locale.languageCode) {'''); - for (String language in languageToLocales.keys) { + for (final String language in languageToLocales.keys) { // Only one instance of the language. if (languageToLocales[language].length == 1) { output.writeln(''' @@ -272,7 +272,7 @@ $factoryDeclaration output.writeln(''' case '$language': { switch (locale.countryCode) {'''); - for (LocaleInfo locale in languageToLocales[language]) { + for (final LocaleInfo locale in languageToLocales[language]) { if (locale.originalString == language) continue; assert(locale.length > 1); @@ -290,14 +290,14 @@ $factoryDeclaration output.writeln(''' case '$language': { switch (locale.scriptCode) {'''); - for (String scriptCode in languageToScriptCodes[language]) { + for (final String scriptCode in languageToScriptCodes[language]) { final LocaleInfo scriptLocale = LocaleInfo.fromString(language + '_' + scriptCode); output.writeln(''' case '$scriptCode': {'''); if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) { output.writeln(''' switch (locale.countryCode) {'''); - for (LocaleInfo locale in languageToLocales[language]) { + for (final LocaleInfo locale in languageToLocales[language]) { if (locale.countryCode == null) continue; else @@ -326,7 +326,7 @@ $factoryDeclaration } else { // Not Explicitly defined, fallback to first locale with the same language and // script: - for (LocaleInfo locale in languageToLocales[language]) { + for (final LocaleInfo locale in languageToLocales[language]) { if (locale.scriptCode != scriptCode) continue; if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) { @@ -345,7 +345,7 @@ $factoryDeclaration if (hasCountryCode) { output.writeln(''' switch (locale.countryCode) {'''); - for (LocaleInfo locale in languageToLocales[language]) { + for (final LocaleInfo locale in languageToLocales[language]) { if (locale.originalString == language) continue; assert(locale.length > 1); diff --git a/dev/tools/localization/gen_l10n.dart b/dev/tools/localization/gen_l10n.dart index 5281c44c632..c3dad4e1113 100644 --- a/dev/tools/localization/gen_l10n.dart +++ b/dev/tools/localization/gen_l10n.dart @@ -270,7 +270,7 @@ String generateDateFormattingLogic(Map bundle, String key) { final Map attributesMap = bundle['@$key'] as Map; if (attributesMap != null && attributesMap.containsKey('placeholders')) { final Map placeholders = attributesMap['placeholders'] as Map; - for (String placeholder in placeholders.keys) { + for (final String placeholder in placeholders.keys) { final dynamic value = placeholders[placeholder]; if ( value is Map && @@ -302,7 +302,7 @@ List genIntlMethodArgs(Map bundle, String key) { final Map placeholders = attributesMap['placeholders'] as Map; if (placeholders.isNotEmpty) { final List argumentList = []; - for (String placeholder in placeholders.keys) { + for (final String placeholder in placeholders.keys) { final dynamic value = placeholders[placeholder]; if ( value is Map && @@ -328,7 +328,7 @@ String genSimpleMethod(Map bundle, String key) { String message = bundle[key] as String; final Map attributesMap = bundle['@$key'] as Map; final Map placeholders = attributesMap['placeholders'] as Map; - for (String placeholder in placeholders.keys) { + for (final String placeholder in placeholders.keys) { final dynamic value = placeholders[placeholder]; if (value is Map && _isDateParameter(value)) { message = message.replaceAll('{$placeholder}', '\$${placeholder}String'); @@ -388,7 +388,7 @@ String genPluralMethod(Map arbBundle, String resourceId) { // To make it easier to parse the plurals message, temporarily replace each // "{placeholder}" parameter with "#placeholder#". String message = arbBundle[resourceId] as String; - for (String placeholder in placeholders) + for (final String placeholder in placeholders) message = message.replaceAll('{$placeholder}', '#$placeholder#'); final Map pluralIds = { @@ -406,12 +406,12 @@ String genPluralMethod(Map arbBundle, String resourceId) { ...genIntlMethodArgs(arbBundle, resourceId), ]; - for (String pluralKey in pluralIds.keys) { + for (final String pluralKey in pluralIds.keys) { final RegExp expRE = RegExp('($pluralKey){([^}]+)}'); final RegExpMatch match = expRE.firstMatch(message); if (match != null && match.groupCount == 2) { String argValue = match.group(2); - for (String placeholder in placeholders) { + for (final String placeholder in placeholders) { final dynamic value = placeholdersMap[placeholder]; if (value is Map && _isDateParameter(value)) { argValue = argValue.replaceAll('#$placeholder#', '\$${placeholder}String'); @@ -435,7 +435,7 @@ String genSupportedLocaleProperty(Set supportedLocales) { const String suffix = '),\n ];'; String resultingProperty = prefix; - for (LocaleInfo locale in supportedLocales) { + for (final LocaleInfo locale in supportedLocales) { final String languageCode = locale.languageCode; final String countryCode = locale.countryCode; @@ -668,7 +668,7 @@ class LocalizationsGenerator { .toList(); final List localeInfoList = []; - for (File file in fileSystemEntityList) { + for (final File file in fileSystemEntityList) { final String filePath = file.path; if (arbFilenameRE.hasMatch(filePath)) { final Map arbContents = json.decode(file.readAsStringSync()) as Map; @@ -705,7 +705,7 @@ class LocalizationsGenerator { })); if (preferredSupportedLocales != null) { - for (LocaleInfo preferredLocale in preferredSupportedLocales) { + for (final LocaleInfo preferredLocale in preferredSupportedLocales) { if (!localeInfoList.contains(preferredLocale)) { throw L10nException( 'The preferred supported locale, \'$preferredLocale\', cannot be ' @@ -750,7 +750,7 @@ class LocalizationsGenerator { } final List sortedArbKeys = bundle.keys.toList()..sort(); - for (String key in sortedArbKeys) { + for (final String key in sortedArbKeys) { if (key.startsWith('@')) continue; if (!_isValidGetterAndMethodName(key)) diff --git a/dev/tools/localization/localizations_utils.dart b/dev/tools/localization/localizations_utils.dart index 61d830d620a..9813d4334e7 100644 --- a/dev/tools/localization/localizations_utils.dart +++ b/dev/tools/localization/localizations_utils.dart @@ -155,7 +155,7 @@ void loadMatchingArbsIntoBundleMaps({ /// overwrite the existing assumed data. final Set assumedLocales = {}; - for (FileSystemEntity entity in directory.listSync().toList()..sort(sortFilesByPath)) { + for (final FileSystemEntity entity in directory.listSync().toList()..sort(sortFilesByPath)) { final String entityPath = entity.path; if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) { final String localeString = filenamePattern.firstMatch(entityPath)[1]; @@ -166,7 +166,7 @@ void loadMatchingArbsIntoBundleMaps({ final Map resources = localeToResources[locale]; final Map attributes = localeToResourceAttributes[locale]; final Map bundle = json.decode(file.readAsStringSync()) as Map; - for (String key in bundle.keys) { + for (final String key in bundle.keys) { // The ARB file resource "attributes" for foo are called @foo. if (key.startsWith('@')) attributes[key.substring(1)] = bundle[key]; @@ -270,7 +270,7 @@ const String registry = 'https://www.iana.org/assignments/language-subtag-regist Map> _parseSection(String section) { final Map> result = >{}; List lastHeading; - for (String line in section.split('\n')) { + for (final String line in section.split('\n')) { if (line == '') continue; if (line.startsWith(' ')) { @@ -304,7 +304,7 @@ Future precacheLanguageAndRegionTags() async { final String body = (await response.cast>().transform(utf8.decoder).toList()).join(''); client.close(force: true); final List>> sections = body.split('%%').skip(1).map>>(_parseSection).toList(); - for (Map> section in sections) { + for (final Map> section in sections) { assert(section.containsKey('Type'), section.toString()); final String type = section['Type'].single; if (type == 'language' || type == 'region' || type == 'script') { diff --git a/dev/tools/localization/localizations_validator.dart b/dev/tools/localization/localizations_validator.dart index 17cd9c88cee..e6f45600570 100644 --- a/dev/tools/localization/localizations_validator.dart +++ b/dev/tools/localization/localizations_validator.dart @@ -38,7 +38,7 @@ void validateEnglishLocalizations(File file) { final Map bundle = json.decode(file.readAsStringSync()) as Map; - for (String resourceId in bundle.keys) { + for (final String resourceId in bundle.keys) { if (resourceId.startsWith('@')) continue; @@ -55,7 +55,7 @@ void validateEnglishLocalizations(File file) { errorMessages.writeln('A value was not specified for @$resourceId'); } - for (String atResourceId in bundle.keys) { + for (final String atResourceId in bundle.keys) { if (!atResourceId.startsWith('@')) continue; diff --git a/dev/tools/mega_gallery.dart b/dev/tools/mega_gallery.dart index 7dcaa669cb5..c7cd9e730bd 100644 --- a/dev/tools/mega_gallery.dart +++ b/dev/tools/mega_gallery.dart @@ -134,7 +134,7 @@ void _copy(Directory source, Directory target) { if (!target.existsSync()) target.createSync(recursive: true); - for (FileSystemEntity entity in source.listSync(followLinks: false)) { + for (final FileSystemEntity entity in source.listSync(followLinks: false)) { final String name = path.basename(entity.path); if (entity is Directory) { @@ -165,7 +165,7 @@ class SourceStats { SourceStats getStatsFor(Directory dir, [SourceStats stats]) { stats ??= SourceStats(); - for (FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) { + for (final FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) { final String name = path.basename(entity.path); if (entity is File && name.endsWith('.dart')) { stats.files += 1; diff --git a/dev/tools/update_icons.dart b/dev/tools/update_icons.dart index d5b07b06b95..7b0128ad1b0 100644 --- a/dev/tools/update_icons.dart +++ b/dev/tools/update_icons.dart @@ -182,7 +182,7 @@ void main(List args) { String regenerateIconsFile(String iconData, String codepointData) { final StringBuffer buf = StringBuffer(); bool generating = false; - for (String line in LineSplitter.split(iconData)) { + for (final String line in LineSplitter.split(iconData)) { if (!generating) buf.writeln(line); if (line.contains(kBeginGeneratedMark)) { diff --git a/dev/tools/vitool/bin/main.dart b/dev/tools/vitool/bin/main.dart index 29d24d2bb39..9bab9d31da3 100644 --- a/dev/tools/vitool/bin/main.dart +++ b/dev/tools/vitool/bin/main.dart @@ -65,7 +65,7 @@ void main(List args) { } final List frames = [ - for (String filePath in argResults.rest) interpretSvg(filePath), + for (final String filePath in argResults.rest) interpretSvg(filePath), ]; final StringBuffer generatedSb = StringBuffer(); diff --git a/dev/tools/vitool/lib/vitool.dart b/dev/tools/vitool/lib/vitool.dart index 52e07e5a8de..df713c2535a 100644 --- a/dev/tools/vitool/lib/vitool.dart +++ b/dev/tools/vitool/lib/vitool.dart @@ -59,7 +59,7 @@ 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 (PathAnimation path in paths) + for (final PathAnimation path in paths) sb.write(path.toDart()); sb.write('$kIndent],\n'); sb.write(');'); @@ -117,11 +117,11 @@ class PathAnimation { final StringBuffer sb = StringBuffer(); sb.write('${kIndent * 2}const _PathFrames(\n'); sb.write('${kIndent * 3}opacities: const [\n'); - for (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 (PathCommandAnimation command in commands) + for (final PathCommandAnimation command in commands) sb.write(command.toDart()); sb.write('${kIndent * 3}],\n'); sb.write('${kIndent * 2}),\n'); @@ -166,9 +166,9 @@ class PathCommandAnimation { } final StringBuffer sb = StringBuffer(); sb.write('${kIndent * 4}const $dartCommandClass(\n'); - for (List> pointFrames in points) { + for (final List> pointFrames in points) { sb.write('${kIndent * 5}const [\n'); - for (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'); } @@ -201,7 +201,7 @@ FrameData interpretSvg(String svgFilePath) { List _interpretSvgGroup(List children, _Transform transform) { final List paths = []; - for (XmlNode node in children) { + for (final XmlNode node in children) { if (node.nodeType != XmlNodeType.ELEMENT) continue; final XmlElement element = node as XmlElement; @@ -304,7 +304,7 @@ class SvgPath { final SvgPathCommandBuilder commandsBuilder = SvgPathCommandBuilder(); if (!_pathCommandValidator.hasMatch(dAttr)) throw Exception('illegal or unsupported path d expression: $dAttr'); - for (Match match in _pathCommandMatcher.allMatches(dAttr)) { + for (final Match match in _pathCommandMatcher.allMatches(dAttr)) { final String commandType = match.group(1); final String pointStr = match.group(2); commands.add(commandsBuilder.build(commandType, parsePoints(pointStr))); @@ -469,7 +469,7 @@ Matrix3 _parseSvgTransform(String transform) { throw Exception('illegal or unsupported transform: $transform'); final Iterable matches =_transformCommand.allMatches(transform).toList().reversed; Matrix3 result = Matrix3.identity(); - for (Match m in matches) { + for (final Match m in matches) { final String command = m.group(1); final String params = m.group(2); if (command == 'translate') { diff --git a/examples/catalog/bin/sample_page.dart b/examples/catalog/bin/sample_page.dart index 2d22885266a..852e7180afb 100644 --- a/examples/catalog/bin/sample_page.dart +++ b/examples/catalog/bin/sample_page.dart @@ -146,7 +146,7 @@ void generate(String commit) { initialize(); final List samples = []; - for (FileSystemEntity entity in sampleDirectory.listSync()) { + for (final FileSystemEntity entity in sampleDirectory.listSync()) { if (entity is File && entity.path.endsWith('.dart')) { final SampleInfo sample = SampleInfo(entity, commit); if (sample.initialize()) // skip files that lack the Sample Catalog comment @@ -175,7 +175,7 @@ void generate(String commit) { ); // Write the sample app files, like animated_list.md - for (SampleInfo sample in samples) { + for (final SampleInfo sample in samples) { writeExpandedTemplate( outputFile(sample.sourceName + '.md'), inputFile('bin', 'sample_page.md.template').readAsStringSync(), @@ -188,13 +188,13 @@ void generate(String commit) { // that feature one class. For example AnimatedList_index.md would only // include samples that had AnimatedList in their "Classes:" list. final Map> classToSamples = >{}; - for (SampleInfo sample in samples) { - for (String className in sample.highlightedClasses) { + for (final SampleInfo sample in samples) { + for (final String className in sample.highlightedClasses) { classToSamples[className] ??= []; classToSamples[className].add(sample); } } - for (String className in classToSamples.keys) { + for (final String className in classToSamples.keys) { final Iterable entries = classToSamples[className].map((SampleInfo sample) { return expandTemplate(entryTemplate, sample.commentValues); }); @@ -238,7 +238,7 @@ void generate(String commit) { // For now, the website's index.json file must be updated by hand. logMessage('The following entries must appear in _data/catalog/widgets.json'); - for (String className in classToSamples.keys) + for (final String className in classToSamples.keys) logMessage('"sample": "${className}_index"'); } diff --git a/examples/catalog/test/expansion_tile_sample_test.dart b/examples/catalog/test/expansion_tile_sample_test.dart index 02b996bc918..9188652da23 100644 --- a/examples/catalog/test/expansion_tile_sample_test.dart +++ b/examples/catalog/test/expansion_tile_sample_test.dart @@ -13,11 +13,11 @@ void main() { await tester.pump(); // Initially only the top level EntryItems (the "chapters") are present. - for (Entry chapter in expansion_tile_sample.data) { + for (final Entry chapter in expansion_tile_sample.data) { expect(find.text(chapter.title), findsOneWidget); - for (Entry section in chapter.children) { + for (final Entry section in chapter.children) { expect(find.text(section.title), findsNothing); - for (Entry item in section.children) + for (final Entry item in section.children) expect(find.text(item.title), findsNothing); } } @@ -34,15 +34,15 @@ void main() { // Expand the chapters. Now the chapter and sections, but not the // items, should be present. - for (Entry chapter in expansion_tile_sample.data.reversed) + for (final Entry chapter in expansion_tile_sample.data.reversed) await tapEntry(chapter.title); - for (Entry chapter in expansion_tile_sample.data) { + for (final Entry chapter in expansion_tile_sample.data) { expect(find.text(chapter.title), findsOneWidget); - for (Entry section in chapter.children) { + for (final Entry section in chapter.children) { expect(find.text(section.title), findsOneWidget); await scrollUpOneEntry(); - for (Entry item in section.children) + for (final Entry item in section.children) expect(find.text(item.title), findsNothing); } await scrollUpOneEntry(); @@ -53,8 +53,8 @@ void main() { await tester.pumpAndSettle(); // Expand the sections. Now Widgets for all three levels should be present. - for (Entry chapter in expansion_tile_sample.data) { - for (Entry section in chapter.children) { + for (final Entry chapter in expansion_tile_sample.data) { + for (final Entry section in chapter.children) { await tapEntry(section.title); await scrollUpOneEntry(); } @@ -65,11 +65,11 @@ void main() { // Working in reverse order, so we don't need to do anymore scrolling, // check that everything is visible and close the sections and // chapters as we go up. - for (Entry chapter in expansion_tile_sample.data.reversed) { + for (final Entry chapter in expansion_tile_sample.data.reversed) { expect(find.text(chapter.title), findsOneWidget); - for (Entry section in chapter.children.reversed) { + for (final Entry section in chapter.children.reversed) { expect(find.text(section.title), findsOneWidget); - for (Entry item in section.children.reversed) + for (final Entry item in section.children.reversed) expect(find.text(item.title), findsOneWidget); await tapEntry(section.title); // close the section } @@ -77,11 +77,11 @@ void main() { } // Finally only the top level EntryItems (the "chapters") are present. - for (Entry chapter in expansion_tile_sample.data) { + for (final Entry chapter in expansion_tile_sample.data) { expect(find.text(chapter.title), findsOneWidget); - for (Entry section in chapter.children) { + for (final Entry section in chapter.children) { expect(find.text(section.title), findsNothing); - for (Entry item in section.children) + for (final Entry item in section.children) expect(find.text(item.title), findsNothing); } } diff --git a/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart b/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart index b4faf8821d4..6c2f4a55c43 100644 --- a/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart @@ -158,14 +158,14 @@ class _BottomNavigationDemoState extends State @override void dispose() { - for (NavigationIconView view in _navigationViews) + for (final NavigationIconView view in _navigationViews) view.controller.dispose(); super.dispose(); } Widget _buildTransitionsStack() { final List transitions = [ - for (NavigationIconView view in _navigationViews) view.transition(_type, context), + for (final NavigationIconView view in _navigationViews) view.transition(_type, context), ]; // We want to have the newly animating (fading in) views on top. diff --git a/examples/flutter_gallery/lib/demo/material/chip_demo.dart b/examples/flutter_gallery/lib/demo/material/chip_demo.dart index 15cd6451a6f..2ab9f9bc69e 100644 --- a/examples/flutter_gallery/lib/demo/material/chip_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/chip_demo.dart @@ -260,7 +260,7 @@ class _ChipDemoState extends State { Set allowedActions = {}; if (_selectedMaterial != null && _selectedMaterial.isNotEmpty) { - for (String tool in _selectedTools) { + for (final String tool in _selectedTools) { allowedActions.addAll(_toolActions[tool]); } allowedActions = allowedActions.intersection(_materialActions[_selectedMaterial]); diff --git a/examples/flutter_gallery/lib/demo/material/data_table_demo.dart b/examples/flutter_gallery/lib/demo/material/data_table_demo.dart index 7108f07cff9..da59408583a 100644 --- a/examples/flutter_gallery/lib/demo/material/data_table_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/data_table_demo.dart @@ -135,7 +135,7 @@ class DessertDataSource extends DataTableSource { int get selectedRowCount => _selectedCount; void _selectAll(bool checked) { - for (Dessert dessert in _desserts) + for (final Dessert dessert in _desserts) dessert.selected = checked; _selectedCount = checked ? _desserts.length : 0; notifyListeners(); diff --git a/examples/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart b/examples/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart index 3841d90a4e3..0e6130e459b 100644 --- a/examples/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart +++ b/examples/flutter_gallery/lib/demo/shrine/expanding_bottom_sheet.dart @@ -476,7 +476,7 @@ class _ProductThumbnailRowState extends State { return; } - for (int product in difference) { + for (final int product in difference) { if (_internalList.length < _list.length) { _list.remove(product); } else if (_internalList.length > _list.length) { diff --git a/examples/flutter_gallery/lib/demo/video_demo.dart b/examples/flutter_gallery/lib/demo/video_demo.dart index aa30d9a1c19..b5beb6f212b 100644 --- a/examples/flutter_gallery/lib/demo/video_demo.dart +++ b/examples/flutter_gallery/lib/demo/video_demo.dart @@ -294,8 +294,7 @@ class _ConnectivityOverlayState extends State { final Connectivity connectivity = Connectivity(); ConnectivityResult previousResult = await connectivity.checkConnectivity(); yield previousResult; - await for (ConnectivityResult result - in connectivity.onConnectivityChanged) { + await for (final ConnectivityResult result in connectivity.onConnectivityChanged) { if (result != previousResult) { yield result; previousResult = result; diff --git a/examples/flutter_gallery/lib/gallery/example_code_parser.dart b/examples/flutter_gallery/lib/gallery/example_code_parser.dart index f37f587d1b3..06e602bc8ec 100644 --- a/examples/flutter_gallery/lib/gallery/example_code_parser.dart +++ b/examples/flutter_gallery/lib/gallery/example_code_parser.dart @@ -27,7 +27,7 @@ Future _parseExampleCode(AssetBundle bundle) async { List codeBlock; String codeTag; - for (String line in lines) { + for (final String line in lines) { if (codeBlock == null) { // Outside a block. if (line.startsWith(_kStartTag)) { diff --git a/examples/flutter_gallery/lib/gallery/syntax_highlighter.dart b/examples/flutter_gallery/lib/gallery/syntax_highlighter.dart index a56368d7d7c..a2023b270d1 100644 --- a/examples/flutter_gallery/lib/gallery/syntax_highlighter.dart +++ b/examples/flutter_gallery/lib/gallery/syntax_highlighter.dart @@ -94,7 +94,7 @@ class DartSyntaxHighlighter extends SyntaxHighlighter { final List formattedText = []; int currentPosition = 0; - for (_HighlightSpan span in _spans) { + for (final _HighlightSpan span in _spans) { if (currentPosition != span.start) formattedText.add(TextSpan(text: _src.substring(currentPosition, span.start))); diff --git a/examples/flutter_gallery/test/live_smoketest.dart b/examples/flutter_gallery/test/live_smoketest.dart index cfae8d34ac1..76d6c0d81b3 100644 --- a/examples/flutter_gallery/test/live_smoketest.dart +++ b/examples/flutter_gallery/test/live_smoketest.dart @@ -61,10 +61,10 @@ Future main() async { print('Starting app...'); runApp(const GalleryApp(testMode: true)); final _LiveWidgetController controller = _LiveWidgetController(WidgetsBinding.instance); - for (GalleryDemoCategory category in kAllGalleryDemoCategories) { + for (final GalleryDemoCategory category in kAllGalleryDemoCategories) { print('Tapping "${category.name}" section...'); await controller.tap(find.text(category.name)); - for (GalleryDemo demo in kGalleryCategoryToDemos[category]) { + for (final GalleryDemo demo in kGalleryCategoryToDemos[category]) { final Finder demoItem = find.text(demo.title); print('Scrolling to "${demo.title}"...'); await controller.scrollIntoView(demoItem, alignment: 0.5); diff --git a/examples/flutter_gallery/test/smoke_test.dart b/examples/flutter_gallery/test/smoke_test.dart index 48ac18ba250..b91e64869bf 100644 --- a/examples/flutter_gallery/test/smoke_test.dart +++ b/examples/flutter_gallery/test/smoke_test.dart @@ -42,7 +42,7 @@ void verifyToStringOutput(String name, String route, String testString) { final List lines = testString.split('\n'); if (!testString.endsWith('\n')) reportToStringError(name, route, lines.length, lines, 'does not end with a line feed'); - for (String line in lines) { + for (final String line in lines) { lineNumber += 1; if (line == '' && lineNumber != lines.length) { reportToStringError(name, route, lineNumber, lines, 'found empty line'); @@ -157,11 +157,11 @@ Future smokeGallery(WidgetTester tester) async { expect(find.text(kGalleryTitle), findsOneWidget); - for (GalleryDemoCategory category in kAllGalleryDemoCategories) { + for (final GalleryDemoCategory category in kAllGalleryDemoCategories) { await Scrollable.ensureVisible(tester.element(find.text(category.name)), alignment: 0.5); await tester.tap(find.text(category.name)); await tester.pumpAndSettle(); - for (GalleryDemo demo in kGalleryCategoryToDemos[category]) { + for (final GalleryDemo demo in kGalleryCategoryToDemos[category]) { await Scrollable.ensureVisible(tester.element(find.text(demo.title)), alignment: 0.0); await smokeDemo(tester, demo); tester.binding.debugAssertNoTransientCallbacks('A transient callback was still active after running $demo'); diff --git a/examples/flutter_gallery/test_driver/transitions_perf_test.dart b/examples/flutter_gallery/test_driver/transitions_perf_test.dart index 2fd1a188be3..0f32b944e64 100644 --- a/examples/flutter_gallery/test_driver/transitions_perf_test.dart +++ b/examples/flutter_gallery/test_driver/transitions_perf_test.dart @@ -69,7 +69,7 @@ Future saveDurationsHistogram(List> events, String ou int frameStart; // Save the duration of the first frame after each 'Start Transition' event. - for (Map event in events) { + for (final Map event in events) { final String eventName = event['name'] as String; if (eventName == 'Start Transition') { assert(startEvent == null); @@ -143,7 +143,7 @@ Future runDemos(List demos, FlutterDriver driver) async { final SerializableFinder demoList = find.byValueKey('GalleryDemoList'); String currentDemoCategory; - for (String demo in demos) { + for (final String demo in demos) { if (kSkippedDemos.contains(demo)) continue; diff --git a/examples/layers/raw/touch_input.dart b/examples/layers/raw/touch_input.dart index 53aff0fe151..370c137f2fd 100644 --- a/examples/layers/raw/touch_input.dart +++ b/examples/layers/raw/touch_input.dart @@ -79,7 +79,7 @@ void beginFrame(Duration timeStamp) { void handlePointerDataPacket(ui.PointerDataPacket packet) { // The pointer packet contains a number of pointer movements, which we iterate // through and process. - for (ui.PointerData datum in packet.data) { + for (final ui.PointerData datum in packet.data) { if (datum.change == ui.PointerChange.down) { // If the pointer went down, we change the color of the circle to blue. color = const ui.Color(0xFF0000FF); diff --git a/examples/layers/rendering/touch_input.dart b/examples/layers/rendering/touch_input.dart index 149fcf16296..928fea7e3ab 100644 --- a/examples/layers/rendering/touch_input.dart +++ b/examples/layers/rendering/touch_input.dart @@ -94,7 +94,7 @@ class RenderDots extends RenderBox { canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFFFFFF)); // We iterate through our model and paint each dot. - for (Dot dot in _dots.values) + for (final Dot dot in _dots.values) dot.paint(canvas, offset); } } diff --git a/examples/layers/widgets/custom_render_box.dart b/examples/layers/widgets/custom_render_box.dart index 878aa646d87..ae914d1e0f3 100644 --- a/examples/layers/widgets/custom_render_box.dart +++ b/examples/layers/widgets/custom_render_box.dart @@ -31,7 +31,7 @@ class RenderDots extends RenderConstrainedBox { canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF)); final Paint paint = Paint()..color = const Color(0xFF00FF00); - for (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/stocks/lib/stock_data.dart b/examples/stocks/lib/stock_data.dart index 8451c5fe236..35a79cae52e 100644 --- a/examples/stocks/lib/stock_data.dart +++ b/examples/stocks/lib/stock_data.dart @@ -56,7 +56,7 @@ class StockData extends ChangeNotifier { bool get loading => _httpClient != null; void add(List data) { - for (List fields in data.cast>()) { + for (final List fields in data.cast>()) { final Stock stock = Stock.fromFields(fields.cast()); _symbols.add(stock.symbol); _stocks[stock.symbol] = stock; diff --git a/packages/flutter/lib/src/animation/listener_helpers.dart b/packages/flutter/lib/src/animation/listener_helpers.dart index 61203f8f3de..e8d66c7adca 100644 --- a/packages/flutter/lib/src/animation/listener_helpers.dart +++ b/packages/flutter/lib/src/animation/listener_helpers.dart @@ -118,7 +118,7 @@ mixin AnimationLocalListenersMixin { /// will not change which listeners are called during this iteration. void notifyListeners() { final List localListeners = List.from(_listeners); - for (VoidCallback listener in localListeners) { + for (final VoidCallback listener in localListeners) { try { if (_listeners.contains(listener)) listener(); @@ -187,7 +187,7 @@ mixin AnimationLocalStatusListenersMixin { /// will not change which listeners are called during this iteration. void notifyStatusListeners(AnimationStatus status) { final List localListeners = List.from(_statusListeners); - for (AnimationStatusListener listener in localListeners) { + for (final AnimationStatusListener listener in localListeners) { try { if (_statusListeners.contains(listener)) listener(status); diff --git a/packages/flutter/lib/src/animation/tween_sequence.dart b/packages/flutter/lib/src/animation/tween_sequence.dart index bb6fa5b9bf7..3d1712a239b 100644 --- a/packages/flutter/lib/src/animation/tween_sequence.dart +++ b/packages/flutter/lib/src/animation/tween_sequence.dart @@ -57,7 +57,7 @@ class TweenSequence extends Animatable { _items.addAll(items); double totalWeight = 0.0; - for (TweenSequenceItem item in _items) + for (final TweenSequenceItem item in _items) totalWeight += item.weight; assert(totalWeight > 0.0); diff --git a/packages/flutter/lib/src/cupertino/date_picker.dart b/packages/flutter/lib/src/cupertino/date_picker.dart index fab27b4057d..29c547f1032 100644 --- a/packages/flutter/lib/src/cupertino/date_picker.dart +++ b/packages/flutter/lib/src/cupertino/date_picker.dart @@ -1572,7 +1572,7 @@ class _CupertinoTimerPickerState extends State { // that has the biggest width. // - If two different 1-digit numbers are of the same width, their corresponding // 2 digit numbers are of the same width. - for (String input in numbers) { + for (final String input in numbers) { textPainter.text = TextSpan( text: input, style: textStyle, diff --git a/packages/flutter/lib/src/cupertino/segmented_control.dart b/packages/flutter/lib/src/cupertino/segmented_control.dart index 6a66b3d1681..fa721391734 100644 --- a/packages/flutter/lib/src/cupertino/segmented_control.dart +++ b/packages/flutter/lib/src/cupertino/segmented_control.dart @@ -257,13 +257,13 @@ class _SegmentedControlState extends State> void _updateAnimationControllers() { assert(mounted, 'This should only be called after didUpdateDependencies'); - for (AnimationController controller in _selectionControllers) { + for (final AnimationController controller in _selectionControllers) { controller.dispose(); } _selectionControllers.clear(); _childTweens.clear(); - for (T key in widget.children.keys) { + for (final T key in widget.children.keys) { final AnimationController animationController = createAnimationController(); if (widget.groupValue == key) { _childTweens.add(_reverseBackgroundColorTween); @@ -294,7 +294,7 @@ class _SegmentedControlState extends State> if (oldWidget.groupValue != widget.groupValue) { int index = 0; - for (T key in widget.children.keys) { + for (final T key in widget.children.keys) { if (widget.groupValue == key) { _childTweens[index] = _forwardBackgroundColorTween; _selectionControllers[index].forward(); @@ -309,7 +309,7 @@ class _SegmentedControlState extends State> @override void dispose() { - for (AnimationController animationController in _selectionControllers) { + for (final AnimationController animationController in _selectionControllers) { animationController.dispose(); } super.dispose(); @@ -364,7 +364,7 @@ class _SegmentedControlState extends State> int index = 0; int selectedIndex; int pressedIndex; - for (T currentKey in widget.children.keys) { + for (final T currentKey in widget.children.keys) { selectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex; pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex; @@ -629,7 +629,7 @@ class _RenderSegmentedControl extends RenderBox double maxHeight = _kMinSegmentedControlHeight; double childWidth = constraints.minWidth / childCount; - for (RenderBox child in getChildrenAsList()) { + for (final RenderBox child in getChildrenAsList()) { childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity)); } childWidth = math.min(childWidth, constraints.maxWidth / childCount); diff --git a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart index 2456693432b..78f68c637e5 100644 --- a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart +++ b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart @@ -301,7 +301,7 @@ class _SegmentedControlState extends State extends State extends State extends State extends State children = []; - for (T currentKey in keys) { + for (final T currentKey in keys) { final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith( fontWeight: _highlightTween.evaluate(_highlightControllers[currentKey]), ); @@ -829,7 +829,7 @@ class _RenderSegmentedControl extends RenderBox double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount; double maxHeight = _kMinSegmentedControlHeight; - for (RenderBox child in getChildrenAsList()) { + for (final RenderBox child in getChildrenAsList()) { childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding); } @@ -999,7 +999,7 @@ class _RenderSegmentedControl extends RenderBox final RRect thumbRRect = RRect.fromRectAndRadius(thumbRect.shift(offset), _kThumbRadius); - for (BoxShadow shadow in thumbShadow) { + for (final BoxShadow shadow in thumbShadow) { context.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint()); } diff --git a/packages/flutter/lib/src/cupertino/tab_scaffold.dart b/packages/flutter/lib/src/cupertino/tab_scaffold.dart index 5e013a98c9a..96c9b751210 100644 --- a/packages/flutter/lib/src/cupertino/tab_scaffold.dart +++ b/packages/flutter/lib/src/cupertino/tab_scaffold.dart @@ -523,10 +523,10 @@ class _TabSwitchingViewState extends State<_TabSwitchingView> { @override void dispose() { - for (FocusScopeNode focusScopeNode in tabFocusNodes) { + for (final FocusScopeNode focusScopeNode in tabFocusNodes) { focusScopeNode.dispose(); } - for (FocusScopeNode focusScopeNode in discardedNodes) { + for (final FocusScopeNode focusScopeNode in discardedNodes) { focusScopeNode.dispose(); } super.dispose(); diff --git a/packages/flutter/lib/src/cupertino/thumb_painter.dart b/packages/flutter/lib/src/cupertino/thumb_painter.dart index 19256122b93..c5a56c1c037 100644 --- a/packages/flutter/lib/src/cupertino/thumb_painter.dart +++ b/packages/flutter/lib/src/cupertino/thumb_painter.dart @@ -79,7 +79,7 @@ class CupertinoThumbPainter { Radius.circular(rect.shortestSide / 2.0), ); - for (BoxShadow shadow in shadows) + for (final BoxShadow shadow in shadows) canvas.drawRRect(rrect.shift(shadow.offset), shadow.toPaint()); canvas.drawRRect( diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index 0c88184b337..7f4ffed2cb4 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -556,7 +556,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'), ]; int i = 1; - for (DiagnosticsNode summary in summaries) { + for (final DiagnosticsNode summary in summaries) { message.add(DiagnosticsProperty('Summary $i', summary, expandableValue : true)); i += 1; } @@ -683,7 +683,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti final RegExp packageParser = RegExp(r'^([^:]+):(.+)$'); final List result = []; final List skipped = []; - for (String line in frames) { + for (final String line in frames) { final Match match = stackParser.firstMatch(line); if (match != null) { assert(match.groupCount == 2); @@ -834,7 +834,7 @@ class _FlutterErrorDetailsNode extends DiagnosticableNode { return null; } Iterable properties = builder.properties; - for (DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) { + for (final DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) { properties = transformer(properties); } return DiagnosticPropertiesBuilder.fromProperties(properties.toList()); diff --git a/packages/flutter/lib/src/foundation/change_notifier.dart b/packages/flutter/lib/src/foundation/change_notifier.dart index 4174f0b05ca..3f7cac30d81 100644 --- a/packages/flutter/lib/src/foundation/change_notifier.dart +++ b/packages/flutter/lib/src/foundation/change_notifier.dart @@ -200,7 +200,7 @@ class ChangeNotifier implements Listenable { assert(_debugAssertNotDisposed()); if (_listeners != null) { final List localListeners = List.from(_listeners); - for (VoidCallback listener in localListeners) { + for (final VoidCallback listener in localListeners) { try { if (_listeners.contains(listener)) listener(); diff --git a/packages/flutter/lib/src/foundation/collections.dart b/packages/flutter/lib/src/foundation/collections.dart index 5fabaeb7062..9caeb50017a 100644 --- a/packages/flutter/lib/src/foundation/collections.dart +++ b/packages/flutter/lib/src/foundation/collections.dart @@ -26,7 +26,7 @@ bool setEquals(Set a, Set b) { return false; if (identical(a, b)) return true; - for (T value in a) { + for (final T value in a) { if (!b.contains(value)) return false; } @@ -84,7 +84,7 @@ bool mapEquals(Map a, Map b) { return false; if (identical(a, b)) return true; - for (T key in a.keys) { + for (final T key in a.keys) { if (!b.containsKey(key) || b[key] != a[key]) { return false; } diff --git a/packages/flutter/lib/src/foundation/consolidate_response.dart b/packages/flutter/lib/src/foundation/consolidate_response.dart index f1f770095ad..a41d84a6e72 100644 --- a/packages/flutter/lib/src/foundation/consolidate_response.dart +++ b/packages/flutter/lib/src/foundation/consolidate_response.dart @@ -115,7 +115,7 @@ class _OutputBuffer extends ByteConversionSinkBase { } _bytes = Uint8List(_contentLength); int offset = 0; - for (List chunk in _chunks) { + for (final List chunk in _chunks) { _bytes.setRange(offset, offset + chunk.length, chunk); offset += chunk.length; } diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 5fa29c27b6c..104532529c1 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -843,7 +843,7 @@ class _PrefixedStringBuilder { ); int i = 0; final int length = lines.length; - for (String line in lines) { + for (final String line in lines) { i++; _writeLine( line, @@ -1132,7 +1132,7 @@ class TextTreeRenderer { const int maxLines = 25; int lines = 0; void visitor(DiagnosticsNode node) { - for (DiagnosticsNode child in node.getChildren()) { + for (final DiagnosticsNode child in node.getChildren()) { if (lines < maxLines) { depth += 1; descendants.add('$prefixOtherLines${" " * depth}$child'); @@ -2508,7 +2508,7 @@ class FlagsSummary extends DiagnosticsProperty> { // For a null value, it is omitted unless `includeEmtpy` is true and // [ifEntryNull] contains a corresponding description. Iterable _formattedValues() sync* { - for (MapEntry entry in value.entries) { + for (final MapEntry entry in value.entries) { if (entry.value != null) { yield entry.key; } diff --git a/packages/flutter/lib/src/foundation/licenses.dart b/packages/flutter/lib/src/foundation/licenses.dart index fcda6ac42b9..084b95440a9 100644 --- a/packages/flutter/lib/src/foundation/licenses.dart +++ b/packages/flutter/lib/src/foundation/licenses.dart @@ -310,7 +310,7 @@ class LicenseRegistry { static Stream get licenses async* { if (_collectors == null) return; - for (LicenseEntryCollector collector in _collectors) + for (final LicenseEntryCollector collector in _collectors) yield* collector(); } diff --git a/packages/flutter/lib/src/gestures/arena.dart b/packages/flutter/lib/src/gestures/arena.dart index 47046eeaa63..d59ab635ca8 100644 --- a/packages/flutter/lib/src/gestures/arena.dart +++ b/packages/flutter/lib/src/gestures/arena.dart @@ -256,7 +256,7 @@ class GestureArenaManager { assert(state.eagerWinner == null || state.eagerWinner == member); assert(!state.isOpen); _arenas.remove(pointer); - for (GestureArenaMember rejectedMember in state.members) { + for (final GestureArenaMember rejectedMember in state.members) { if (rejectedMember != member) rejectedMember.rejectGesture(pointer); } diff --git a/packages/flutter/lib/src/gestures/binding.dart b/packages/flutter/lib/src/gestures/binding.dart index 1a10df47058..55e7174e04c 100644 --- a/packages/flutter/lib/src/gestures/binding.dart +++ b/packages/flutter/lib/src/gestures/binding.dart @@ -193,7 +193,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H } return; } - for (HitTestEntry entry in hitTestResult.path) { + for (final HitTestEntry entry in hitTestResult.path) { try { entry.target.handleEvent(event.transformed(entry.transform), entry); } catch (exception, stack) { diff --git a/packages/flutter/lib/src/gestures/converter.dart b/packages/flutter/lib/src/gestures/converter.dart index a93a262dc73..0093c26b0bf 100644 --- a/packages/flutter/lib/src/gestures/converter.dart +++ b/packages/flutter/lib/src/gestures/converter.dart @@ -42,7 +42,7 @@ class PointerEventConverter { /// from physical coordinates to logical pixels. See the discussion at /// [PointerEvent] for more details on the [PointerEvent] coordinate space. static Iterable expand(Iterable data, double devicePixelRatio) sync* { - for (ui.PointerData datum in data) { + for (final ui.PointerData datum in data) { final Offset position = Offset(datum.physicalX, datum.physicalY) / devicePixelRatio; final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio; final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio); diff --git a/packages/flutter/lib/src/gestures/mouse_tracking.dart b/packages/flutter/lib/src/gestures/mouse_tracking.dart index 563b12ba832..c8e42c125a1 100644 --- a/packages/flutter/lib/src/gestures/mouse_tracking.dart +++ b/packages/flutter/lib/src/gestures/mouse_tracking.dart @@ -410,7 +410,7 @@ class MouseTracker extends ChangeNotifier { // We can safely use `_mouseStates` here without worrying about the removed // state, because `targetEvent` should be null when `_mouseStates` is used. final Iterable<_MouseState> dirtyStates = targetEvent == null ? _mouseStates.values : <_MouseState>[targetState]; - for (_MouseState dirtyState in dirtyStates) { + for (final _MouseState dirtyState in dirtyStates) { final LinkedHashSet nextAnnotations = _findAnnotations(dirtyState); final LinkedHashSet lastAnnotations = dirtyState.replaceAnnotations(nextAnnotations); handleUpdatedDevice(dirtyState, lastAnnotations); diff --git a/packages/flutter/lib/src/gestures/multitap.dart b/packages/flutter/lib/src/gestures/multitap.dart index 57e9a7b5bfd..ed31657a015 100644 --- a/packages/flutter/lib/src/gestures/multitap.dart +++ b/packages/flutter/lib/src/gestures/multitap.dart @@ -505,7 +505,7 @@ class MultiTapGestureRecognizer extends GestureRecognizer { @override void dispose() { final List<_TapGesture> localGestures = List<_TapGesture>.from(_gestureMap.values); - for (_TapGesture gesture in localGestures) + for (final _TapGesture gesture in localGestures) gesture.cancel(); // Rejection of each gesture should cause it to be removed from our map assert(_gestureMap.isEmpty); diff --git a/packages/flutter/lib/src/gestures/recognizer.dart b/packages/flutter/lib/src/gestures/recognizer.dart index 3b988c1e046..af81933d47d 100644 --- a/packages/flutter/lib/src/gestures/recognizer.dart +++ b/packages/flutter/lib/src/gestures/recognizer.dart @@ -251,7 +251,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer { void resolve(GestureDisposition disposition) { final List localEntries = List.from(_entries.values); _entries.clear(); - for (GestureArenaEntry entry in localEntries) + for (final GestureArenaEntry entry in localEntries) entry.resolve(disposition); } @@ -270,7 +270,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer { @override void dispose() { resolve(GestureDisposition.rejected); - for (int pointer in _trackedPointers) + for (final int pointer in _trackedPointers) GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent); _trackedPointers.clear(); assert(_entries.isEmpty); diff --git a/packages/flutter/lib/src/gestures/scale.dart b/packages/flutter/lib/src/gestures/scale.dart index 83b996ae22d..bf5d9595741 100644 --- a/packages/flutter/lib/src/gestures/scale.dart +++ b/packages/flutter/lib/src/gestures/scale.dart @@ -338,7 +338,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { // Compute the focal point Offset focalPoint = Offset.zero; - for (int pointer in _pointerLocations.keys) + for (final int pointer in _pointerLocations.keys) focalPoint += _pointerLocations[pointer]; _currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero; @@ -348,7 +348,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { double totalDeviation = 0.0; double totalHorizontalDeviation = 0.0; double totalVerticalDeviation = 0.0; - for (int pointer in _pointerLocations.keys) { + for (final int pointer in _pointerLocations.keys) { totalDeviation += (_currentFocalPoint - _pointerLocations[pointer]).distance; totalHorizontalDeviation += (_currentFocalPoint.dx - _pointerLocations[pointer].dx).abs(); totalVerticalDeviation += (_currentFocalPoint.dy - _pointerLocations[pointer].dy).abs(); diff --git a/packages/flutter/lib/src/gestures/team.dart b/packages/flutter/lib/src/gestures/team.dart index 2dcdd738a58..128a323ec3e 100644 --- a/packages/flutter/lib/src/gestures/team.dart +++ b/packages/flutter/lib/src/gestures/team.dart @@ -34,7 +34,7 @@ class _CombiningGestureArenaMember extends GestureArenaMember { assert(_winner != null || _members.isNotEmpty); _close(); _winner ??= _owner.captain ?? _members[0]; - for (GestureArenaMember member in _members) { + for (final GestureArenaMember member in _members) { if (member != _winner) member.rejectGesture(pointer); } @@ -45,7 +45,7 @@ class _CombiningGestureArenaMember extends GestureArenaMember { void rejectGesture(int pointer) { assert(_pointer == pointer); _close(); - for (GestureArenaMember member in _members) + for (final GestureArenaMember member in _members) member.rejectGesture(pointer); } diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index 55e7e58d332..44fc5397f8a 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -488,7 +488,7 @@ class _LicensePageState extends State { debugFlowId = flow.id; return true; }()); - await for (LicenseEntry license in LicenseRegistry.licenses) { + await for (final LicenseEntry license in LicenseRegistry.licenses) { if (!mounted) { return; } @@ -523,7 +523,7 @@ class _LicensePageState extends State { textAlign: TextAlign.center, ), )); - for (LicenseParagraph paragraph in paragraphs) { + for (final LicenseParagraph paragraph in paragraphs) { if (paragraph.indent == LicenseParagraph.centeredIndent) { _licenses.add(Padding( padding: const EdgeInsets.only(top: 16.0), diff --git a/packages/flutter/lib/src/material/animated_icons/animated_icons.dart b/packages/flutter/lib/src/material/animated_icons/animated_icons.dart index 4c7d9b1d264..97366e44cbd 100644 --- a/packages/flutter/lib/src/material/animated_icons/animated_icons.dart +++ b/packages/flutter/lib/src/material/animated_icons/animated_icons.dart @@ -162,7 +162,7 @@ class _AnimatedIconPainter extends CustomPainter { } final double clampedProgress = progress.value.clamp(0.0, 1.0) as double; - for (_PathFrames path in paths) + for (final _PathFrames path in paths) path.paint(canvas, color, uiPathFactory, clampedProgress); } @@ -203,7 +203,7 @@ class _PathFrames { ..style = PaintingStyle.fill ..color = color.withOpacity(color.opacity * opacity); final ui.Path path = uiPathFactory(); - for (_PathCommand command in commands) + for (final _PathCommand command in commands) command.apply(path, progress); canvas.drawPath(path, paint); } diff --git a/packages/flutter/lib/src/material/arc.dart b/packages/flutter/lib/src/material/arc.dart index b6bf4ab7d40..94ddec00129 100644 --- a/packages/flutter/lib/src/material/arc.dart +++ b/packages/flutter/lib/src/material/arc.dart @@ -199,7 +199,7 @@ typedef _KeyFunc = double Function(T input); T _maxBy(Iterable input, _KeyFunc keyFunc) { T maxValue; double maxKey; - for (T value in input) { + for (final T value in input) { final double key = keyFunc(value); if (maxKey == null || key > maxKey) { maxValue = value; diff --git a/packages/flutter/lib/src/material/bottom_navigation_bar.dart b/packages/flutter/lib/src/material/bottom_navigation_bar.dart index 9ea673d5902..2b6856765e6 100644 --- a/packages/flutter/lib/src/material/bottom_navigation_bar.dart +++ b/packages/flutter/lib/src/material/bottom_navigation_bar.dart @@ -670,9 +670,9 @@ class _BottomNavigationBarState extends State with TickerPr static final Animatable _flexTween = Tween(begin: 1.0, end: 1.5); void _resetState() { - for (AnimationController controller in _controllers) + for (final AnimationController controller in _controllers) controller.dispose(); - for (_Circle circle in _circles) + for (final _Circle circle in _circles) circle.dispose(); _circles.clear(); @@ -708,9 +708,9 @@ class _BottomNavigationBarState extends State with TickerPr @override void dispose() { - for (AnimationController controller in _controllers) + for (final AnimationController controller in _controllers) controller.dispose(); - for (_Circle circle in _circles) + for (final _Circle circle in _circles) circle.dispose(); super.dispose(); } @@ -984,7 +984,7 @@ class _RadialPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - for (_Circle circle in circles) { + for (final _Circle circle in circles) { final Paint paint = Paint()..color = circle.color; final Rect rect = Rect.fromLTWH(0.0, 0.0, size.width, size.height); canvas.clipRect(rect); diff --git a/packages/flutter/lib/src/material/chip.dart b/packages/flutter/lib/src/material/chip.dart index 85b0e355612..9ac390e3ac4 100644 --- a/packages/flutter/lib/src/material/chip.dart +++ b/packages/flutter/lib/src/material/chip.dart @@ -216,7 +216,7 @@ abstract class DeletableChipAttributes { /// ]; /// /// Iterable get actorWidgets sync* { - /// for (Actor actor in _cast) { + /// for (final Actor actor in _cast) { /// yield Padding( /// padding: const EdgeInsets.all(4.0), /// child: Chip( @@ -1056,7 +1056,7 @@ class ChoiceChip extends StatelessWidget /// List _filters = []; /// /// Iterable get actorWidgets sync* { -/// for (ActorFilterEntry actor in _cast) { +/// for (final ActorFilterEntry actor in _cast) { /// yield Padding( /// padding: const EdgeInsets.all(4.0), /// child: FilterChip( @@ -2316,7 +2316,7 @@ class _RenderChip extends RenderBox { @override void attach(PipelineOwner owner) { super.attach(owner); - for (RenderBox child in _children) { + for (final RenderBox child in _children) { child.attach(owner); } } @@ -2324,7 +2324,7 @@ class _RenderChip extends RenderBox { @override void detach() { super.detach(); - for (RenderBox child in _children) { + for (final RenderBox child in _children) { child.detach(); } } diff --git a/packages/flutter/lib/src/material/data_table.dart b/packages/flutter/lib/src/material/data_table.dart index 3f87bfcd402..b224aa121c3 100644 --- a/packages/flutter/lib/src/material/data_table.dart +++ b/packages/flutter/lib/src/material/data_table.dart @@ -454,7 +454,7 @@ class DataTable extends StatelessWidget { if (onSelectAll != null) { onSelectAll(checked); } else { - for (DataRow row in rows) { + for (final DataRow row in rows) { if ((row.onSelectChanged != null) && (row.selected != checked)) row.onSelectChanged(checked); } @@ -648,7 +648,7 @@ class DataTable extends StatelessWidget { onCheckboxChanged: _handleSelectAll, ); rowIndex = 1; - for (DataRow row in rows) { + for (final DataRow row in rows) { tableRows[rowIndex].children[0] = _buildCheckbox( color: theme.accentColor, checked: row.selected, @@ -699,7 +699,7 @@ class DataTable extends StatelessWidget { ascending: sortAscending, ); rowIndex = 1; - for (DataRow row in rows) { + for (final DataRow row in rows) { final DataCell cell = row.cells[dataColumnIndex]; tableRows[rowIndex].children[displayColumnIndex] = _buildDataCell( context: context, diff --git a/packages/flutter/lib/src/material/expansion_panel.dart b/packages/flutter/lib/src/material/expansion_panel.dart index 6a8df6b1e36..3f56eb48e72 100644 --- a/packages/flutter/lib/src/material/expansion_panel.dart +++ b/packages/flutter/lib/src/material/expansion_panel.dart @@ -389,7 +389,7 @@ class _ExpansionPanelListState extends State { bool _allIdentifiersUnique() { final Map identifierMap = {}; - for (ExpansionPanelRadio child in widget.children.cast()) { + for (final ExpansionPanelRadio child in widget.children.cast()) { identifierMap[child.value] = true; } return identifierMap.length == widget.children.length; @@ -427,7 +427,7 @@ class _ExpansionPanelListState extends State { } ExpansionPanelRadio searchPanelByValue(List panels, Object value) { - for (ExpansionPanelRadio panel in panels) { + for (final ExpansionPanelRadio panel in panels) { if (panel.value == value) return panel; } diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 647484218cb..4fb38dbbac1 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -737,12 +737,12 @@ class _InkResponseState extends State with AutomaticKe if (_splashes != null) { final Set splashes = _splashes; _splashes = null; - for (InteractiveInkFeature splash in splashes) + for (final InteractiveInkFeature splash in splashes) splash.dispose(); _currentSplash = null; } assert(_currentSplash == null); - for (_HighlightType highlight in _highlights.keys) { + for (final _HighlightType highlight in _highlights.keys) { _highlights[highlight]?.dispose(); _highlights[highlight] = null; } @@ -768,7 +768,7 @@ class _InkResponseState extends State with AutomaticKe Widget build(BuildContext context) { assert(widget.debugCheckContext(context)); super.build(context); // See AutomaticKeepAliveClientMixin. - for (_HighlightType type in _highlights.keys) { + for (final _HighlightType type in _highlights.keys) { _highlights[type]?.color = getHighlightColorForType(type); } _currentSplash?.color = widget.splashColor ?? Theme.of(context).splashColor; diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index 1ce7920716b..e868c6a69ef 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -805,14 +805,14 @@ class _RenderDecoration extends RenderBox { @override void attach(PipelineOwner owner) { super.attach(owner); - for (RenderBox child in _children) + for (final RenderBox child in _children) child.attach(owner); } @override void detach() { super.detach(); - for (RenderBox child in _children) + for (final RenderBox child in _children) child.detach(); } @@ -1199,7 +1199,7 @@ class _RenderDecoration extends RenderBox { double _lineHeight(double width, List boxes) { double height = 0.0; - for (RenderBox box in boxes) { + for (final RenderBox box in boxes) { if (box == null) continue; height = math.max(_minHeight(box, width), height); @@ -1448,7 +1448,7 @@ class _RenderDecoration extends RenderBox { @override bool hitTestChildren(BoxHitTestResult result, { @required Offset position }) { assert(position != null); - for (RenderBox child in _children) { + for (final RenderBox child in _children) { // TODO(hansmuller): label must be handled specially since we've transformed it final Offset offset = _boxParentData(child).offset; final bool isHit = result.addWithPaintOffset( diff --git a/packages/flutter/lib/src/material/list_tile.dart b/packages/flutter/lib/src/material/list_tile.dart index 93836a277b6..80eadc38d62 100644 --- a/packages/flutter/lib/src/material/list_tile.dart +++ b/packages/flutter/lib/src/material/list_tile.dart @@ -1209,14 +1209,14 @@ class _RenderListTile extends RenderBox { @override void attach(PipelineOwner owner) { super.attach(owner); - for (RenderBox child in _children) + for (final RenderBox child in _children) child.attach(owner); } @override void detach() { super.detach(); - for (RenderBox child in _children) + for (final RenderBox child in _children) child.detach(); } @@ -1479,7 +1479,7 @@ class _RenderListTile extends RenderBox { @override bool hitTestChildren(BoxHitTestResult result, { @required Offset position }) { assert(position != null); - for (RenderBox child in _children) { + for (final RenderBox child in _children) { final BoxParentData parentData = child.parentData as BoxParentData; final bool isHit = result.addWithPaintOffset( offset: parentData.offset, diff --git a/packages/flutter/lib/src/material/material.dart b/packages/flutter/lib/src/material/material.dart index 679542476b1..39f3d2aad59 100644 --- a/packages/flutter/lib/src/material/material.dart +++ b/packages/flutter/lib/src/material/material.dart @@ -524,7 +524,7 @@ class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController canvas.save(); canvas.translate(offset.dx, offset.dy); canvas.clipRect(Offset.zero & size); - for (InkFeature inkFeature in _inkFeatures) + for (final InkFeature inkFeature in _inkFeatures) inkFeature._paint(canvas); canvas.restore(); } diff --git a/packages/flutter/lib/src/material/mergeable_material.dart b/packages/flutter/lib/src/material/mergeable_material.dart index b87251f193a..e60d5fabf6e 100644 --- a/packages/flutter/lib/src/material/mergeable_material.dart +++ b/packages/flutter/lib/src/material/mergeable_material.dart @@ -204,7 +204,7 @@ class _MergeableMaterialState extends State with TickerProvid @override void dispose() { - for (MergeableMaterialItem child in _children) { + for (final MergeableMaterialItem child in _children) { if (child is MaterialGap) _animationTuples[child.key].controller.dispose(); } @@ -687,7 +687,7 @@ class _RenderMergeableMaterialListBody extends RenderListBody { List boxShadows; void _paintShadows(Canvas canvas, Rect rect) { - for (BoxShadow boxShadow in boxShadows) { + for (final BoxShadow boxShadow in boxShadows) { final Paint paint = boxShadow.toPaint(); // TODO(dragostis): Right now, we are only interpolating the border radii // of the visible Material slices, not the shadows; they are not getting diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 5a3f2c76dbf..e1b86781f3a 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -2113,7 +2113,7 @@ class ScaffoldState extends State with TickerProviderStateMixin { _snackBarTimer?.cancel(); _snackBarTimer = null; _geometryNotifier.dispose(); - for (_StandardBottomSheet bottomSheet in _dismissedBottomSheets) { + for (final _StandardBottomSheet bottomSheet in _dismissedBottomSheets) { bottomSheet.animationController?.dispose(); } if (_currentBottomSheet != null) { diff --git a/packages/flutter/lib/src/material/tabs.dart b/packages/flutter/lib/src/material/tabs.dart index cc159d04aa7..740c08530fa 100644 --- a/packages/flutter/lib/src/material/tabs.dart +++ b/packages/flutter/lib/src/material/tabs.dart @@ -750,7 +750,7 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// [AppBar] uses this size to compute its own preferred size. @override Size get preferredSize { - for (Widget item in tabs) { + for (final Widget item in tabs) { if (item is Tab) { final Tab tab = item; if (tab.text != null && tab.icon != null) diff --git a/packages/flutter/lib/src/material/time_picker.dart b/packages/flutter/lib/src/material/time_picker.dart index b02f6917a1f..d6ddd703035 100644 --- a/packages/flutter/lib/src/material/time_picker.dart +++ b/packages/flutter/lib/src/material/time_picker.dart @@ -685,7 +685,7 @@ class _TimePickerHeaderLayout extends MultiChildLayoutDelegate { void _positionPivoted(double width, double y, Map<_TimePickerHeaderId, Size> childSizes, List<_TimePickerHeaderFragment> fragments, int pivotIndex) { double tailWidth = childSizes[fragments[pivotIndex].layoutId].width / 2.0; - for (_TimePickerHeaderFragment fragment in fragments.skip(pivotIndex + 1)) { + for (final _TimePickerHeaderFragment fragment in fragments.skip(pivotIndex + 1)) { tailWidth += childSizes[fragment.layoutId].width + fragment.startMargin; } @@ -703,7 +703,7 @@ class _TimePickerHeaderLayout extends MultiChildLayoutDelegate { void _positionPiece(double width, double centeredAroundY, Map<_TimePickerHeaderId, Size> childSizes, List<_TimePickerHeaderFragment> fragments) { double pieceWidth = 0.0; double nextMargin = 0.0; - for (_TimePickerHeaderFragment fragment in fragments) { + for (final _TimePickerHeaderFragment fragment in fragments) { final Size childSize = childSizes[fragment.layoutId]; pieceWidth += childSize.width + nextMargin; // Delay application of margin until next element because margin of the @@ -927,7 +927,7 @@ class _DialPainter extends CustomPainter { final double labelThetaIncrement = -_kTwoPi / labels.length; double labelTheta = math.pi / 2.0; - for (_TappableLabel label in labels) { + for (final _TappableLabel label in labels) { final TextPainter labelPainter = label.painter; final Offset labelOffset = Offset(-labelPainter.width / 2.0, -labelPainter.height / 2.0); labelPainter.paint(canvas, getOffsetForTheta(labelTheta, ring) + labelOffset); @@ -1339,7 +1339,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { } List<_TappableLabel> _build24HourInnerRing(TextTheme textTheme) => <_TappableLabel>[ - for (TimeOfDay timeOfDay in _amHours) + for (final TimeOfDay timeOfDay in _amHours) _buildTappableLabel( textTheme, timeOfDay.hour, @@ -1351,7 +1351,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ]; List<_TappableLabel> _build24HourOuterRing(TextTheme textTheme) => <_TappableLabel>[ - for (TimeOfDay timeOfDay in _pmHours) + for (final TimeOfDay timeOfDay in _pmHours) _buildTappableLabel( textTheme, timeOfDay.hour, @@ -1363,7 +1363,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ]; List<_TappableLabel> _build12HourOuterRing(TextTheme textTheme) => <_TappableLabel>[ - for (TimeOfDay timeOfDay in _amHours) + for (final TimeOfDay timeOfDay in _amHours) _buildTappableLabel( textTheme, timeOfDay.hour, @@ -1391,7 +1391,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ]; return <_TappableLabel>[ - for (TimeOfDay timeOfDay in _minuteMarkerValues) + for (final TimeOfDay timeOfDay in _minuteMarkerValues) _buildTappableLabel( textTheme, timeOfDay.minute, diff --git a/packages/flutter/lib/src/painting/binding.dart b/packages/flutter/lib/src/painting/binding.dart index 8adac804f89..cbdb882dbca 100644 --- a/packages/flutter/lib/src/painting/binding.dart +++ b/packages/flutter/lib/src/painting/binding.dart @@ -128,7 +128,7 @@ class _SystemFontsNotifier extends Listenable { final Set _systemFontsCallbacks = {}; void notifyListeners () { - for (VoidCallback callback in _systemFontsCallbacks) { + for (final VoidCallback callback in _systemFontsCallbacks) { callback(); } } diff --git a/packages/flutter/lib/src/painting/borders.dart b/packages/flutter/lib/src/painting/borders.dart index 5725e3e3816..f5517c89a81 100644 --- a/packages/flutter/lib/src/painting/borders.dart +++ b/packages/flutter/lib/src/painting/borders.dart @@ -603,7 +603,7 @@ class _CompoundBorder extends ShapeBorder { @override void paint(Canvas canvas, Rect rect, { TextDirection textDirection }) { - for (ShapeBorder border in borders) { + for (final ShapeBorder border in borders) { border.paint(canvas, rect, textDirection: textDirection); rect = border.dimensions.resolve(textDirection).deflateRect(rect); } diff --git a/packages/flutter/lib/src/painting/box_decoration.dart b/packages/flutter/lib/src/painting/box_decoration.dart index bb3b7b43530..95ec70f3f4c 100644 --- a/packages/flutter/lib/src/painting/box_decoration.dart +++ b/packages/flutter/lib/src/painting/box_decoration.dart @@ -433,7 +433,7 @@ class _BoxDecorationPainter extends BoxPainter { void _paintShadows(Canvas canvas, Rect rect, TextDirection textDirection) { if (_decoration.boxShadow == null) return; - for (BoxShadow boxShadow in _decoration.boxShadow) { + for (final BoxShadow boxShadow in _decoration.boxShadow) { final Paint paint = boxShadow.toPaint(); final Rect bounds = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius); _paintBox(canvas, bounds, paint, textDirection); diff --git a/packages/flutter/lib/src/painting/decoration_image.dart b/packages/flutter/lib/src/painting/decoration_image.dart index 69b35971635..e7dfe173c71 100644 --- a/packages/flutter/lib/src/painting/decoration_image.dart +++ b/packages/flutter/lib/src/painting/decoration_image.dart @@ -443,14 +443,14 @@ void paintImage({ if (repeat == ImageRepeat.noRepeat) { canvas.drawImageRect(image, sourceRect, destinationRect, paint); } else { - for (Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) + for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) canvas.drawImageRect(image, sourceRect, tileRect, paint); } } else { if (repeat == ImageRepeat.noRepeat) { canvas.drawImageNine(image, centerSlice, destinationRect, paint); } else { - for (Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) + for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) canvas.drawImageNine(image, centerSlice, tileRect, paint); } } diff --git a/packages/flutter/lib/src/painting/image_resolution.dart b/packages/flutter/lib/src/painting/image_resolution.dart index fcc0bd7179f..17e6eb811ec 100644 --- a/packages/flutter/lib/src/painting/image_resolution.dart +++ b/packages/flutter/lib/src/painting/image_resolution.dart @@ -233,7 +233,7 @@ class AssetImage extends AssetBundleImageProvider { return main; // TODO(ianh): Consider moving this parsing logic into _manifestParser. final SplayTreeMap mapping = SplayTreeMap(); - for (String candidate in candidates) + for (final String candidate in candidates) mapping[_parseScale(candidate)] = candidate; // TODO(ianh): implement support for config.locale, config.textDirection, // config.size, config.platform (then document this over in the Image.asset diff --git a/packages/flutter/lib/src/painting/image_stream.dart b/packages/flutter/lib/src/painting/image_stream.dart index 82e62a773d9..4b062f99c03 100644 --- a/packages/flutter/lib/src/painting/image_stream.dart +++ b/packages/flutter/lib/src/painting/image_stream.dart @@ -402,7 +402,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { // Make a copy to allow for concurrent modification. final List localListeners = List.from(_listeners); - for (ImageStreamListener listener in localListeners) { + for (final ImageStreamListener listener in localListeners) { try { listener.onImage(image, false); } catch (exception, stack) { @@ -469,7 +469,7 @@ abstract class ImageStreamCompleter extends Diagnosticable { if (localErrorListeners.isEmpty) { FlutterError.reportError(_currentError); } else { - for (ImageErrorListener errorListener in localErrorListeners) { + for (final ImageErrorListener errorListener in localErrorListeners) { try { errorListener(exception, stack); } catch (exception, stack) { @@ -604,7 +604,7 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { .map((ImageStreamListener listener) => listener.onChunk) .where((ImageChunkListener chunkListener) => chunkListener != null) .toList(); - for (ImageChunkListener listener in localListeners) { + for (final ImageChunkListener listener in localListeners) { listener(event); } } diff --git a/packages/flutter/lib/src/painting/shader_warm_up.dart b/packages/flutter/lib/src/painting/shader_warm_up.dart index 608534f1ced..420f334588c 100644 --- a/packages/flutter/lib/src/painting/shader_warm_up.dart +++ b/packages/flutter/lib/src/painting/shader_warm_up.dart @@ -171,7 +171,7 @@ class DefaultShaderWarmUp extends ShaderWarmUp { // Warm up path stroke and fill shaders. for (int i = 0; i < paths.length; i += 1) { canvas.save(); - for (ui.Paint paint in paints) { + for (final ui.Paint paint in paints) { canvas.drawPath(paths[i], paint); canvas.translate(drawCallSpacing, 0.0); } @@ -202,7 +202,7 @@ class DefaultShaderWarmUp extends ShaderWarmUp { // // Add an integral or fractional translation to trigger Skia's non-AA or AA // optimizations (as did before in normal FillRectOp in rrect clip cases). - for (double fraction in [0.0, 0.5]) { + for (final double fraction in [0.0, 0.5]) { canvas ..save() ..translate(fraction, fraction) diff --git a/packages/flutter/lib/src/painting/text_span.dart b/packages/flutter/lib/src/painting/text_span.dart index 93d49d02a05..d4ea24918a8 100644 --- a/packages/flutter/lib/src/painting/text_span.dart +++ b/packages/flutter/lib/src/painting/text_span.dart @@ -206,7 +206,7 @@ class TextSpan extends InlineSpan { if (text != null) builder.addText(text); if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { assert(child != null); child.build( builder, @@ -231,7 +231,7 @@ class TextSpan extends InlineSpan { return false; } if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { if (!child.visitChildren(visitor)) return false; } @@ -256,7 +256,7 @@ class TextSpan extends InlineSpan { return false; } if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { assert( child is TextSpan, 'visitTextSpan is deprecated. Use visitChildren to support InlineSpans', @@ -300,7 +300,7 @@ class TextSpan extends InlineSpan { buffer.write(text); } if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { child.computeToPlainText(buffer, includeSemanticsLabels: includeSemanticsLabels, includePlaceholders: includePlaceholders, @@ -320,7 +320,7 @@ class TextSpan extends InlineSpan { )); } if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { child.computeSemanticsInformation(collector); } } @@ -364,7 +364,7 @@ class TextSpan extends InlineSpan { bool debugAssertIsValid() { assert(() { if (children != null) { - for (InlineSpan child in children) { + for (final InlineSpan child in children) { if (child == null) { throw FlutterError.fromParts([ ErrorSummary('TextSpan contains a null child.'), diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart index 59ed8cdbd13..e3cc975a91d 100644 --- a/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/packages/flutter/lib/src/rendering/custom_paint.dart @@ -790,7 +790,7 @@ class RenderCustomPaint extends RenderProxyBox { } assert(() { - for (SemanticsNode node in newChildren) { + for (final SemanticsNode node in newChildren) { assert(node != null); } return true; diff --git a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart index 7911b0a0a31..8ec25e13041 100644 --- a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart +++ b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart @@ -282,7 +282,7 @@ mixin DebugOverflowIndicatorMixin on RenderObject { } final List<_OverflowRegionData> overflowRegions = _calculateOverflowRegions(overflow, containerRect); - for (_OverflowRegionData region in overflowRegions) { + for (final _OverflowRegionData region in overflowRegions) { context.canvas.drawRect(region.rect.shift(offset), _indicatorPaint); final TextSpan textSpan = _indicatorLabel[region.side.index].text as TextSpan; if (textSpan?.text != region.label) { diff --git a/packages/flutter/lib/src/rendering/editable.dart b/packages/flutter/lib/src/rendering/editable.dart index 79765ba981f..1b89c0e7830 100644 --- a/packages/flutter/lib/src/rendering/editable.dart +++ b/packages/flutter/lib/src/rendering/editable.dart @@ -1908,7 +1908,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin { 'Last width ($_textLayoutLastMinWidth, $_textLayoutLastMaxWidth) not the same as max width constraint (${constraints.minWidth}, ${constraints.maxWidth}).'); assert(_selectionRects != null); final Paint paint = Paint()..color = _selectionColor; - for (ui.TextBox box in _selectionRects) + for (final ui.TextBox box in _selectionRects) canvas.drawRect(box.toRect().shift(effectiveOffset), paint); } diff --git a/packages/flutter/lib/src/rendering/flow.dart b/packages/flutter/lib/src/rendering/flow.dart index b2a7d458a57..533e5d890f0 100644 --- a/packages/flutter/lib/src/rendering/flow.dart +++ b/packages/flutter/lib/src/rendering/flow.dart @@ -352,7 +352,7 @@ class RenderFlow extends RenderBox _lastPaintOrder.clear(); _paintingContext = context; _paintingOffset = offset; - for (RenderBox child in _randomAccessChildren) { + for (final RenderBox child in _randomAccessChildren) { final FlowParentData childParentData = child.parentData as FlowParentData; childParentData._transform = null; } diff --git a/packages/flutter/lib/src/rendering/layer.dart b/packages/flutter/lib/src/rendering/layer.dart index 4a32715465b..5b4f2730358 100644 --- a/packages/flutter/lib/src/rendering/layer.dart +++ b/packages/flutter/lib/src/rendering/layer.dart @@ -70,7 +70,7 @@ class AnnotationResult { /// /// It is similar to [entries] but does not contain other information. Iterable get annotations sync* { - for (AnnotationEntry entry in _entries) + for (final AnnotationEntry entry in _entries) yield entry.annotation; } } @@ -804,7 +804,7 @@ class ContainerLayer extends Layer { // PhysicalModelLayers. If we don't, we'll end up adding duplicate layers // or continuing to render stale outlines. if (temporaryLayers != null) { - for (PictureLayer temporaryLayer in temporaryLayers) { + for (final PictureLayer temporaryLayer in temporaryLayers) { temporaryLayer.remove(); } } diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 1da7a3bed36..3476119123e 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -883,7 +883,7 @@ class PipelineOwner { while (_nodesNeedingLayout.isNotEmpty) { final List dirtyNodes = _nodesNeedingLayout; _nodesNeedingLayout = []; - for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => a.depth - b.depth)) { + for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => a.depth - b.depth)) { if (node._needsLayout && node.owner == this) node._layoutWithoutResize(); } @@ -935,7 +935,7 @@ class PipelineOwner { Timeline.startSync('Compositing bits'); } _nodesNeedingCompositingBitsUpdate.sort((RenderObject a, RenderObject b) => a.depth - b.depth); - for (RenderObject node in _nodesNeedingCompositingBitsUpdate) { + for (final RenderObject node in _nodesNeedingCompositingBitsUpdate) { if (node._needsCompositingBitsUpdate && node.owner == this) node._updateCompositingBits(); } @@ -974,7 +974,7 @@ class PipelineOwner { final List dirtyNodes = _nodesNeedingPaint; _nodesNeedingPaint = []; // Sort the dirty nodes in reverse order (deepest first). - for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) { + for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) { assert(node._layer != null); if (node._needsPaint && node.owner == this) { if (node._layer.attached) { @@ -1079,7 +1079,7 @@ class PipelineOwner { final List nodesToProcess = _nodesNeedingSemantics.toList() ..sort((RenderObject a, RenderObject b) => a.depth - b.depth); _nodesNeedingSemantics.clear(); - for (RenderObject node in nodesToProcess) { + for (final RenderObject node in nodesToProcess) { if (node._needsSemanticsUpdate && node.owner == this) node._updateSemantics(); } @@ -2625,7 +2625,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im dropSemanticsOfPreviousSiblings = true; } // Figure out which child fragments are to be made explicit. - for (_InterestingSemanticsFragment fragment in parentFragment.interestingFragments) { + for (final _InterestingSemanticsFragment fragment in parentFragment.interestingFragments) { fragments.add(fragment); fragment.addAncestor(this); fragment.addTags(config.tagsForChildren); @@ -2637,7 +2637,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im continue; if (!config.isCompatibleWith(fragment.config)) toBeMarkedExplicit.add(fragment); - for (_InterestingSemanticsFragment siblingFragment in fragments.sublist(0, fragments.length - 1)) { + for (final _InterestingSemanticsFragment siblingFragment in fragments.sublist(0, fragments.length - 1)) { if (!fragment.config.isCompatibleWith(siblingFragment.config)) { toBeMarkedExplicit.add(fragment); toBeMarkedExplicit.add(siblingFragment); @@ -2650,7 +2650,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im return _AbortingSemanticsFragment(owner: this); } - for (_InterestingSemanticsFragment fragment in toBeMarkedExplicit) + for (final _InterestingSemanticsFragment fragment in toBeMarkedExplicit) fragment.markAsExplicit(); _needsSemanticsUpdate = false; @@ -3601,7 +3601,7 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment { Iterable compileChildren({ Rect parentSemanticsClipRect, Rect parentPaintClipRect, double elevationAdjustment }) sync* { if (!_isExplicit) { owner._semantics = null; - for (_InterestingSemanticsFragment fragment in _children) { + for (final _InterestingSemanticsFragment fragment in _children) { assert(_ancestorChain.first == fragment._ancestorChain.last); fragment._ancestorChain.addAll(_ancestorChain.sublist(1)); yield* fragment.compileChildren( @@ -3671,7 +3671,7 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment { @override void addAll(Iterable<_InterestingSemanticsFragment> fragments) { - for (_InterestingSemanticsFragment fragment in fragments) { + for (final _InterestingSemanticsFragment fragment in fragments) { _children.add(fragment); if (fragment.config == null) continue; diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index b62cdd03e1d..5e9d800a994 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -333,7 +333,7 @@ class RenderParagraph extends RenderBox // alignments that require the baseline (baseline, aboveBaseline, // belowBaseline). bool _canComputeIntrinsics() { - for (PlaceholderSpan span in _placeholderSpans) { + for (final PlaceholderSpan span in _placeholderSpans) { switch (span.alignment) { case ui.PlaceholderAlignment.baseline: case ui.PlaceholderAlignment.aboveBaseline: @@ -781,7 +781,7 @@ class RenderParagraph extends RenderBox final List combined = []; String workingText = ''; String workingLabel; - for (InlineSpanSemanticsInformation info in _semanticsInfo) { + for (final InlineSpanSemanticsInformation info in _semanticsInfo) { if (info.requiresOwnNode) { if (workingText != null) { combined.add(InlineSpanSemanticsInformation( @@ -823,7 +823,7 @@ class RenderParagraph extends RenderBox config.isSemanticBoundary = true; } else { final StringBuffer buffer = StringBuffer(); - for (InlineSpanSemanticsInformation info in _semanticsInfo) { + for (final InlineSpanSemanticsInformation info in _semanticsInfo) { buffer.write(info.semanticsLabel ?? info.text); } config.label = buffer.toString(); @@ -841,7 +841,7 @@ class RenderParagraph extends RenderBox int start = 0; int placeholderIndex = 0; RenderBox child = firstChild; - for (InlineSpanSemanticsInformation info in _combineSemanticsInfo()) { + for (final InlineSpanSemanticsInformation info in _combineSemanticsInfo()) { final TextDirection initialDirection = currentDirection; final TextSelection selection = TextSelection( baseOffset: start, @@ -853,7 +853,7 @@ class RenderParagraph extends RenderBox } Rect rect = rects.first.toRect(); currentDirection = rects.first.direction; - for (ui.TextBox textBox in rects.skip(1)) { + for (final ui.TextBox textBox in rects.skip(1)) { rect = rect.expandToInclude(textBox.toRect()); currentDirection = textBox.direction; } diff --git a/packages/flutter/lib/src/rendering/platform_view.dart b/packages/flutter/lib/src/rendering/platform_view.dart index 90d62fcfdf0..76f6835c970 100644 --- a/packages/flutter/lib/src/rendering/platform_view.dart +++ b/packages/flutter/lib/src/rendering/platform_view.dart @@ -417,7 +417,7 @@ class _UiKitViewGestureRecognizer extends OneSequenceGestureRecognizer { @override void addAllowedPointer(PointerDownEvent event) { startTrackingPointer(event.pointer, event.transform); - for (OneSequenceGestureRecognizer recognizer in _gestureRecognizers) { + for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) { recognizer.addPointer(event); } } @@ -493,7 +493,7 @@ class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer { @override void addAllowedPointer(PointerDownEvent event) { startTrackingPointer(event.pointer, event.transform); - for (OneSequenceGestureRecognizer recognizer in _gestureRecognizers) { + for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) { recognizer.addPointer(event); } } diff --git a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart index becf10eeed9..037b342dcfe 100644 --- a/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart +++ b/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart @@ -375,14 +375,14 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver @override void attach(PipelineOwner owner) { super.attach(owner); - for (RenderBox child in _keepAliveBucket.values) + for (final RenderBox child in _keepAliveBucket.values) child.attach(owner); } @override void detach() { super.detach(); - for (RenderBox child in _keepAliveBucket.values) + for (final RenderBox child in _keepAliveBucket.values) child.detach(); } @@ -683,7 +683,7 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } if (_keepAliveBucket.isNotEmpty) { final List indices = _keepAliveBucket.keys.toList()..sort(); - for (int index in indices) { + for (final int index in indices) { children.add(_keepAliveBucket[index].toDiagnosticsNode( name: 'child with index $index (kept alive but not laid out)', style: DiagnosticsTreeStyle.offstage, diff --git a/packages/flutter/lib/src/rendering/table.dart b/packages/flutter/lib/src/rendering/table.dart index 12913ae3691..e0316f5aa19 100644 --- a/packages/flutter/lib/src/rendering/table.dart +++ b/packages/flutter/lib/src/rendering/table.dart @@ -96,7 +96,7 @@ class IntrinsicColumnWidth extends TableColumnWidth { @override double minIntrinsicWidth(Iterable cells, double containerWidth) { double result = 0.0; - for (RenderBox cell in cells) + for (final RenderBox cell in cells) result = math.max(result, cell.getMinIntrinsicWidth(double.infinity)); return result; } @@ -104,7 +104,7 @@ class IntrinsicColumnWidth extends TableColumnWidth { @override double maxIntrinsicWidth(Iterable cells, double containerWidth) { double result = 0.0; - for (RenderBox cell in cells) + for (final RenderBox cell in cells) result = math.max(result, cell.getMaxIntrinsicWidth(double.infinity)); return result; } @@ -527,7 +527,7 @@ class RenderTable extends RenderBox { return; _rowDecorations = value; if (_rowDecorationPainters != null) { - for (BoxPainter painter in _rowDecorationPainters) + for (final BoxPainter painter in _rowDecorationPainters) painter?.dispose(); } _rowDecorationPainters = _rowDecorations != null ? List(_rowDecorations.length) : null; @@ -592,7 +592,7 @@ class RenderTable extends RenderBox { assert(_rows == 0); return; } - for (RenderBox oldChild in _children) { + for (final RenderBox oldChild in _children) { if (oldChild != null) dropChild(oldChild); } @@ -645,7 +645,7 @@ class RenderTable extends RenderBox { setFlatChildren(0, null); return; } - for (RenderBox oldChild in _children) { + for (final RenderBox oldChild in _children) { if (oldChild != null) dropChild(oldChild); } @@ -664,7 +664,7 @@ class RenderTable extends RenderBox { assert(_children.length == rows * columns); _rows += 1; _children.addAll(cells); - for (RenderBox cell in cells) { + for (final RenderBox cell in cells) { if (cell != null) adoptChild(cell); } @@ -695,7 +695,7 @@ class RenderTable extends RenderBox { @override void attach(PipelineOwner owner) { super.attach(owner); - for (RenderBox child in _children) + for (final RenderBox child in _children) child?.attach(owner); } @@ -703,18 +703,18 @@ class RenderTable extends RenderBox { void detach() { super.detach(); if (_rowDecorationPainters != null) { - for (BoxPainter painter in _rowDecorationPainters) + for (final BoxPainter painter in _rowDecorationPainters) painter?.dispose(); _rowDecorationPainters = List(_rowDecorations.length); } - for (RenderBox child in _children) + for (final RenderBox child in _children) child?.detach(); } @override void visitChildren(RenderObjectVisitor visitor) { assert(_children.length == rows * columns); - for (RenderBox child in _children) { + for (final RenderBox child in _children) { if (child != null) visitor(child); } diff --git a/packages/flutter/lib/src/rendering/table_border.dart b/packages/flutter/lib/src/rendering/table_border.dart index a277440f84f..7fa011862a5 100644 --- a/packages/flutter/lib/src/rendering/table_border.dart +++ b/packages/flutter/lib/src/rendering/table_border.dart @@ -226,7 +226,7 @@ class TableBorder { ..strokeWidth = verticalInside.width ..style = PaintingStyle.stroke; path.reset(); - for (double x in columns) { + for (final double x in columns) { path.moveTo(rect.left + x, rect.top); path.lineTo(rect.left + x, rect.bottom); } @@ -245,7 +245,7 @@ class TableBorder { ..strokeWidth = horizontalInside.width ..style = PaintingStyle.stroke; path.reset(); - for (double y in rows) { + for (final double y in rows) { path.moveTo(rect.left, rect.top + y); path.lineTo(rect.right, rect.top + y); } diff --git a/packages/flutter/lib/src/rendering/viewport.dart b/packages/flutter/lib/src/rendering/viewport.dart index 7ce0996daef..809b3210d0e 100644 --- a/packages/flutter/lib/src/rendering/viewport.dart +++ b/packages/flutter/lib/src/rendering/viewport.dart @@ -581,7 +581,7 @@ abstract class RenderViewportBase timings) { - for (FrameTiming frameTiming in timings) { + for (final FrameTiming frameTiming in timings) { frameNumber += 1; _profileFramePostEvent(frameNumber, frameTiming); } @@ -249,7 +249,7 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { void _executeTimingsCallbacks(List timings) { final List clonedCallbacks = List.from(_timingsCallbacks); - for (TimingsCallback callback in clonedCallbacks) { + for (final TimingsCallback callback in clonedCallbacks) { try { if (_timingsCallbacks.contains(callback)) { callback(timings); @@ -582,7 +582,7 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { 'The stack traces for when they were registered are as follows:' ); } - for (int id in callbacks.keys) { + for (final int id in callbacks.keys) { final _FrameCallbackEntry entry = callbacks[id]; yield DiagnosticsStackTrace('── callback $id ──', entry.debugStack, showSeparator: false); } @@ -1043,7 +1043,7 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { try { // PERSISTENT FRAME CALLBACKS _schedulerPhase = SchedulerPhase.persistentCallbacks; - for (FrameCallback callback in _persistentCallbacks) + for (final FrameCallback callback in _persistentCallbacks) _invokeFrameCallback(callback, _currentFrameTimeStamp); // POST-FRAME CALLBACKS @@ -1051,7 +1051,7 @@ mixin SchedulerBinding on BindingBase, ServicesBinding { final List localPostFrameCallbacks = List.from(_postFrameCallbacks); _postFrameCallbacks.clear(); - for (FrameCallback callback in localPostFrameCallbacks) + for (final FrameCallback callback in localPostFrameCallbacks) _invokeFrameCallback(callback, _currentFrameTimeStamp); } finally { _schedulerPhase = SchedulerPhase.idle; diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 3d17560698b..5831864fada 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -386,7 +386,7 @@ class SemanticsData extends Diagnosticable { properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0)); properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0)); final List actionSummary = [ - for (SemanticsAction action in SemanticsAction.values.values) + for (final SemanticsAction action in SemanticsAction.values.values) if ((actions & action.index) != 0) describeEnum(action), ]; @@ -397,7 +397,7 @@ class SemanticsData extends Diagnosticable { properties.add(IterableProperty('customActions', customSemanticsActionSummary, ifEmpty: null)); final List flagSummary = [ - for (SemanticsFlag flag in SemanticsFlag.values.values) + for (final SemanticsFlag flag in SemanticsFlag.values.values) if ((flags & flag.index) != 0) describeEnum(flag), ]; @@ -1397,25 +1397,25 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { }()); assert(() { final Set seenChildren = {}; - for (SemanticsNode child in newChildren) + for (final SemanticsNode child in newChildren) assert(seenChildren.add(child)); // check for duplicate adds return true; }()); // The goal of this function is updating sawChange. if (_children != null) { - for (SemanticsNode child in _children) + for (final SemanticsNode child in _children) child._dead = true; } if (newChildren != null) { - for (SemanticsNode child in newChildren) { + for (final SemanticsNode child in newChildren) { assert(!child.isInvisible, 'Child $child is invisible and should not be added as a child of $this.'); child._dead = false; } } bool sawChange = false; if (_children != null) { - for (SemanticsNode child in _children) { + for (final SemanticsNode child in _children) { if (child._dead) { if (child.parent == this) { // we might have already had our child stolen from us by @@ -1427,7 +1427,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { } } if (newChildren != null) { - for (SemanticsNode child in newChildren) { + for (final SemanticsNode child in newChildren) { if (child.parent != this) { if (child.parent != null) { // we're rebuilding the tree from the bottom up, so it's possible @@ -1473,7 +1473,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { /// returns false. void visitChildren(SemanticsNodeVisitor visitor) { if (_children != null) { - for (SemanticsNode child in _children) { + for (final SemanticsNode child in _children) { if (!visitor(child)) return; } @@ -1487,7 +1487,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { /// returned true, otherwise returns false. bool _visitDescendants(SemanticsNodeVisitor visitor) { if (_children != null) { - for (SemanticsNode child in _children) { + for (final SemanticsNode child in _children) { if (!visitor(child) || !child._visitDescendants(visitor)) return false; } @@ -1519,7 +1519,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { _markDirty(); } if (_children != null) { - for (SemanticsNode child in _children) + for (final SemanticsNode child in _children) child.attach(owner); } } @@ -1533,7 +1533,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { super.detach(); assert(owner == null); if (_children != null) { - for (SemanticsNode child in _children) { + for (final SemanticsNode child in _children) { // The list of children may be stale and may contain nodes that have // been assigned to a different parent. if (child.parent == this) @@ -1910,7 +1910,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { final double elevation = _elevation; double thickness = _thickness; final Set customSemanticsActionIds = {}; - for (CustomSemanticsAction action in _customSemanticsActions.keys) + for (final CustomSemanticsAction action in _customSemanticsActions.keys) customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action)); if (hintOverrides != null) { if (hintOverrides.onTapHint != null) { @@ -1955,7 +1955,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { mergedTags.addAll(node.tags); } if (node._customSemanticsActions != null) { - for (CustomSemanticsAction action in _customSemanticsActions.keys) + for (final CustomSemanticsAction action in _customSemanticsActions.keys) customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action)); } if (node.hintOverrides != null) { @@ -2356,7 +2356,7 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> { /// then sorts them using [sortedWithinKnot]. List sortedWithinVerticalGroup() { final List<_BoxEdge> edges = <_BoxEdge>[]; - for (SemanticsNode child in nodes) { + for (final SemanticsNode child in nodes) { // Using a small delta to shrink child rects removes overlapping cases. final Rect childRect = child.rect.deflate(0.1); edges.add(_BoxEdge( @@ -2375,7 +2375,7 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> { List<_SemanticsSortGroup> horizontalGroups = <_SemanticsSortGroup>[]; _SemanticsSortGroup group; int depth = 0; - for (_BoxEdge edge in edges) { + for (final _BoxEdge edge in edges) { if (edge.isLeadingEdge) { depth += 1; group ??= _SemanticsSortGroup( @@ -2424,10 +2424,10 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> { } final Map nodeMap = {}; final Map edges = {}; - for (SemanticsNode node in nodes) { + for (final SemanticsNode node in nodes) { nodeMap[node.id] = node; final Offset center = _pointInParentCoordinates(node, node.rect.center); - for (SemanticsNode nextNode in nodes) { + for (final SemanticsNode nextNode in nodes) { if (identical(node, nextNode) || edges[nextNode.id] == node.id) { // Skip self or when we've already established that the next node // points to current node. @@ -2499,7 +2499,7 @@ Offset _pointInParentCoordinates(SemanticsNode node, Offset point) { /// For an illustration of the algorithm see http://bit.ly/flutter-default-traversal. List _childrenInDefaultOrder(List children, TextDirection textDirection) { final List<_BoxEdge> edges = <_BoxEdge>[]; - for (SemanticsNode child in children) { + for (final SemanticsNode child in children) { assert(child.rect.isFinite); // Using a small delta to shrink child rects removes overlapping cases. final Rect childRect = child.rect.deflate(0.1); @@ -2519,7 +2519,7 @@ List _childrenInDefaultOrder(List children, TextDi final List<_SemanticsSortGroup> verticalGroups = <_SemanticsSortGroup>[]; _SemanticsSortGroup group; int depth = 0; - for (_BoxEdge edge in edges) { + for (final _BoxEdge edge in edges) { if (edge.isLeadingEdge) { depth += 1; group ??= _SemanticsSortGroup( @@ -2616,7 +2616,7 @@ class SemanticsOwner extends ChangeNotifier { _detachedNodes.clear(); localDirtyNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth); visitedNodes.addAll(localDirtyNodes); - for (SemanticsNode node in localDirtyNodes) { + for (final SemanticsNode node in localDirtyNodes) { assert(node._dirty); assert(node.parent == null || !node.parent.isPartOfNodeMerging || node.isMergedIntoParent); if (node.isPartOfNodeMerging) { @@ -2629,7 +2629,7 @@ class SemanticsOwner extends ChangeNotifier { } visitedNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth); final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); - for (SemanticsNode node in visitedNodes) { + for (final SemanticsNode node in visitedNodes) { assert(node.parent?._dirty != true); // could be null (no parent) or false (not dirty) // The _serialize() method marks the node as not dirty, and // recurses through the tree to do a deep serialization of all @@ -2645,7 +2645,7 @@ class SemanticsOwner extends ChangeNotifier { node._addToUpdate(builder, customSemanticsActionIds); } _dirtyNodes.clear(); - for (int actionId in customSemanticsActionIds) { + for (final int actionId in customSemanticsActionIds) { final CustomSemanticsAction action = CustomSemanticsAction.getAction(actionId); builder.updateCustomAction(id: actionId, label: action.label, hint: action.hint, overrideId: action.action?.index ?? -1); } @@ -2710,7 +2710,7 @@ class SemanticsOwner extends ChangeNotifier { return result?._actions[action]; } if (node.hasChildren) { - for (SemanticsNode child in node._children.reversed) { + for (final SemanticsNode child in node._children.reversed) { final _SemanticsActionHandler handler = _getSemanticsActionHandlerForPosition(child, position, action); if (handler != null) return handler; diff --git a/packages/flutter/lib/src/semantics/semantics_event.dart b/packages/flutter/lib/src/semantics/semantics_event.dart index 657c4d4183a..71b96b7d773 100644 --- a/packages/flutter/lib/src/semantics/semantics_event.dart +++ b/packages/flutter/lib/src/semantics/semantics_event.dart @@ -46,7 +46,7 @@ abstract class SemanticsEvent { final List pairs = []; final Map dataMap = getDataMap(); final List sortedKeys = dataMap.keys.toList()..sort(); - for (String key in sortedKeys) + for (final String key in sortedKeys) pairs.add('$key: ${dataMap[key]}'); return '$runtimeType(${pairs.join(', ')})'; } diff --git a/packages/flutter/lib/src/services/binding.dart b/packages/flutter/lib/src/services/binding.dart index cd1b7e60432..88a320e0713 100644 --- a/packages/flutter/lib/src/services/binding.dart +++ b/packages/flutter/lib/src/services/binding.dart @@ -101,7 +101,7 @@ mixin ServicesBinding on BindingBase { final String _licenseSeparator = '\n' + ('-' * 80) + '\n'; final List result = []; final List licenses = rawLicenses.split(_licenseSeparator); - for (String license in licenses) { + for (final String license in licenses) { final int split = license.indexOf('\n\n'); if (split >= 0) { result.add(LicenseEntryWithLineBreaks( diff --git a/packages/flutter/lib/src/services/keyboard_key.dart b/packages/flutter/lib/src/services/keyboard_key.dart index c9eb338f245..3c8e0b3897b 100644 --- a/packages/flutter/lib/src/services/keyboard_key.dart +++ b/packages/flutter/lib/src/services/keyboard_key.dart @@ -246,7 +246,7 @@ class LogicalKeyboardKey extends KeyboardKey { /// [control], so that the question "is any control key down?" can be asked. static Set collapseSynonyms(Set input) { final Set result = {}; - for (LogicalKeyboardKey key in input) { + for (final LogicalKeyboardKey key in input) { final LogicalKeyboardKey synonym = _synonyms[key]; result.add(synonym ?? key); } diff --git a/packages/flutter/lib/src/services/platform_channel.dart b/packages/flutter/lib/src/services/platform_channel.dart index 978e16ec951..3a32f36eec9 100644 --- a/packages/flutter/lib/src/services/platform_channel.dart +++ b/packages/flutter/lib/src/services/platform_channel.dart @@ -289,7 +289,7 @@ class MethodChannel { /// } else if ([@"getSongs" isEqualToString:call.method]) { /// NSArray* items = [BWPlayApi items]; /// NSMutableArray* json = [NSMutableArray arrayWithCapacity:items.count]; - /// for (BWPlayItem* item in items) { + /// for (final BWPlayItem* item in items) { /// [json addObject:@{@"id":item.itemId, @"title":item.name, @"artist":item.artist}]; /// } /// result(json); diff --git a/packages/flutter/lib/src/services/platform_views.dart b/packages/flutter/lib/src/services/platform_views.dart index 70022fc750c..646d4e692bb 100644 --- a/packages/flutter/lib/src/services/platform_views.dart +++ b/packages/flutter/lib/src/services/platform_views.dart @@ -633,7 +633,7 @@ class AndroidViewController { } _textureId = await SystemChannels.platform_views.invokeMethod('create', args); _state = _AndroidViewState.created; - for (PlatformViewCreatedCallback callback in _platformViewCreatedCallbacks) { + for (final PlatformViewCreatedCallback callback in _platformViewCreatedCallbacks) { callback(id); } } diff --git a/packages/flutter/lib/src/services/raw_keyboard.dart b/packages/flutter/lib/src/services/raw_keyboard.dart index 6d3969d3c18..3a841c0712c 100644 --- a/packages/flutter/lib/src/services/raw_keyboard.dart +++ b/packages/flutter/lib/src/services/raw_keyboard.dart @@ -165,7 +165,7 @@ abstract class RawKeyEventData { /// event, and the keyboard side or sides that the key was on. Map get modifiersPressed { final Map result = {}; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (isModifierPressed(key)) { result[key] = getModifierSide(key); } @@ -523,7 +523,7 @@ class RawKeyboard { if (_listeners.isEmpty) { return; } - for (ValueChanged listener in List>.from(_listeners)) { + for (final ValueChanged listener in List>.from(_listeners)) { if (_listeners.contains(listener)) { listener(event); } @@ -575,7 +575,7 @@ class RawKeyboard { void _synchronizeModifiers(RawKeyEvent event) { final Map modifiersPressed = event.data.modifiersPressed; final Set modifierKeys = {}; - for (ModifierKey key in modifiersPressed.keys) { + for (final ModifierKey key in modifiersPressed.keys) { final Set mappedKeys = _modifierKeyMap[_ModifierSidePair(key, modifiersPressed[key])]; assert(mappedKeys != null, 'Platform key support for ${Platform.operatingSystem} is ' diff --git a/packages/flutter/lib/src/services/system_chrome.dart b/packages/flutter/lib/src/services/system_chrome.dart index b20413acf62..ebd7bfe1599 100644 --- a/packages/flutter/lib/src/services/system_chrome.dart +++ b/packages/flutter/lib/src/services/system_chrome.dart @@ -207,7 +207,7 @@ class SystemUiOverlayStyle { } List _stringify(List list) => [ - for (dynamic item in list) item.toString(), + for (final dynamic item in list) item.toString(), ]; /// Controls specific aspects of the operating system's graphical interface and diff --git a/packages/flutter/lib/src/widgets/animated_list.dart b/packages/flutter/lib/src/widgets/animated_list.dart index a9477beccdd..6298411c474 100644 --- a/packages/flutter/lib/src/widgets/animated_list.dart +++ b/packages/flutter/lib/src/widgets/animated_list.dart @@ -828,7 +828,7 @@ class SliverAnimatedListState extends State with TickerProvi @override void dispose() { - for (_ActiveItem item in _incomingItems.followedBy(_outgoingItems)) { + for (final _ActiveItem item in _incomingItems.followedBy(_outgoingItems)) { item.controller.dispose(); } super.dispose(); @@ -852,7 +852,7 @@ class SliverAnimatedListState extends State with TickerProvi int _indexToItemIndex(int index) { int itemIndex = index; - for (_ActiveItem item in _outgoingItems) { + for (final _ActiveItem item in _outgoingItems) { if (item.itemIndex <= itemIndex) itemIndex += 1; else @@ -863,7 +863,7 @@ class SliverAnimatedListState extends State with TickerProvi int _itemIndexToIndex(int itemIndex) { int index = itemIndex; - for (_ActiveItem item in _outgoingItems) { + for (final _ActiveItem item in _outgoingItems) { assert(item.itemIndex != itemIndex); if (item.itemIndex < itemIndex) index -= 1; @@ -892,11 +892,11 @@ class SliverAnimatedListState extends State with TickerProvi // Increment the incoming and outgoing item indices to account // for the insertion. - for (_ActiveItem item in _incomingItems) { + for (final _ActiveItem item in _incomingItems) { if (item.itemIndex >= itemIndex) item.itemIndex += 1; } - for (_ActiveItem item in _outgoingItems) { + for (final _ActiveItem item in _outgoingItems) { if (item.itemIndex >= itemIndex) item.itemIndex += 1; } @@ -956,11 +956,11 @@ class SliverAnimatedListState extends State with TickerProvi // Decrement the incoming and outgoing item indices to account // for the removal. - for (_ActiveItem item in _incomingItems) { + for (final _ActiveItem item in _incomingItems) { if (item.itemIndex > outgoingItem.itemIndex) item.itemIndex -= 1; } - for (_ActiveItem item in _outgoingItems) { + for (final _ActiveItem item in _outgoingItems) { if (item.itemIndex > outgoingItem.itemIndex) item.itemIndex -= 1; } diff --git a/packages/flutter/lib/src/widgets/animated_switcher.dart b/packages/flutter/lib/src/widgets/animated_switcher.dart index 4c29e4a99a1..10d1c5037c3 100644 --- a/packages/flutter/lib/src/widgets/animated_switcher.dart +++ b/packages/flutter/lib/src/widgets/animated_switcher.dart @@ -425,7 +425,7 @@ class _AnimatedSwitcherState extends State with TickerProvider void dispose() { if (_currentEntry != null) _currentEntry.controller.dispose(); - for (_ChildEntry entry in _outgoingEntries) + for (final _ChildEntry entry in _outgoingEntries) entry.controller.dispose(); super.dispose(); } diff --git a/packages/flutter/lib/src/widgets/app.dart b/packages/flutter/lib/src/widgets/app.dart index bd3ce0f33d7..7c29768f7c4 100644 --- a/packages/flutter/lib/src/widgets/app.dart +++ b/packages/flutter/lib/src/widgets/app.dart @@ -1110,7 +1110,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { final Map languageAndScriptLocales = HashMap(); final Map languageLocales = HashMap(); final Map countryLocales = HashMap(); - for (Locale locale in supportedLocales) { + for (final Locale locale in supportedLocales) { allSupportedLocales['${locale.languageCode}_${locale.scriptCode}_${locale.countryCode}'] ??= locale; languageAndScriptLocales['${locale.languageCode}_${locale.scriptCode}'] ??= locale; languageAndCountryLocales['${locale.languageCode}_${locale.countryCode}'] ??= locale; @@ -1209,7 +1209,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { assert(() { final Set unsupportedTypes = _localizationsDelegates.map((LocalizationsDelegate delegate) => delegate.type).toSet(); - for (LocalizationsDelegate delegate in _localizationsDelegates) { + for (final LocalizationsDelegate delegate in _localizationsDelegates) { if (!unsupportedTypes.contains(delegate.type)) continue; if (delegate.isSupported(appLocale)) @@ -1230,7 +1230,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { 'Warning: This application\'s locale, $appLocale, is not supported by all of its\n' 'localization delegates.' ); - for (Type unsupportedType in unsupportedTypes) { + for (final Type unsupportedType in unsupportedTypes) { // Currently the Cupertino library only provides english localizations. // Remove this when https://github.com/flutter/flutter/issues/23847 // is fixed. diff --git a/packages/flutter/lib/src/widgets/automatic_keep_alive.dart b/packages/flutter/lib/src/widgets/automatic_keep_alive.dart index aafc4417d08..5d61d0b0e66 100644 --- a/packages/flutter/lib/src/widgets/automatic_keep_alive.dart +++ b/packages/flutter/lib/src/widgets/automatic_keep_alive.dart @@ -66,7 +66,7 @@ class _AutomaticKeepAliveState extends State { @override void dispose() { if (_handles != null) { - for (Listenable handle in _handles.keys) + for (final Listenable handle in _handles.keys) handle.removeListener(_handles[handle]); } super.dispose(); diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index a1143b93070..eb236eb0ca0 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -6784,7 +6784,7 @@ class KeyedSubtree extends StatelessWidget { final List itemsWithUniqueKeys = []; int itemIndex = baseIndex; - for (Widget item in items) { + for (final Widget item in items) { itemsWithUniqueKeys.add(KeyedSubtree.wrap(item, itemIndex)); itemIndex += 1; } diff --git a/packages/flutter/lib/src/widgets/binding.dart b/packages/flutter/lib/src/widgets/binding.dart index 1fba2f54799..995cb3ea891 100644 --- a/packages/flutter/lib/src/widgets/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -447,28 +447,28 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @override void handleMetricsChanged() { super.handleMetricsChanged(); - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeMetrics(); } @override void handleTextScaleFactorChanged() { super.handleTextScaleFactorChanged(); - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeTextScaleFactor(); } @override void handlePlatformBrightnessChanged() { super.handlePlatformBrightnessChanged(); - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangePlatformBrightness(); } @override void handleAccessibilityFeaturesChanged() { super.handleAccessibilityFeaturesChanged(); - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeAccessibilityFeatures(); } @@ -492,7 +492,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @protected @mustCallSuper void dispatchLocalesChanged(List locales) { - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeLocales(locales); } @@ -505,7 +505,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @protected @mustCallSuper void dispatchAccessibilityFeaturesChanged() { - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeAccessibilityFeatures(); } @@ -525,7 +525,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// [SystemChannels.navigation]. @protected Future handlePopRoute() async { - for (WidgetsBindingObserver observer in List.from(_observers)) { + for (final WidgetsBindingObserver observer in List.from(_observers)) { if (await observer.didPopRoute()) return; } @@ -545,7 +545,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @protected @mustCallSuper Future handlePushRoute(String route) async { - for (WidgetsBindingObserver observer in List.from(_observers)) { + for (final WidgetsBindingObserver observer in List.from(_observers)) { if (await observer.didPushRoute(route)) return; } @@ -564,7 +564,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @override void handleAppLifecycleStateChanged(AppLifecycleState state) { super.handleAppLifecycleStateChanged(state); - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didChangeAppLifecycleState(state); } @@ -577,7 +577,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// This method exposes the `memoryPressure` notification from /// [SystemChannels.system]. void handleMemoryPressure() { - for (WidgetsBindingObserver observer in _observers) + for (final WidgetsBindingObserver observer in _observers) observer.didHaveMemoryPressure(); } diff --git a/packages/flutter/lib/src/widgets/debug.dart b/packages/flutter/lib/src/widgets/debug.dart index 2c334c00b50..79a8746fe96 100644 --- a/packages/flutter/lib/src/widgets/debug.dart +++ b/packages/flutter/lib/src/widgets/debug.dart @@ -108,7 +108,7 @@ bool debugHighlightDeprecatedWidgets = false; Key _firstNonUniqueKey(Iterable widgets) { final Set keySet = HashSet(); - for (Widget widget in widgets) { + for (final Widget widget in widgets) { assert(widget != null); if (widget.key == null) continue; diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index 1365be2e646..78d1261aaef 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -669,7 +669,7 @@ class _DragAvatar extends Drag { Iterable<_DragTargetState> _getDragTargets(Iterable path) sync* { // Look for the RenderBoxes that corresponds to the hit target (the hit target // widgets build RenderMetaData boxes for us for this purpose). - for (HitTestEntry entry in path) { + for (final HitTestEntry entry in path) { final HitTestTarget target = entry.target; if (target is RenderMetaData) { final dynamic metaData = target.metaData; diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 54e2f14fccb..8188fb62930 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -1618,7 +1618,7 @@ class EditableTextState extends State with AutomaticKeepAliveClien void _formatAndSetValue(TextEditingValue value) { final bool textChanged = _value?.text != value?.text; if (textChanged && widget.inputFormatters != null && widget.inputFormatters.isNotEmpty) { - for (TextInputFormatter formatter in widget.inputFormatters) + for (final TextInputFormatter formatter in widget.inputFormatters) value = formatter.formatEditUpdate(_value, value); _value = value; _updateRemoteEditingValueIfNeeded(); diff --git a/packages/flutter/lib/src/widgets/focus_manager.dart b/packages/flutter/lib/src/widgets/focus_manager.dart index e5d9a000847..2942c7c4fd9 100644 --- a/packages/flutter/lib/src/widgets/focus_manager.dart +++ b/packages/flutter/lib/src/widgets/focus_manager.dart @@ -24,7 +24,7 @@ bool _focusDebug(String message, [Iterable details]) { if (_kDebugFocus) { debugPrint('FOCUS: $message'); if (details != null && details.isNotEmpty) { - for (String detail in details) { + for (final String detail in details) { debugPrint(' $detail'); } } @@ -507,7 +507,7 @@ class FocusNode with DiagnosticableTreeMixin, ChangeNotifier { Iterable get descendants { if (_descendants == null) { final List result = []; - for (FocusNode child in _children) { + for (final FocusNode child in _children) { result.addAll(child.descendants); result.add(child); } @@ -732,7 +732,7 @@ class FocusNode with DiagnosticableTreeMixin, ChangeNotifier { node._parent = null; _children.remove(node); - for (FocusNode ancestor in ancestors) { + for (final FocusNode ancestor in ancestors) { ancestor._descendants = null; } _descendants = null; @@ -741,7 +741,7 @@ class FocusNode with DiagnosticableTreeMixin, ChangeNotifier { void _updateManager(FocusManager manager) { _manager = manager; - for (FocusNode descendant in descendants) { + for (final FocusNode descendant in descendants) { descendant._manager = manager; descendant._ancestors = null; } @@ -766,7 +766,7 @@ class FocusNode with DiagnosticableTreeMixin, ChangeNotifier { child._parent = this; child._ancestors = null; child._updateManager(_manager); - for (FocusNode ancestor in child.ancestors) { + for (final FocusNode ancestor in child.ancestors) { ancestor._descendants = null; } if (hadFocus) { @@ -869,7 +869,7 @@ class FocusNode with DiagnosticableTreeMixin, ChangeNotifier { /// child in that scope is removed, the previous focus returns. void _setAsFocusedChild() { FocusNode scopeFocus = this; - for (FocusScopeNode ancestor in ancestors.whereType()) { + for (final FocusScopeNode ancestor in ancestors.whereType()) { assert(scopeFocus != ancestor, 'Somehow made a loop by setting focusedChild to its scope.'); assert(_focusDebug('Setting $scopeFocus as focused child for scope:', [ancestor.toString()])); // Remove it anywhere in the focused child history. @@ -1258,7 +1258,7 @@ class FocusManager with DiagnosticableTreeMixin { return; } final List> localListeners = List>.from(_listeners); - for (ValueChanged listener in localListeners) { + for (final ValueChanged listener in localListeners) { try { if (_listeners.contains(listener)) { listener(_highlightMode); @@ -1322,7 +1322,7 @@ class FocusManager with DiagnosticableTreeMixin { return; } bool handled = false; - for (FocusNode node in [_primaryFocus, ..._primaryFocus.ancestors]) { + for (final FocusNode node in [_primaryFocus, ..._primaryFocus.ancestors]) { if (node.onKey != null && node.onKey(node, event)) { assert(_focusDebug('Node $node handled key event $event.')); handled = true; @@ -1409,7 +1409,7 @@ class FocusManager with DiagnosticableTreeMixin { } } assert(_focusDebug('Notifying ${_dirtyNodes.length} dirty nodes:', _dirtyNodes.toList().map((FocusNode node) => node.toString()))); - for (FocusNode node in _dirtyNodes) { + for (final FocusNode node in _dirtyNodes) { node._notify(); } _dirtyNodes.clear(); diff --git a/packages/flutter/lib/src/widgets/focus_traversal.dart b/packages/flutter/lib/src/widgets/focus_traversal.dart index 09be0f533e8..c88ed395531 100644 --- a/packages/flutter/lib/src/widgets/focus_traversal.dart +++ b/packages/flutter/lib/src/widgets/focus_traversal.dart @@ -618,7 +618,7 @@ class WidgetOrderFocusTraversalPolicy extends FocusTraversalPolicy with Directio FocusNode firstNode; FocusNode lastNode; bool visit(FocusNode node) { - for (FocusNode visited in node.traversalChildren) { + for (final FocusNode visited in node.traversalChildren) { firstNode ??= visited; if (!visit(visited)) { return false; @@ -750,7 +750,7 @@ class ReadingOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalF } final List<_SortData> data = <_SortData>[ - for (FocusNode node in nodes) _SortData(node), + for (final FocusNode node in nodes) _SortData(node), ]; // Pick the initial widget as the one that is leftmost in the band of the @@ -800,7 +800,7 @@ class ReadingOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalF final Iterable maybeFlipped = forward ? sortedNodes : sortedNodes.reversed; FocusNode previousNode; - for (FocusNode node in maybeFlipped) { + for (final FocusNode node in maybeFlipped) { if (previousNode == focusedChild) { _focusAndEnsureVisible( node, diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 1d8d94ca8dd..9b71f4b99a3 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -177,7 +177,7 @@ class FormState extends State
{ /// Saves every [FormField] that is a descendant of this [Form]. void save() { - for (FormFieldState field in _fields) + for (final FormFieldState field in _fields) field.save(); } @@ -189,7 +189,7 @@ class FormState extends State { /// If the form's [Form.autovalidate] property is true, the fields will all be /// revalidated after being reset. void reset() { - for (FormFieldState field in _fields) + for (final FormFieldState field in _fields) field.reset(); _fieldDidChange(); } @@ -205,7 +205,7 @@ class FormState extends State { bool _validate() { bool hasError = false; - for (FormFieldState field in _fields) + for (final FormFieldState field in _fields) hasError = !field.validate() || hasError; return !hasError; } diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 47f3d56d154..000a1ce1da5 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -206,7 +206,7 @@ abstract class GlobalKey> extends Key { static void _debugVerifyIllFatedPopulation() { assert(() { Map> duplicates; - for (Element element in _debugIllFatedElements) { + for (final Element element in _debugIllFatedElements) { if (element._debugLifecycleState != _ElementLifecycle.defunct) { assert(element != null); assert(element.widget != null); @@ -224,7 +224,7 @@ abstract class GlobalKey> extends Key { if (duplicates != null) { final List information = []; information.add(ErrorSummary('Multiple widgets used the same GlobalKey.')); - for (GlobalKey key in duplicates.keys) { + for (final GlobalKey key in duplicates.keys) { final Set elements = duplicates[key]; // TODO(jacobr): this will omit the '- ' before each widget name and // use the more standard whitespace style instead. Please let me know @@ -1501,7 +1501,7 @@ abstract class ParentDataWidget extends ProxyWidge '$runtimeType widgets must be placed directly inside $T widgets.\n' '$description has a $T ancestor, but there are other widgets between them:' ); - for (Widget ancestor in badAncestors) { + for (final Widget ancestor in badAncestors) { if (ancestor.runtimeType == runtimeType) { yield ErrorDescription('- $ancestor (this is a different $runtimeType than the one with the problem)'); } else { @@ -2551,7 +2551,7 @@ class BuildOwner { return true; }()); } finally { - for (Element element in _dirtyElements) { + for (final Element element in _dirtyElements) { assert(element._inDirtyList); element._inDirtyList = false; } @@ -2606,13 +2606,13 @@ class BuildOwner { if (_debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans != null && _debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans.isNotEmpty) { final Set keys = HashSet(); - for (Element element in _debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans.keys) { + for (final Element element in _debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans.keys) { if (element._debugLifecycleState != _ElementLifecycle.defunct) keys.addAll(_debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans[element]); } if (keys.isNotEmpty) { final Map keyStringCount = HashMap(); - for (String key in keys.map((GlobalKey key) => key.toString())) { + for (final String key in keys.map((GlobalKey key) => key.toString())) { if (keyStringCount.containsKey(key)) { keyStringCount[key] += 1; } else { @@ -2629,7 +2629,7 @@ class BuildOwner { }); final Iterable elements = _debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans.keys; final Map elementStringCount = HashMap(); - for (String element in elements.map((Element element) => element.toString())) { + for (final String element in elements.map((Element element) => element.toString())) { if (elementStringCount.containsKey(element)) { elementStringCount[element] += 1; } else { @@ -3402,7 +3402,7 @@ abstract class Element extends DiagnosticableTree implements BuildContext { assert(depth != null); assert(_active); if (_dependencies != null && _dependencies.isNotEmpty) { - for (InheritedElement dependency in _dependencies) + for (final InheritedElement dependency in _dependencies) dependency._dependents.remove(this); // For expediency, we don't actually clear the list here, even though it's // no longer representative of what we are registered with. If we never @@ -4914,7 +4914,7 @@ class InheritedElement extends ProxyElement { @override void notifyClients(InheritedWidget oldWidget) { assert(_debugCheckOwnerBuildTargetExists('notifyClients')); - for (Element dependent in _dependents.keys) { + for (final Element dependent in _dependents.keys) { assert(() { // check that it really is our descendant Element ancestor = dependent._parent; @@ -5329,7 +5329,7 @@ abstract class RenderObjectElement extends Element { // Clean up any of the remaining middle nodes from the old list. if (haveOldChildren && oldKeyedChildren.isNotEmpty) { - for (Element oldChild in oldKeyedChildren.values) { + for (final Element oldChild in oldKeyedChildren.values) { if (forgottenChildren == null || !forgottenChildren.contains(oldChild)) deactivateChild(oldChild); } @@ -5612,7 +5612,7 @@ class MultiChildRenderObjectElement extends RenderObjectElement { @override void visitChildren(ElementVisitor visitor) { - for (Element child in _children) { + for (final Element child in _children) { if (!_forgottenChildren.contains(child)) visitor(child); } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index c8e04ea1e32..9febee15d26 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -990,7 +990,7 @@ class RawGestureDetectorState extends State { @override void dispose() { - for (GestureRecognizer recognizer in _recognizers.values) + for (final GestureRecognizer recognizer in _recognizers.values) recognizer.dispose(); _recognizers = null; super.dispose(); @@ -1000,7 +1000,7 @@ class RawGestureDetectorState extends State { assert(_recognizers != null); final Map oldRecognizers = _recognizers; _recognizers = {}; - for (Type type in gestures.keys) { + for (final Type type in gestures.keys) { assert(gestures[type] != null); assert(gestures[type]._debugAssertTypeMatches(type)); assert(!_recognizers.containsKey(type)); @@ -1008,7 +1008,7 @@ class RawGestureDetectorState extends State { assert(_recognizers[type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of type ${_recognizers[type].runtimeType}. The GestureRecognizerFactory must be specialized with the type of the class that it returns from its constructor method.'); gestures[type].initializer(_recognizers[type]); } - for (Type type in oldRecognizers.keys) { + for (final Type type in oldRecognizers.keys) { if (!_recognizers.containsKey(type)) oldRecognizers[type].dispose(); } @@ -1016,7 +1016,7 @@ class RawGestureDetectorState extends State { void _handlePointerDown(PointerDownEvent event) { assert(_recognizers != null); - for (GestureRecognizer recognizer in _recognizers.values) + for (final GestureRecognizer recognizer in _recognizers.values) recognizer.addPointer(event); } diff --git a/packages/flutter/lib/src/widgets/heroes.dart b/packages/flutter/lib/src/widgets/heroes.dart index 2629cd5dc30..7253e7bbf99 100644 --- a/packages/flutter/lib/src/widgets/heroes.dart +++ b/packages/flutter/lib/src/widgets/heroes.dart @@ -755,7 +755,7 @@ class HeroController extends NavigatorObserver { // Treat these invalidated flights as dismissed. Calling _handleAnimationUpdate // will also remove the flight from _flights. - for (_HeroFlight flight in invalidFlights) { + for (final _HeroFlight flight in invalidFlights) { flight._handleAnimationUpdate(AnimationStatus.dismissed); } } @@ -834,7 +834,7 @@ class HeroController extends NavigatorObserver { // animation value back to what it was before it was "moved" offstage. to.offstage = false; - for (Object tag in fromHeroes.keys) { + for (final Object tag in fromHeroes.keys) { if (toHeroes[tag] != null) { final HeroFlightShuttleBuilder fromShuttleBuilder = fromHeroes[tag].widget.flightShuttleBuilder; final HeroFlightShuttleBuilder toShuttleBuilder = toHeroes[tag].widget.flightShuttleBuilder; @@ -866,7 +866,7 @@ class HeroController extends NavigatorObserver { // If the from hero is gone, the flight won't start and the to hero needs to // be put on stage again. - for (Object tag in toHeroes.keys) { + for (final Object tag in toHeroes.keys) { if (fromHeroes[tag] == null) toHeroes[tag].ensurePlaceholderIsHidden(); } diff --git a/packages/flutter/lib/src/widgets/inherited_model.dart b/packages/flutter/lib/src/widgets/inherited_model.dart index a04b8700115..e4c7efe3cb7 100644 --- a/packages/flutter/lib/src/widgets/inherited_model.dart +++ b/packages/flutter/lib/src/widgets/inherited_model.dart @@ -170,7 +170,7 @@ abstract class InheritedModel extends InheritedWidget { } final InheritedElement lastModel = models.last; - for (InheritedElement model in models) { + for (final InheritedElement model in models) { final T value = context.dependOnInheritedElement(model, aspect: aspect) as T; if (model == lastModel) return value; diff --git a/packages/flutter/lib/src/widgets/inherited_theme.dart b/packages/flutter/lib/src/widgets/inherited_theme.dart index ecae20ab22b..dd2a29c4d21 100644 --- a/packages/flutter/lib/src/widgets/inherited_theme.dart +++ b/packages/flutter/lib/src/widgets/inherited_theme.dart @@ -147,7 +147,7 @@ class _CaptureAll extends StatelessWidget { @override Widget build(BuildContext context) { Widget wrappedChild = child; - for (InheritedTheme theme in themes) + for (final InheritedTheme theme in themes) wrappedChild = theme.wrap(context, wrappedChild); return wrappedChild; } diff --git a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart index b88d1962a27..bced3d08ace 100644 --- a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart @@ -265,7 +265,7 @@ class FixedExtentScrollController extends ScrollController { } await Future.wait(>[ - for (_FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) + for (final _FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) position.animateTo( itemIndex * position.itemExtent, duration: duration, @@ -279,7 +279,7 @@ class FixedExtentScrollController extends ScrollController { /// Jumps the item index position from its current value to the given value, /// without animation, and without checking if the new value is in range. void jumpToItem(int itemIndex) { - for (_FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) { + for (final _FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) { position.jumpTo(itemIndex * position.itemExtent); } } diff --git a/packages/flutter/lib/src/widgets/localizations.dart b/packages/flutter/lib/src/widgets/localizations.dart index 5ae0b6e7ebd..8dae00dd5f7 100644 --- a/packages/flutter/lib/src/widgets/localizations.dart +++ b/packages/flutter/lib/src/widgets/localizations.dart @@ -47,14 +47,14 @@ Future> _loadAll(Locale locale, Iterable types = {}; final List> delegates = >[]; - for (LocalizationsDelegate delegate in allDelegates) { + for (final LocalizationsDelegate delegate in allDelegates) { if (!types.contains(delegate.type) && delegate.isSupported(locale)) { types.add(delegate.type); delegates.add(delegate); } } - for (LocalizationsDelegate delegate in delegates) { + for (final LocalizationsDelegate delegate in delegates) { final Future inputValue = delegate.load(locale); dynamic completedValue; final Future futureValue = inputValue.then((dynamic value) { diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index 344249fec6f..39484aaba85 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -1521,7 +1521,7 @@ class NavigatorState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); - for (NavigatorObserver observer in widget.observers) { + for (final NavigatorObserver observer in widget.observers) { assert(observer.navigator == null); observer._navigator = this; } @@ -1535,7 +1535,7 @@ class NavigatorState extends State with TickerProviderStateMixin { final List routeParts = initialRouteName.split('/'); if (initialRouteName.isNotEmpty) { String routeName = ''; - for (String part in routeParts) { + for (final String part in routeParts) { routeName += '/$part'; plannedInitialRoutes.add(_routeNamed(routeName, allowNull: true, arguments: null)); } @@ -1564,7 +1564,7 @@ class NavigatorState extends State with TickerProviderStateMixin { route ??= _routeNamed(Navigator.defaultRouteName, arguments: null); push(route); } - for (Route route in _history) + for (final Route route in _history) _initialOverlayEntries.addAll(route.overlayEntries); } @@ -1572,14 +1572,14 @@ class NavigatorState extends State with TickerProviderStateMixin { void didUpdateWidget(Navigator oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.observers != widget.observers) { - for (NavigatorObserver observer in oldWidget.observers) + for (final NavigatorObserver observer in oldWidget.observers) observer._navigator = null; - for (NavigatorObserver observer in widget.observers) { + for (final NavigatorObserver observer in widget.observers) { assert(observer.navigator == null); observer._navigator = this; } } - for (Route route in _history) + for (final Route route in _history) route.changedExternalState(); } @@ -1590,10 +1590,10 @@ class NavigatorState extends State with TickerProviderStateMixin { _debugLocked = true; return true; }()); - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer._navigator = null; final List> doomed = _poppedRoutes.toList()..addAll(_history); - for (Route route in doomed) + for (final Route route in doomed) route.dispose(); _poppedRoutes.clear(); _history.clear(); @@ -1609,7 +1609,7 @@ class NavigatorState extends State with TickerProviderStateMixin { OverlayState get overlay => _overlayKey.currentState; OverlayEntry get _currentOverlayEntry { - for (Route route in _history.reversed) { + for (final Route route in _history.reversed) { if (route.overlayEntries.isNotEmpty) return route.overlayEntries.last; } @@ -1796,7 +1796,7 @@ class NavigatorState extends State with TickerProviderStateMixin { oldRoute.didChangeNext(route); route.didChangePrevious(oldRoute); } - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didPush(route, oldRoute); RouteNotificationMessages.maybeNotifyRouteChange(_routePushedMethod, route, oldRoute); assert(() { @@ -1896,7 +1896,7 @@ class NavigatorState extends State with TickerProviderStateMixin { _history[index - 1].didChangeNext(newRoute); newRoute.didChangePrevious(_history[index - 1]); } - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didReplace(newRoute: newRoute, oldRoute: oldRoute); RouteNotificationMessages.maybeNotifyRouteChange(_routeReplacedMethod, newRoute, oldRoute); assert(() { @@ -1956,8 +1956,8 @@ class NavigatorState extends State with TickerProviderStateMixin { newRoute.didPush().whenCompleteOrCancel(() { if (mounted) { - for (Route removedRoute in removedRoutes) { - for (NavigatorObserver observer in widget.observers) + for (final Route removedRoute in removedRoutes) { + for (final NavigatorObserver observer in widget.observers) observer.didRemove(removedRoute, newPrecedingRoute); removedRoute.dispose(); } @@ -1969,7 +1969,7 @@ class NavigatorState extends State with TickerProviderStateMixin { // Notify for newRoute newRoute.didChangeNext(null); - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didPush(newRoute, precedingRoute); assert(() { @@ -2020,7 +2020,7 @@ class NavigatorState extends State with TickerProviderStateMixin { _history[index - 1].didChangeNext(newRoute); newRoute.didChangePrevious(_history[index - 1]); } - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didReplace(newRoute: newRoute, oldRoute: oldRoute); RouteNotificationMessages.maybeNotifyRouteChange(_routeReplacedMethod, newRoute, oldRoute); oldRoute.dispose(); @@ -2132,7 +2132,7 @@ class NavigatorState extends State with TickerProviderStateMixin { if (route._navigator != null) _poppedRoutes.add(route); _history.last.didPopNext(route); - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didPop(route, _history.last); RouteNotificationMessages.maybeNotifyRouteChange(_routePoppedMethod, route, _history.last); } else { @@ -2190,7 +2190,7 @@ class NavigatorState extends State with TickerProviderStateMixin { _history.removeAt(index); previousRoute?.didChangeNext(nextRoute); nextRoute?.didChangePrevious(previousRoute); - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didRemove(route, previousRoute); route.dispose(); assert(() { @@ -2281,7 +2281,7 @@ class NavigatorState extends State with TickerProviderStateMixin { // Don't operate the _history list since the gesture may be canceled. // In case of a back swipe, the gesture controller will call .pop() itself. - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didStartUserGesture(route, previousRoute); } } @@ -2294,7 +2294,7 @@ class NavigatorState extends State with TickerProviderStateMixin { assert(_userGesturesInProgress > 0); _userGesturesInProgress -= 1; if (_userGesturesInProgress == 0) { - for (NavigatorObserver observer in widget.observers) + for (final NavigatorObserver observer in widget.observers) observer.didStopUserGesture(); } } diff --git a/packages/flutter/lib/src/widgets/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index 213f85c6d67..f7397dfa527 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -497,7 +497,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont } bool get hasScrolledBody { - for (_NestedScrollPosition position in _innerPositions) { + for (final _NestedScrollPosition position in _innerPositions) { assert(position.minScrollExtent != null && position.pixels != null); if (position.pixels > position.minScrollExtent) { return true; @@ -520,7 +520,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont return; _userScrollDirection = value; _outerPosition.didUpdateScrollDirection(value); - for (_NestedScrollPosition position in _innerPositions) + for (final _NestedScrollPosition position in _innerPositions) position.didUpdateScrollDirection(value); } @@ -529,7 +529,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont void beginActivity(ScrollActivity newOuterActivity, _NestedScrollActivityGetter innerActivityGetter) { _outerPosition.beginActivity(newOuterActivity); bool scrolling = newOuterActivity.isScrolling; - for (_NestedScrollPosition position in _innerPositions) { + for (final _NestedScrollPosition position in _innerPositions) { final ScrollActivity newInnerActivity = innerActivityGetter(position); position.beginActivity(newInnerActivity); scrolling = scrolling && newInnerActivity.isScrolling; @@ -574,7 +574,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont // are heading towards. _NestedScrollPosition innerPosition; if (velocity != 0.0) { - for (_NestedScrollPosition position in _innerPositions) { + for (final _NestedScrollPosition position in _innerPositions) { if (innerPosition != null) { if (velocity > 0.0) { if (innerPosition.pixels < position.pixels) @@ -707,7 +707,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont if (!_outerPosition.haveDimensions) return; double maxInnerExtent = 0.0; - for (_NestedScrollPosition position in _innerPositions) { + for (final _NestedScrollPosition position in _innerPositions) { if (!position.haveDimensions) return; maxInnerExtent = math.max(maxInnerExtent, position.maxScrollExtent - position.minScrollExtent); @@ -744,7 +744,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont void jumpTo(double to) { goIdle(); _outerPosition.localJumpTo(nestOffset(to, _outerPosition)); - for (_NestedScrollPosition position in _innerPositions) + for (final _NestedScrollPosition position in _innerPositions) position.localJumpTo(nestOffset(to, position)); goBallistic(0.0); } @@ -799,7 +799,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont // different levels of overscroll. final double innerDelta = _outerPosition.applyClampedDragUpdate(delta); if (innerDelta != 0.0) { - for (_NestedScrollPosition position in _innerPositions) + for (final _NestedScrollPosition position in _innerPositions) position.applyFullDragUpdate(innerDelta); } } else { @@ -808,7 +808,7 @@ class _NestedScrollCoordinator implements ScrollActivityDelegate, ScrollHoldCont double outerDelta = 0.0; // it will go positive if it changes final List overscrolls = []; final List<_NestedScrollPosition> innerPositions = _innerPositions.toList(); - for (_NestedScrollPosition position in innerPositions) { + for (final _NestedScrollPosition position in innerPositions) { final double overscroll = position.applyClampedDragUpdate(delta); outerDelta = math.max(outerDelta, overscroll); overscrolls.add(overscroll); diff --git a/packages/flutter/lib/src/widgets/overlay.dart b/packages/flutter/lib/src/widgets/overlay.dart index 39b7e57e4b9..ec6bc13c30b 100644 --- a/packages/flutter/lib/src/widgets/overlay.dart +++ b/packages/flutter/lib/src/widgets/overlay.dart @@ -337,7 +337,7 @@ class OverlayState extends State with TickerProviderStateMixin { ); if (entries.isEmpty) return; - for (OverlayEntry entry in entries) { + for (final OverlayEntry entry in entries) { assert(entry._overlay == null); entry._overlay = this; } @@ -390,7 +390,7 @@ class OverlayState extends State with TickerProviderStateMixin { if (listEquals(_entries, newEntriesList)) return; final LinkedHashSet old = LinkedHashSet.from(_entries); - for (OverlayEntry entry in newEntriesList) { + for (final OverlayEntry entry in newEntriesList) { entry._overlay ??= this; } setState(() { @@ -561,7 +561,7 @@ class _TheatreElement extends RenderObjectElement { void visitChildren(ElementVisitor visitor) { if (_onstage != null) visitor(_onstage); - for (Element child in _offstage) { + for (final Element child in _offstage) { if (!_forgottenOffstageChildren.contains(child)) visitor(child); } diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index 850b30b8daa..18ba06c7500 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -68,7 +68,7 @@ abstract class OverlayRoute extends Route { @override void dispose() { - for (OverlayEntry entry in _overlayEntries) + for (final OverlayEntry entry in _overlayEntries) entry.remove(); _overlayEntries.clear(); super.dispose(); @@ -1131,7 +1131,7 @@ abstract class ModalRoute extends TransitionRoute with LocalHistoryRoute willPop() async { final _ModalScopeState scope = _scopeKey.currentState; assert(scope != null); - for (WillPopCallback callback in List.from(_willPopCallbacks)) { + for (final WillPopCallback callback in List.from(_willPopCallbacks)) { if (!await callback()) return RoutePopDisposition.doNotPop; } @@ -1446,7 +1446,7 @@ class RouteObserver> extends NavigatorObserver { /// subscribed to multiple types, this will unregister it (once) from each type. void unsubscribe(RouteAware routeAware) { assert(routeAware != null); - for (R route in _listeners.keys) { + for (final R route in _listeners.keys) { final Set subscribers = _listeners[route]; subscribers?.remove(routeAware); } @@ -1458,7 +1458,7 @@ class RouteObserver> extends NavigatorObserver { final List previousSubscribers = _listeners[previousRoute]?.toList(); if (previousSubscribers != null) { - for (RouteAware routeAware in previousSubscribers) { + for (final RouteAware routeAware in previousSubscribers) { routeAware.didPopNext(); } } @@ -1466,7 +1466,7 @@ class RouteObserver> extends NavigatorObserver { final List subscribers = _listeners[route]?.toList(); if (subscribers != null) { - for (RouteAware routeAware in subscribers) { + for (final RouteAware routeAware in subscribers) { routeAware.didPop(); } } @@ -1479,7 +1479,7 @@ class RouteObserver> extends NavigatorObserver { final Set previousSubscribers = _listeners[previousRoute]; if (previousSubscribers != null) { - for (RouteAware routeAware in previousSubscribers) { + for (final RouteAware routeAware in previousSubscribers) { routeAware.didPushNext(); } } diff --git a/packages/flutter/lib/src/widgets/scroll_controller.dart b/packages/flutter/lib/src/widgets/scroll_controller.dart index 88fdb31a3aa..35c1b1f06e1 100644 --- a/packages/flutter/lib/src/widgets/scroll_controller.dart +++ b/packages/flutter/lib/src/widgets/scroll_controller.dart @@ -168,7 +168,7 @@ class ScrollController extends ChangeNotifier { /// value was out of range. void jumpTo(double value) { assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.'); - for (ScrollPosition position in List.from(_positions)) + for (final ScrollPosition position in List.from(_positions)) position.jumpTo(value); } @@ -194,7 +194,7 @@ class ScrollController extends ChangeNotifier { @override void dispose() { - for (ScrollPosition position in _positions) + for (final ScrollPosition position in _positions) position.removeListener(notifyListeners); super.dispose(); } @@ -367,7 +367,7 @@ class TrackingScrollController extends ScrollController { @override void dispose() { - for (ScrollPosition position in positions) { + for (final ScrollPosition position in positions) { assert(_positionToListener.containsKey(position)); position.removeListener(_positionToListener[position]); } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 193d8be22e6..cbf6de687f2 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -763,7 +763,7 @@ class _RenderScrollSemantics extends RenderProxyBox { int firstVisibleIndex; final List excluded = [_innerNode]; final List included = []; - for (SemanticsNode child in children) { + for (final SemanticsNode child in children) { assert(child.isTagged(RenderViewport.useTwoPaneSemantics)); if (child.isTagged(RenderViewport.excludeFromScrolling)) { excluded.add(child); diff --git a/packages/flutter/lib/src/widgets/shortcuts.dart b/packages/flutter/lib/src/widgets/shortcuts.dart index f34e0f611d0..351ef1137b1 100644 --- a/packages/flutter/lib/src/widgets/shortcuts.dart +++ b/packages/flutter/lib/src/widgets/shortcuts.dart @@ -196,7 +196,7 @@ class ShortcutManager extends ChangeNotifier with DiagnosticableMixin { // have synonyms in the map. This is for things like left and right shift // keys mapping to just the "shift" pseudo-key. final Set pseudoKeys = {}; - for (LogicalKeyboardKey setKey in keySet.keys) { + for (final LogicalKeyboardKey setKey in keySet.keys) { final Set synonyms = setKey.synonyms; if (synonyms.isNotEmpty) { // There currently aren't any synonyms that match more than one key. diff --git a/packages/flutter/lib/src/widgets/sliver.dart b/packages/flutter/lib/src/widgets/sliver.dart index 9b4a89ce167..92fe47f9a69 100644 --- a/packages/flutter/lib/src/widgets/sliver.dart +++ b/packages/flutter/lib/src/widgets/sliver.dart @@ -1229,7 +1229,7 @@ class SliverMultiBoxAdaptorElement extends RenderObjectElement implements Render } } - for (int index in _childElements.keys.toList()) { + for (final int index in _childElements.keys.toList()) { final Key key = _childElements[index].widget.key; final int newIndex = key == null ? null : widget.delegate.findIndexByKey(key); if (newIndex != null && newIndex != index) { diff --git a/packages/flutter/lib/src/widgets/table.dart b/packages/flutter/lib/src/widgets/table.dart index 3eec4b717d6..965a70a06df 100644 --- a/packages/flutter/lib/src/widgets/table.dart +++ b/packages/flutter/lib/src/widgets/table.dart @@ -285,7 +285,7 @@ class _TableElement extends RenderObjectElement { @override void update(Table newWidget) { final Map> oldKeyedRows = >{}; - for (_TableElementRow row in _children) { + for (final _TableElementRow row in _children) { if (row.key != null) { oldKeyedRows[row.key] = row.children; } @@ -293,7 +293,7 @@ class _TableElement extends RenderObjectElement { final Iterator<_TableElementRow> oldUnkeyedRows = _children.where((_TableElementRow row) => row.key == null).iterator; final List<_TableElementRow> newChildren = <_TableElementRow>[]; final Set> taken = >{}; - for (TableRow row in newWidget.children) { + for (final TableRow row in newWidget.children) { List oldChildren; if (row.key != null && oldKeyedRows.containsKey(row.key)) { oldChildren = oldKeyedRows[row.key]; @@ -310,7 +310,7 @@ class _TableElement extends RenderObjectElement { } while (oldUnkeyedRows.moveNext()) updateChildren(oldUnkeyedRows.current.children, const [], forgottenChildren: _forgottenChildren); - for (List oldChildren in oldKeyedRows.values.where((List list) => !taken.contains(list))) + for (final List oldChildren in oldKeyedRows.values.where((List list) => !taken.contains(list))) updateChildren(oldChildren, const [], forgottenChildren: _forgottenChildren); _children = newChildren; @@ -335,7 +335,7 @@ class _TableElement extends RenderObjectElement { @override void visitChildren(ElementVisitor visitor) { - for (Element child in _children.expand((_TableElementRow row) => row.children)) { + for (final Element child in _children.expand((_TableElementRow row) => row.children)) { if (!_forgottenChildren.contains(child)) visitor(child); } diff --git a/packages/flutter/lib/src/widgets/ticker_provider.dart b/packages/flutter/lib/src/widgets/ticker_provider.dart index 392ac563c90..65a825431ac 100644 --- a/packages/flutter/lib/src/widgets/ticker_provider.dart +++ b/packages/flutter/lib/src/widgets/ticker_provider.dart @@ -180,7 +180,7 @@ mixin TickerProviderStateMixin on State implements void dispose() { assert(() { if (_tickers != null) { - for (Ticker ticker in _tickers) { + for (final Ticker ticker in _tickers) { if (ticker.isActive) { throw FlutterError.fromParts([ ErrorSummary('$this was disposed with an active Ticker.'), @@ -208,7 +208,7 @@ mixin TickerProviderStateMixin on State implements void didChangeDependencies() { final bool muted = !TickerMode.of(context); if (_tickers != null) { - for (Ticker ticker in _tickers) { + for (final Ticker ticker in _tickers) { ticker.muted = muted; } } diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index cff08a15a80..d113c750e92 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -1440,7 +1440,7 @@ mixin WidgetInspectorService { // https://github.com/flutter/flutter/issues/32660 is fixed. return !file.contains('packages/flutter/'); } - for (String directory in _pubRootDirectories) { + for (final String directory in _pubRootDirectories) { if (file.startsWith(directory)) { return true; } @@ -1573,7 +1573,7 @@ mixin WidgetInspectorService { InspectorSerializationDelegate delegate, ) { final List children = [ - for (DiagnosticsNode child in nodes) + for (final DiagnosticsNode child in nodes) if (!delegate.summaryTree || _shouldShowInSummaryTree(child)) child else @@ -1781,7 +1781,7 @@ mixin WidgetInspectorService { Element current = selection?.currentElement; if (current != null && !_isValueCreatedByLocalProject(current)) { Element firstLocal; - for (Element candidate in current.debugGetDiagnosticChain()) { + for (final Element candidate in current.debugGetDiagnosticChain()) { if (_isValueCreatedByLocalProject(candidate)) { firstLocal = candidate; break; @@ -2003,7 +2003,7 @@ class _ElementLocationStatsTracker { // trigger significant additional memory allocations. Avoiding memory // allocations is important to minimize the impact this class has on cpu // and memory performance of the running app. - for (_LocationCount entry in active) { + for (final _LocationCount entry in active) { entry.reset(); } active.clear(); @@ -2014,7 +2014,7 @@ class _ElementLocationStatsTracker { Map exportToJson(Duration startTime) { final List events = List.filled(active.length * 2, 0); int j = 0; - for (_LocationCount stat in active) { + for (final _LocationCount stat in active) { events[j++] = stat.id; events[j++] = stat.count; } @@ -2027,7 +2027,7 @@ class _ElementLocationStatsTracker { if (newLocations.isNotEmpty) { // Add all newly used location ids to the JSON. final Map> locationsJson = >{}; - for (_LocationCount entry in newLocations) { + for (final _LocationCount entry in newLocations) { final _Location location = entry.location; final List jsonForFile = locationsJson.putIfAbsent( location.file, @@ -2537,7 +2537,7 @@ class _InspectorOverlayLayer extends Layer { final RenderObject selected = selection.current; final List<_TransformedRect> candidates = <_TransformedRect>[]; - for (RenderObject candidate in selection.candidates) { + for (final RenderObject candidate in selection.candidates) { if (candidate == selected || !candidate.attached) continue; candidates.add(_TransformedRect(candidate)); @@ -2584,7 +2584,7 @@ class _InspectorOverlayLayer extends Layer { // Show all other candidate possibly selected elements. This helps selecting // render objects by selecting the edge of the bounding box shows all // elements the user could toggle the selection between. - for (_TransformedRect transformedRect in state.candidates) { + for (final _TransformedRect transformedRect in state.candidates) { canvas ..save() ..transform(transformedRect.transform.storage) @@ -2767,7 +2767,7 @@ bool _isDebugCreator(DiagnosticsNode node) => node is DiagnosticsDebugCreator; Iterable transformDebugCreator(Iterable properties) sync* { final List pending = []; bool foundStackTrace = false; - for (DiagnosticsNode node in properties) { + for (final DiagnosticsNode node in properties) { if (!foundStackTrace && node is DiagnosticsStackTrace) foundStackTrace = true; if (_isDebugCreator(node)) { diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index e03599490f3..4a52f77cd83 100644 --- a/packages/flutter/test/foundation/diagnostics_json_test.dart +++ b/packages/flutter/test/foundation/diagnostics_json_test.dart @@ -247,7 +247,7 @@ class TestTree extends Object with DiagnosticableTreeMixin { @override List debugDescribeChildren() => [ - for (TestTree child in children) + for (final TestTree child in children) child.toDiagnosticsNode( name: 'child ${child.name}', style: child.style, diff --git a/packages/flutter/test/foundation/diagnostics_test.dart b/packages/flutter/test/foundation/diagnostics_test.dart index 09246b79c35..2ab97c8be9d 100644 --- a/packages/flutter/test/foundation/diagnostics_test.dart +++ b/packages/flutter/test/foundation/diagnostics_test.dart @@ -23,7 +23,7 @@ class TestTree extends Object with DiagnosticableTreeMixin { @override List debugDescribeChildren() => [ - for (TestTree child in children) + for (final TestTree child in children) child.toDiagnosticsNode( name: 'child ${child.name}', style: child.style, diff --git a/packages/flutter/test/gestures/gesture_binding_test.dart b/packages/flutter/test/gestures/gesture_binding_test.dart index 1bd207d86de..41574f10728 100644 --- a/packages/flutter/test/gestures/gesture_binding_test.dart +++ b/packages/flutter/test/gestures/gesture_binding_test.dart @@ -205,7 +205,7 @@ void main() { test('Should synthesize kPrimaryButton for stylus', () { final Offset location = const Offset(10.0, 10.0) * ui.window.devicePixelRatio; - for (PointerDeviceKind kind in [ + for (final PointerDeviceKind kind in [ PointerDeviceKind.stylus, PointerDeviceKind.invertedStylus, ]) { @@ -268,7 +268,7 @@ void main() { test('Should not synthesize kPrimaryButton for mouse', () { final Offset location = const Offset(10.0, 10.0) * ui.window.devicePixelRatio; - for (PointerDeviceKind kind in [ + for (final PointerDeviceKind kind in [ PointerDeviceKind.mouse, ]) { final ui.PointerDataPacket packet = ui.PointerDataPacket( diff --git a/packages/flutter/test/gestures/velocity_tracker_test.dart b/packages/flutter/test/gestures/velocity_tracker_test.dart index b1e4c320041..803286738e5 100644 --- a/packages/flutter/test/gestures/velocity_tracker_test.dart +++ b/packages/flutter/test/gestures/velocity_tracker_test.dart @@ -38,7 +38,7 @@ void main() { test('Velocity tracker gives expected results', () { final VelocityTracker tracker = VelocityTracker(); int i = 0; - for (PointerEvent event in velocityEventData) { + for (final PointerEvent event in velocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) tracker.addPosition(event.timeStamp, event.position); if (event is PointerUpEvent) { @@ -63,7 +63,7 @@ void main() { test('Interrupted velocity estimation', () { // Regression test for https://github.com/flutter/flutter/pull/7510 final VelocityTracker tracker = VelocityTracker(); - for (PointerEvent event in interruptedVelocityEventData) { + for (final PointerEvent event in interruptedVelocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) tracker.addPosition(event.timeStamp, event.position); if (event is PointerUpEvent) { diff --git a/packages/flutter/test/material/colors_test.dart b/packages/flutter/test/material/colors_test.dart index d0e4209c047..a9f33bbcb53 100644 --- a/packages/flutter/test/material/colors_test.dart +++ b/packages/flutter/test/material/colors_test.dart @@ -53,31 +53,31 @@ void main() { }); test('Colors swatches do not contain duplicates', () { - for (MaterialColor color in Colors.primaries) + for (final MaterialColor color in Colors.primaries) expect(primaryKeys.map((int key) => color[key]).toSet().length, primaryKeys.length); expect(primaryKeys.map((int key) => Colors.grey[key]).toSet().length, primaryKeys.length); - for (MaterialAccentColor color in Colors.accents) + for (final MaterialAccentColor color in Colors.accents) expect(accentKeys.map((int key) => color[key]).toSet().length, accentKeys.length); }); test('All color swatch colors are opaque and equal their primary color', () { - for (MaterialColor color in Colors.primaries) { + for (final MaterialColor color in Colors.primaries) { expect(color.value, color.shade500.value); - for (int key in primaryKeys) { + for (final int key in primaryKeys) { expect(color[key].alpha, 0xFF); } } expect(Colors.grey.value, Colors.grey.shade500.value); - for (int key in primaryKeys) { + for (final int key in primaryKeys) { expect(Colors.grey[key].alpha, 0xFF); } - for (MaterialAccentColor color in Colors.accents) { + for (final MaterialAccentColor color in Colors.accents) { expect(color.value, color.shade200.value); - for (int key in accentKeys) { + for (final int key in accentKeys) { expect(color[key].alpha, 0xFF); } } diff --git a/packages/flutter/test/material/date_picker_test.dart b/packages/flutter/test/material/date_picker_test.dart index b2cd46b8c45..7b683c8db7c 100644 --- a/packages/flutter/test/material/date_picker_test.dart +++ b/packages/flutter/test/material/date_picker_test.dart @@ -742,7 +742,7 @@ void _tests() { // Initial chevron animation state should be dismissed // An AlwaysStoppedAnimation is also found and is ignored - for (RenderAnimatedOpacity renderer in chevronRenderers) { + for (final RenderAnimatedOpacity renderer in chevronRenderers) { expect(renderer.opacity.value, equals(1.0)); expect(renderer.opacity.status, equals(AnimationStatus.dismissed)); } @@ -751,7 +751,7 @@ void _tests() { final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await gesture.moveBy(const Offset(50.0, 100.0)); await tester.pumpAndSettle(); - for (RenderAnimatedOpacity renderer in chevronRenderers) { + for (final RenderAnimatedOpacity renderer in chevronRenderers) { expect(renderer.opacity.value, equals(0.0)); expect(renderer.opacity.status, equals(AnimationStatus.completed)); } @@ -759,7 +759,7 @@ void _tests() { // Release the drag and test for the opacity to return to original value await gesture.up(); await tester.pumpAndSettle(); - for (RenderAnimatedOpacity renderer in chevronRenderers) { + for (final RenderAnimatedOpacity renderer in chevronRenderers) { expect(renderer.opacity.value, equals(1.0)); expect(renderer.opacity.status, equals(AnimationStatus.dismissed)); } diff --git a/packages/flutter/test/material/dropdown_form_field_test.dart b/packages/flutter/test/material/dropdown_form_field_test.dart index ef98d30f587..5ad34d7d8b1 100644 --- a/packages/flutter/test/material/dropdown_form_field_test.dart +++ b/packages/flutter/test/material/dropdown_form_field_test.dart @@ -264,7 +264,7 @@ void main() { final double menuItemHeight = itemBoxesHeight.reduce(math.max); expect(menuItemHeight, greaterThanOrEqualTo(buttonBox.size.height)); - for (RenderBox itemBox in itemBoxes) { + for (final RenderBox itemBox in itemBoxes) { expect(itemBox.attached, isTrue); final Offset buttonBoxCenter = buttonBox.size.center(buttonBox.localToGlobal(Offset.zero)); final Offset itemBoxCenter = itemBox.size.center(itemBox.localToGlobal(Offset.zero)); diff --git a/packages/flutter/test/material/dropdown_test.dart b/packages/flutter/test/material/dropdown_test.dart index b8c6e81d04a..795822c42c4 100644 --- a/packages/flutter/test/material/dropdown_test.dart +++ b/packages/flutter/test/material/dropdown_test.dart @@ -447,7 +447,7 @@ void main() { await tester.pump(const Duration(seconds: 1)); // finish the menu animation }); - for (TextDirection textDirection in TextDirection.values) { + for (final TextDirection textDirection in TextDirection.values) { testWidgets('Dropdown button aligns selected menu item ($textDirection)', (WidgetTester tester) async { final Key buttonKey = UniqueKey(); const String value = 'two'; @@ -471,7 +471,7 @@ void main() { // have the same origin and height as the dropdown button. final List itemBoxes = tester.renderObjectList(find.byKey(const ValueKey('two'))).toList(); expect(itemBoxes.length, equals(2)); - for (RenderBox itemBox in itemBoxes) { + for (final RenderBox itemBox in itemBoxes) { assert(itemBox.attached); assert(textDirection != null); switch (textDirection) { @@ -664,7 +664,7 @@ void main() { final double menuItemHeight = itemBoxes.map((RenderBox box) => box.size.height).reduce(math.max); expect(menuItemHeight, greaterThan(buttonBox.size.height)); - for (RenderBox itemBox in itemBoxes) { + for (final RenderBox itemBox in itemBoxes) { assert(itemBox.attached); final Offset buttonBoxCenter = buttonBox.size.center(buttonBox.localToGlobal(Offset.zero)); final Offset itemBoxCenter = itemBox.size.center(itemBox.localToGlobal(Offset.zero)); diff --git a/packages/flutter/test/material/floating_action_button_location_test.dart b/packages/flutter/test/material/floating_action_button_location_test.dart index e898bb5dbb9..264e7197b9b 100644 --- a/packages/flutter/test/material/floating_action_button_location_test.dart +++ b/packages/flutter/test/material/floating_action_button_location_test.dart @@ -137,9 +137,9 @@ void main() { && currentRotations != null && currentRotations.isNotEmpty && previousRect != null && currentRect != null) { final List deltas = []; - for (double currentRotation in currentRotations) { + for (final double currentRotation in currentRotations) { double minDelta; - for (double previousRotation in previousRotations) { + for (final double previousRotation in previousRotations) { final double delta = (previousRotation - currentRotation).abs(); minDelta ??= delta; minDelta = min(delta, minDelta); diff --git a/packages/flutter/test/material/material_test.dart b/packages/flutter/test/material/material_test.dart index a862fd4d304..c48b3b7911d 100644 --- a/packages/flutter/test/material/material_test.dart +++ b/packages/flutter/test/material/material_test.dart @@ -251,7 +251,7 @@ void main() { ElevationColor(24.0, Color(0xFF20362B)), ]; - for (ElevationColor test in elevationColors) { + for (final ElevationColor test in elevationColors) { await tester.pumpWidget( Theme( data: ThemeData( diff --git a/packages/flutter/test/material/page_selector_test.dart b/packages/flutter/test/material/page_selector_test.dart index 43be2d76c8c..35e24dc375c 100644 --- a/packages/flutter/test/material/page_selector_test.dart +++ b/packages/flutter/test/material/page_selector_test.dart @@ -212,7 +212,7 @@ void main() { ).evaluate(); // Indicators get an 8 pixel margin, 16 + 8 = 24. - for (Element indicatorElement in indicatorElements) + for (final Element indicatorElement in indicatorElements) expect(indicatorElement.size, const Size(24.0, 24.0)); expect(tester.getSize(find.byType(TabPageSelector)).height, 24.0); diff --git a/packages/flutter/test/material/reorderable_list_test.dart b/packages/flutter/test/material/reorderable_list_test.dart index 8ae34726122..94568e84a96 100644 --- a/packages/flutter/test/material/reorderable_list_test.dart +++ b/packages/flutter/test/material/reorderable_list_test.dart @@ -316,7 +316,7 @@ void main() { testWidgets('Provides the correct accessibility actions in LTR and RTL modes', (WidgetTester tester) async { // The a11y actions for a vertical list are the same in LTR and RTL modes. final SemanticsHandle handle = tester.ensureSemantics(); - for (TextDirection direction in TextDirection.values) { + for (final TextDirection direction in TextDirection.values) { await tester.pumpWidget(build()); // The first item can be moved down or to the end. diff --git a/packages/flutter/test/material/theme_data_test.dart b/packages/flutter/test/material/theme_data_test.dart index fbad907149a..041ed51daf5 100644 --- a/packages/flutter/test/material/theme_data_test.dart +++ b/packages/flutter/test/material/theme_data_test.dart @@ -21,7 +21,7 @@ void main() { }); test('Defaults to the default typography for the platform', () { - for (TargetPlatform platform in TargetPlatform.values) { + for (final TargetPlatform platform in TargetPlatform.values) { final ThemeData theme = ThemeData(platform: platform); final Typography typography = Typography(platform: platform); expect(theme.textTheme, typography.black.apply(decoration: TextDecoration.none), diff --git a/packages/flutter/test/material/theme_test.dart b/packages/flutter/test/material/theme_test.dart index dd9513c1754..837ec1aaa86 100644 --- a/packages/flutter/test/material/theme_test.dart +++ b/packages/flutter/test/material/theme_test.dart @@ -148,7 +148,7 @@ void main() { await tester.tap(find.byKey(dropdownMenuButtonKey)); await tester.pump(const Duration(seconds: 1)); - for (Element item in tester.elementList(find.text('menuItem'))) + for (final Element item in tester.elementList(find.text('menuItem'))) expect(Theme.of(item).brightness, equals(Brightness.light)); }); @@ -390,8 +390,8 @@ void main() { ]; } - for (TextTheme textTheme in [theme.textTheme, theme.primaryTextTheme, theme.accentTextTheme]) { - for (TextStyle style in extractStyles(textTheme).map((TextStyle style) => _TextStyleProxy(style))) { + for (final TextTheme textTheme in [theme.textTheme, theme.primaryTextTheme, theme.accentTextTheme]) { + for (final TextStyle style in extractStyles(textTheme).map((TextStyle style) => _TextStyleProxy(style))) { expect(style.inherit, false); expect(style.color, isNotNull); expect(style.fontFamily, isNotNull); diff --git a/packages/flutter/test/material/time_picker_test.dart b/packages/flutter/test/material/time_picker_test.dart index 4be6efdcc19..d5a4d439cb7 100644 --- a/packages/flutter/test/material/time_picker_test.dart +++ b/packages/flutter/test/material/time_picker_test.dart @@ -734,7 +734,7 @@ class _CustomPainterSemanticsTester { final PaintPattern expectedLabels = paints; int i = 0; - for (_SemanticsNodeExpectation expectation in expectedNodes) { + for (final _SemanticsNodeExpectation expectation in expectedNodes) { expect(semantics, includesNodeWith(value: expectation.label)); final Iterable dialLabelNodes = semantics .nodesWith(value: expectation.label) diff --git a/packages/flutter/test/material/typography_test.dart b/packages/flutter/test/material/typography_test.dart index c4c642d9365..726f2c4de99 100644 --- a/packages/flutter/test/material/typography_test.dart +++ b/packages/flutter/test/material/typography_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('Typography is defined for all target platforms', () { - for (TargetPlatform platform in TargetPlatform.values) { + for (final TargetPlatform platform in TargetPlatform.values) { final Typography typography = Typography(platform: platform); expect(typography, isNotNull, reason: 'null typography for $platform'); expect(typography.black, isNotNull, reason: 'null black typography for $platform'); @@ -32,7 +32,7 @@ void main() { }, 'Uses SF Text font'); final Typography typography = Typography(platform: TargetPlatform.iOS); - for (TextTheme textTheme in [typography.black, typography.white]) { + for (final TextTheme textTheme in [typography.black, typography.white]) { expect(textTheme.display4, isDisplayFont); expect(textTheme.display3, isDisplayFont); expect(textTheme.display2, isDisplayFont); diff --git a/packages/flutter/test/painting/alignment_test.dart b/packages/flutter/test/painting/alignment_test.dart index fd487f2ff9b..15691d677f8 100644 --- a/packages/flutter/test/painting/alignment_test.dart +++ b/packages/flutter/test/painting/alignment_test.dart @@ -57,14 +57,14 @@ void main() { expect(topEnd * 1.0, topEnd); expect(topLeft * 1.0, topLeft); expect(topRight * 1.0, topRight); - for (double n in numbers) { + for (final double n in numbers) { expect((topStart * n).add(topStart), topStart * (n + 1.0)); expect((topEnd * n).add(topEnd), topEnd * (n + 1.0)); - for (double m in numbers) + for (final double m in numbers) expect((topStart * n).add(topStart * m), topStart * (n + m)); } expect(topStart + topStart + topStart, topStart * 3.0); // without using "add" - for (TextDirection x in TextDirection.values) { + for (final TextDirection x in TextDirection.values) { expect((topEnd * 0.0).add(topRight * 0.0).resolve(x), center.add(center).resolve(x)); expect((topEnd * 0.0).add(topLeft).resolve(x), center.add(topLeft).resolve(x)); expect(((topEnd * 0.0).resolve(x)).add(topLeft.resolve(x)), (center.resolve(x)).add(topLeft.resolve(x))); @@ -107,7 +107,7 @@ void main() { final AlignmentGeometry mixed2 = const Alignment(70.0, 110.0).add(const AlignmentDirectional(130.0, 170.0)); final AlignmentGeometry mixed3 = const Alignment(25.0, 42.5).add(const AlignmentDirectional(55.0, 80.0)); - for (TextDirection direction in TextDirection.values) { + for (final TextDirection direction in TextDirection.values) { expect(AlignmentGeometry.lerp(mixed1, mixed2, 0.0).resolve(direction), mixed1.resolve(direction)); expect(AlignmentGeometry.lerp(mixed1, mixed2, 1.0).resolve(direction), mixed2.resolve(direction)); expect(AlignmentGeometry.lerp(mixed1, mixed2, 0.25).resolve(direction), mixed3.resolve(direction)); @@ -150,17 +150,17 @@ void main() { final List times = [ 0.25, 0.5, 0.75 ]; - for (TextDirection direction in TextDirection.values) { + for (final TextDirection direction in TextDirection.values) { final Alignment defaultValue = AlignmentDirectional.center.resolve(direction); - for (AlignmentGeometry a in offsets) { + for (final AlignmentGeometry a in offsets) { final Alignment resolvedA = a?.resolve(direction) ?? defaultValue; - for (AlignmentGeometry b in offsets) { + for (final AlignmentGeometry b in offsets) { final Alignment resolvedB = b?.resolve(direction) ?? defaultValue; approxExpect(Alignment.lerp(resolvedA, resolvedB, 0.0), resolvedA); approxExpect(Alignment.lerp(resolvedA, resolvedB, 1.0), resolvedB); approxExpect((AlignmentGeometry.lerp(a, b, 0.0) ?? defaultValue).resolve(direction), resolvedA); approxExpect((AlignmentGeometry.lerp(a, b, 1.0) ?? defaultValue).resolve(direction), resolvedB); - for (double t in times) { + for (final double t in times) { assert(t > 0.0); assert(t < 1.0); final Alignment value = (AlignmentGeometry.lerp(a, b, t) ?? defaultValue).resolve(direction); @@ -191,7 +191,7 @@ void main() { expect(const AlignmentDirectional(1.0, 2.0) / 2.0, const AlignmentDirectional(0.5, 1.0)); expect(const AlignmentDirectional(1.0, 2.0) % 2.0, const AlignmentDirectional(1.0, 0.0)); expect(const AlignmentDirectional(1.0, 2.0) ~/ 2.0, const AlignmentDirectional(0.0, 1.0)); - for (TextDirection direction in TextDirection.values) { + for (final TextDirection direction in TextDirection.values) { expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) * 2.0).resolve(direction), const AlignmentDirectional(2.0, 4.0).resolve(direction)); expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) / 2.0).resolve(direction), const AlignmentDirectional(0.5, 1.0).resolve(direction)); expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) % 2.0).resolve(direction), const AlignmentDirectional(1.0, 0.0).resolve(direction)); diff --git a/packages/flutter/test/painting/decoration_test.dart b/packages/flutter/test/painting/decoration_test.dart index b869fee1c71..1e1b6613793 100644 --- a/packages/flutter/test/painting/decoration_test.dart +++ b/packages/flutter/test/painting/decoration_test.dart @@ -521,7 +521,7 @@ void main() { BoxFit.scaleDown, ]; - for (BoxFit boxFit in boxFits) { + for (final BoxFit boxFit in boxFits) { final TestCanvas canvas = TestCanvas([]); const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0); diff --git a/packages/flutter/test/painting/gradient_test.dart b/packages/flutter/test/painting/gradient_test.dart index d47a1646c13..41bd3e74f73 100644 --- a/packages/flutter/test/painting/gradient_test.dart +++ b/packages/flutter/test/painting/gradient_test.dart @@ -814,13 +814,13 @@ void main() { } testWidgets('Gradients - 45 degrees', (WidgetTester tester) async { - for (Gradient gradient in gradients45) { + for (final Gradient gradient in gradients45) { await runTest(tester, gradient, 45); } }, skip: isBrowser); // TODO(yjbanov): web does not support golden tests yet: https://github.com/flutter/flutter/issues/40297 testWidgets('Gradients - 90 degrees', (WidgetTester tester) async { - for (Gradient gradient in gradients90) { + for (final Gradient gradient in gradients90) { await runTest(tester, gradient, 90); } }, skip: isBrowser); // TODO(yjbanov): web does not support golden tests yet: https://github.com/flutter/flutter/issues/40297 diff --git a/packages/flutter/test/painting/text_painter_test.dart b/packages/flutter/test/painting/text_painter_test.dart index e7063eac5d3..e2996f090fc 100644 --- a/packages/flutter/test/painting/text_painter_test.dart +++ b/packages/flutter/test/painting/text_painter_test.dart @@ -749,7 +749,7 @@ void main() { // be removed when it is no longer useful. if (lines[1].hardBreak == true) { print('LineMetrics called: ${lines.length}'); - for (ui.LineMetrics line in lines) { + for (final ui.LineMetrics line in lines) { print('${line.lineNumber}: ${line.hardBreak}'); } } diff --git a/packages/flutter/test/rendering/annotated_region_test.dart b/packages/flutter/test/rendering/annotated_region_test.dart index 29dc34b91b5..81f696d7f48 100644 --- a/packages/flutter/test/rendering/annotated_region_test.dart +++ b/packages/flutter/test/rendering/annotated_region_test.dart @@ -16,7 +16,7 @@ void main() { OffsetLayer(offset: const Offset(0.0, 200.0)), ]; int i = 0; - for (OffsetLayer layer in layers) { + for (final OffsetLayer layer in layers) { layer.append(AnnotatedRegionLayer(i, size: const Size(200.0, 100.0))); containerLayer.append(layer); i += 1; @@ -35,7 +35,7 @@ void main() { ClipRectLayer(clipRect: const Rect.fromLTRB(0.0, 200.0, 100.0, 300.0)), ]; int i = 0; - for (ClipRectLayer layer in layers) { + for (final ClipRectLayer layer in layers) { layer.append(AnnotatedRegionLayer(i)); containerLayer.append(layer); i += 1; @@ -55,7 +55,7 @@ void main() { ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0))), ]; int i = 0; - for (ClipRRectLayer layer in layers) { + for (final ClipRRectLayer layer in layers) { layer.append(AnnotatedRegionLayer(i)); containerLayer.append(layer); i += 1; @@ -80,7 +80,7 @@ void main() { OffsetLayer(offset: const Offset(0.0, 200.0)), ]; int i = 0; - for (OffsetLayer layer in layers) { + for (final OffsetLayer layer in layers) { final AnnotatedRegionLayer annotatedRegionLayer = AnnotatedRegionLayer(i, size: const Size(100.0, 100.0)); layer.append(annotatedRegionLayer); transformLayer.append(layer); @@ -145,7 +145,7 @@ void main() { OffsetLayer(offset: const Offset(0.0, 200.0)), ]; int i = 0; - for (OffsetLayer layer in layers) { + for (final OffsetLayer layer in layers) { layer.append(AnnotatedRegionLayer(i, size: const Size(200.0, 100.0))); containerLayer.append(layer); i += 1; @@ -164,7 +164,7 @@ void main() { ClipRectLayer(clipRect: const Rect.fromLTRB(0.0, 200.0, 100.0, 300.0)), ]; int i = 0; - for (ClipRectLayer layer in layers) { + for (final ClipRectLayer layer in layers) { layer.append(AnnotatedRegionLayer(i)); containerLayer.append(layer); i += 1; @@ -184,7 +184,7 @@ void main() { ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0))), ]; int i = 0; - for (ClipRRectLayer layer in layers) { + for (final ClipRRectLayer layer in layers) { layer.append(AnnotatedRegionLayer(i)); containerLayer.append(layer); i += 1; @@ -209,7 +209,7 @@ void main() { OffsetLayer(offset: const Offset(0.0, 200.0)), ]; int i = 0; - for (OffsetLayer layer in layers) { + for (final OffsetLayer layer in layers) { final AnnotatedRegionLayer annotatedRegionLayer = AnnotatedRegionLayer(i, size: const Size(100.0, 100.0)); layer.append(annotatedRegionLayer); transformLayer.append(layer); @@ -231,7 +231,7 @@ void main() { AnnotatedRegionLayer(index++, size: const Size(100.0, 100.0)), AnnotatedRegionLayer(index++, size: const Size(100.0, 100.0)), ]; - for (ContainerLayer layer in layers) { + for (final ContainerLayer layer in layers) { final AnnotatedRegionLayer annotatedRegionLayer = AnnotatedRegionLayer(index++, size: const Size(100.0, 100.0)); layer.append(annotatedRegionLayer); parent.append(layer); diff --git a/packages/flutter/test/rendering/layer_annotations_test.dart b/packages/flutter/test/rendering/layer_annotations_test.dart index e89da636751..b3bd5d1adbf 100644 --- a/packages/flutter/test/rendering/layer_annotations_test.dart +++ b/packages/flutter/test/rendering/layer_annotations_test.dart @@ -674,7 +674,7 @@ class _Layers { assert(!_assigned); _assigned = true; if (children != null) { - for (Object child in children) { + for (final Object child in children) { Layer layer; if (child is Layer) { layer = child; diff --git a/packages/flutter/test/rendering/layers_test.dart b/packages/flutter/test/rendering/layers_test.dart index e57b76b5c30..231e15c455e 100644 --- a/packages/flutter/test/rendering/layers_test.dart +++ b/packages/flutter/test/rendering/layers_test.dart @@ -113,15 +113,15 @@ void main() { b.append(f); c.append(g); - for (ContainerLayer layer in allLayers) { + for (final ContainerLayer layer in allLayers) { expect(layer.debugSubtreeNeedsAddToScene, true); } - for (ContainerLayer layer in allLayers) { + for (final ContainerLayer layer in allLayers) { layer.debugMarkClean(); } - for (ContainerLayer layer in allLayers) { + for (final ContainerLayer layer in allLayers) { expect(layer.debugSubtreeNeedsAddToScene, false); } @@ -148,7 +148,7 @@ void main() { expect(g.debugSubtreeNeedsAddToScene, true); a.buildScene(SceneBuilder()); - for (ContainerLayer layer in allLayers) { + for (final ContainerLayer layer in allLayers) { expect(layer.debugSubtreeNeedsAddToScene, false); } }); diff --git a/packages/flutter/test/rendering/mock_canvas.dart b/packages/flutter/test/rendering/mock_canvas.dart index 345187ef11d..869db0484f8 100644 --- a/packages/flutter/test/rendering/mock_canvas.dart +++ b/packages/flutter/test/rendering/mock_canvas.dart @@ -456,10 +456,10 @@ class _PathMatcher extends Matcher { } final Path path = object as Path; final List errors = [ - for (Offset offset in includes) + for (final Offset offset in includes) if (!path.contains(offset)) 'Offset $offset should be inside the path, but is not.', - for (Offset offset in excludes) + for (final Offset offset in excludes) if (path.contains(offset)) 'Offset $offset should be outside the path, but is not.', ]; @@ -546,7 +546,7 @@ abstract class _TestRecordingCanvasMatcher extends Matcher { if (!result) { if (canvas.invocations.isNotEmpty) { description.write('The complete display list was:'); - for (RecordedInvocation call in canvas.invocations) + for (final RecordedInvocation call in canvas.invocations) description.write('\n * $call'); } matchState[this] = '$prefixMessage\n$description'; @@ -583,7 +583,7 @@ class _TestRecordingCanvasPaintsCountMatcher extends _TestRecordingCanvasMatcher @override bool _evaluatePredicates(Iterable calls, StringBuffer description) { int count = 0; - for (RecordedInvocation call in calls) { + for (final RecordedInvocation call in calls) { if (call.invocation.isMethod && call.invocation.memberName == _methodName) { count++; } @@ -651,7 +651,7 @@ class _TestRecordingCanvasPaintsAssertionMatcher extends Matcher { if (!result) { if (canvas.invocations.isNotEmpty) { description.write('The complete display list was:'); - for (RecordedInvocation call in canvas.invocations) + for (final RecordedInvocation call in canvas.invocations) description.write('\n * $call'); } matchState[this] = '$prefixMessage\n$description'; @@ -1159,13 +1159,13 @@ class _PathPaintPredicate extends _DrawCommandPaintPredicate { super.verifyArguments(arguments); final Path pathArgument = arguments[0] as Path; if (includes != null) { - for (Offset offset in includes) { + for (final Offset offset in includes) { if (!pathArgument.contains(offset)) throw 'It called $methodName with a path that unexpectedly did not contain $offset.'; } } if (excludes != null) { - for (Offset offset in excludes) { + for (final Offset offset in excludes) { if (pathArgument.contains(offset)) throw 'It called $methodName with a path that unexpectedly contained $offset.'; } @@ -1243,13 +1243,13 @@ class _ShadowPredicate extends _PaintPredicate { throw 'It called $methodName with ${arguments.length} arguments; expected 4.'; final Path pathArgument = arguments[0] as Path; if (includes != null) { - for (Offset offset in includes) { + for (final Offset offset in includes) { if (!pathArgument.contains(offset)) throw 'It called $methodName with a path that unexpectedly did not contain $offset.'; } } if (excludes != null) { - for (Offset offset in excludes) { + for (final Offset offset in excludes) { if (pathArgument.contains(offset)) throw 'It called $methodName with a path that unexpectedly contained $offset.'; } diff --git a/packages/flutter/test/rendering/slivers_helpers_test.dart b/packages/flutter/test/rendering/slivers_helpers_test.dart index 9b30daccc88..5d942522097 100644 --- a/packages/flutter/test/rendering/slivers_helpers_test.dart +++ b/packages/flutter/test/rendering/slivers_helpers_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('applyGrowthDirectionToAxisDirection produces expected AxisDirection', () { expect(AxisDirection.values.length, 4); - for (AxisDirection axisDirection in AxisDirection.values) { + for (final AxisDirection axisDirection in AxisDirection.values) { expect(applyGrowthDirectionToAxisDirection(axisDirection, GrowthDirection.forward), axisDirection); } expect(applyGrowthDirectionToAxisDirection(AxisDirection.up, GrowthDirection.reverse), AxisDirection.down); diff --git a/packages/flutter/test/rendering/table_test.dart b/packages/flutter/test/rendering/table_test.dart index b8ac8db4d4e..0d082e1365f 100644 --- a/packages/flutter/test/rendering/table_test.dart +++ b/packages/flutter/test/rendering/table_test.dart @@ -55,7 +55,7 @@ void main() { layout(table, constraints: const BoxConstraints.tightFor(width: 100.0)); const double expectedWidth = 100.0 / 6; - for (RenderBox child in children) { + for (final RenderBox child in children) { expect(child.size.width, moreOrLessEquals(expectedWidth)); } }); diff --git a/packages/flutter/test/semantics/semantics_test.dart b/packages/flutter/test/semantics/semantics_test.dart index c3884828c74..527c336514e 100644 --- a/packages/flutter/test/semantics/semantics_test.dart +++ b/packages/flutter/test/semantics/semantics_test.dart @@ -264,7 +264,7 @@ void main() { final List expectedResults = [0, -1, 1, 0]; assert(tests.length == expectedResults.length); final List results = [ - for (List tuple in tests) tuple[0].compareTo(tuple[1]), + for (final List tuple in tests) tuple[0].compareTo(tuple[1]), ]; expect(results, orderedEquals(expectedResults)); }); @@ -279,7 +279,7 @@ void main() { final List expectedResults = [0, -1, 1, 0]; assert(tests.length == expectedResults.length); final List results = [ - for (List tuple in tests) tuple[0].compareTo(tuple[1]), + for (final List tuple in tests) tuple[0].compareTo(tuple[1]), ]; expect(results, orderedEquals(expectedResults)); }); diff --git a/packages/flutter/test/services/font_loader_test.dart b/packages/flutter/test/services/font_loader_test.dart index c0242e7e172..029d7e76b5b 100644 --- a/packages/flutter/test/services/font_loader_test.dart +++ b/packages/flutter/test/services/font_loader_test.dart @@ -29,7 +29,7 @@ void main() { Uint8List.fromList([200]), ]; - for (Uint8List asset in expectedAssets) { + for (final Uint8List asset in expectedAssets) { tfl.addFont(Future.value(ByteData.view(asset.buffer))); } await tfl.load(); diff --git a/packages/flutter/test/services/raw_keyboard_test.dart b/packages/flutter/test/services/raw_keyboard_test.dart index 6c9dce864af..066ace86869 100644 --- a/packages/flutter/test/services/raw_keyboard_test.dart +++ b/packages/flutter/test/services/raw_keyboard_test.dart @@ -15,7 +15,7 @@ class _ModifierCheck { void main() { group('RawKeyboard', () { testWidgets('keysPressed is maintained', (WidgetTester tester) async { - for (String platform in ['linux', 'android', 'macos', 'fuchsia']) { + for (final String platform in ['linux', 'android', 'macos', 'fuchsia']) { RawKeyboard.instance.clearKeysPressed(); expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); @@ -224,7 +224,7 @@ void main() { }; test('modifier keys are recognized individually', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { final RawKeyEvent event = RawKeyEvent.fromMessage({ 'type': 'keydown', 'keymap': 'android', @@ -237,7 +237,7 @@ void main() { 'deviceId': 1, }); final RawKeyEventDataAndroid data = event.data as RawKeyEventDataAndroid; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -256,7 +256,7 @@ void main() { } }); test('modifier keys are recognized when combined', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { if (modifier == RawKeyEventDataAndroid.modifierFunction) { // No need to combine function key with itself. continue; @@ -273,7 +273,7 @@ void main() { 'deviceId': 1, }); final RawKeyEventDataAndroid data = event.data as RawKeyEventDataAndroid; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key || key == ModifierKey.functionModifier) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -454,7 +454,7 @@ void main() { }; test('modifier keys are recognized individually', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { final RawKeyEvent event = RawKeyEvent.fromMessage({ 'type': 'keydown', 'keymap': 'fuchsia', @@ -463,7 +463,7 @@ void main() { 'modifiers': modifier, }); final RawKeyEventDataFuchsia data = event.data as RawKeyEventDataFuchsia; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -481,7 +481,7 @@ void main() { } }); test('modifier keys are recognized when combined', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { if (modifier == RawKeyEventDataFuchsia.modifierCapsLock) { // No need to combine caps lock key with itself. continue; @@ -494,7 +494,7 @@ void main() { 'modifiers': modifier | RawKeyEventDataFuchsia.modifierCapsLock, }); final RawKeyEventDataFuchsia data = event.data as RawKeyEventDataFuchsia; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key || key == ModifierKey.capsLockModifier) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -571,7 +571,7 @@ void main() { }; test('modifier keys are recognized individually', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { final RawKeyEvent event = RawKeyEvent.fromMessage({ 'type': 'keydown', 'keymap': 'macos', @@ -581,7 +581,7 @@ void main() { 'modifiers': modifier, }); final RawKeyEventDataMacOs data = event.data as RawKeyEventDataMacOs; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -600,7 +600,7 @@ void main() { } }); test('modifier keys are recognized when combined', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { if (modifier == RawKeyEventDataMacOs.modifierCapsLock) { // No need to combine caps lock key with itself. continue; @@ -615,7 +615,7 @@ void main() { 'modifiers': modifier | RawKeyEventDataMacOs.modifierCapsLock, }); final RawKeyEventDataMacOs data = event.data as RawKeyEventDataMacOs; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key || key == ModifierKey.capsLockModifier) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -731,9 +731,9 @@ void main() { } test('modifier keys are recognized individually', () { - for (int modifier in modifierTests.keys) { - for (bool isDown in [true, false]) { - for (bool isLeft in [true, false]) { + for (final int modifier in modifierTests.keys) { + for (final bool isDown in [true, false]) { + for (final bool isLeft in [true, false]) { final RawKeyEvent event = RawKeyEvent.fromMessage({ 'type': isDown ? 'keydown' : 'keyup', 'keymap': 'linux', @@ -745,7 +745,7 @@ void main() { 'modifiers': isDown ? 0 : modifier, }); final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -766,7 +766,7 @@ void main() { } }); test('modifier keys are recognized when combined', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { if (modifier == GLFWKeyHelper.modifierControl) { // No need to combine CTRL key with itself. continue; @@ -781,7 +781,7 @@ void main() { 'modifiers': modifier | GLFWKeyHelper.modifierControl, }); final RawKeyEventDataLinux data = event.data as RawKeyEventDataLinux; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier].key == key || key == ModifierKey.controlModifier) { expect( data.isModifierPressed(key, side: modifierTests[modifier].side), @@ -894,7 +894,7 @@ void main() { }; test('modifier keys are recognized individually', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { final RawKeyEvent event = RawKeyEvent.fromMessage({ 'type': 'keydown', 'keymap': 'web', @@ -903,7 +903,7 @@ void main() { 'metaState': modifier, }); final RawKeyEventDataWeb data = event.data as RawKeyEventDataWeb; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier] == key) { expect( data.isModifierPressed(key), @@ -921,7 +921,7 @@ void main() { } }); test('modifier keys are recognized when combined', () { - for (int modifier in modifierTests.keys) { + for (final int modifier in modifierTests.keys) { if (modifier == RawKeyEventDataWeb.modifierMeta) { // No need to combine meta key with itself. continue; @@ -934,7 +934,7 @@ void main() { 'metaState': modifier | RawKeyEventDataWeb.modifierMeta, }); final RawKeyEventDataWeb data = event.data as RawKeyEventDataWeb; - for (ModifierKey key in ModifierKey.values) { + for (final ModifierKey key in ModifierKey.values) { if (modifierTests[modifier] == key || key == ModifierKey.metaModifier) { expect( data.isModifierPressed(key), diff --git a/packages/flutter/test/widgets/animated_switcher_test.dart b/packages/flutter/test/widgets/animated_switcher_test.dart index b6db226b469..38648528829 100644 --- a/packages/flutter/test/widgets/animated_switcher_test.dart +++ b/packages/flutter/test/widgets/animated_switcher_test.dart @@ -261,7 +261,7 @@ void main() { ); expect(find.byType(Column), findsOneWidget); - for (Widget child in foundChildren) { + for (final Widget child in foundChildren) { expect(child, isInstanceOf()); } @@ -279,7 +279,7 @@ void main() { ); await tester.pump(const Duration(milliseconds: 50)); - for (Widget child in foundChildren) { + for (final Widget child in foundChildren) { expect(child, isInstanceOf()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(SizeTransition)), @@ -429,7 +429,7 @@ void main() { await tester.pump(const Duration(milliseconds: 10)); expect(foundChildren.length, equals(3)); - for (Widget child in foundChildren) { + for (final Widget child in foundChildren) { expect(child, isInstanceOf()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(FadeTransition)), @@ -459,7 +459,7 @@ void main() { await tester.pump(const Duration(milliseconds: 10)); expect(foundChildren.length, equals(3)); - for (Widget child in foundChildren) { + for (final Widget child in foundChildren) { expect(child, isInstanceOf()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(ScaleTransition)), diff --git a/packages/flutter/test/widgets/build_scope_test.dart b/packages/flutter/test/widgets/build_scope_test.dart index 5ab5d2c1992..f17d2926110 100644 --- a/packages/flutter/test/widgets/build_scope_test.dart +++ b/packages/flutter/test/widgets/build_scope_test.dart @@ -210,12 +210,12 @@ void main() { middle = part2; await tester.pumpWidget(part1); - for (StatefulWrapperState state in tester.stateList(find.byType(StatefulWrapper))) { + for (final StatefulWrapperState state in tester.stateList(find.byType(StatefulWrapper))) { expect(state.built, isNotNull); state.oldBuilt = state.built; state.trigger(); } - for (StateSetter setState in setStates) + for (final StateSetter setState in setStates) setState(() { }); StatefulWrapperState.buildId = 0; @@ -223,7 +223,7 @@ void main() { didMiddle = false; await tester.pumpWidget(part2); - for (StatefulWrapperState state in tester.stateList(find.byType(StatefulWrapper))) { + for (final StatefulWrapperState state in tester.stateList(find.byType(StatefulWrapper))) { expect(state.built, isNotNull); expect(state.built, isNot(equals(state.oldBuilt))); } diff --git a/packages/flutter/test/widgets/custom_painter_test.dart b/packages/flutter/test/widgets/custom_painter_test.dart index 85e2dde4da9..abdd4adeaad 100644 --- a/packages/flutter/test/widgets/custom_painter_test.dart +++ b/packages/flutter/test/widgets/custom_painter_test.dart @@ -374,7 +374,7 @@ void _defineTests() { // Do the actions work? final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner; int expectedLength = 1; - for (SemanticsAction action in allActions) { + for (final SemanticsAction action in allActions) { switch (action) { case SemanticsAction.moveCursorBackwardByCharacter: case SemanticsAction.moveCursorForwardByCharacter: @@ -716,7 +716,7 @@ class _DiffTester { TestSemantics.rootChild( rect: TestSemantics.fullScreen, children: [ - for (String label in labels) + for (final String label in labels) TestSemantics( rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), label: label, @@ -783,7 +783,7 @@ class _SemanticsDiffTest extends CustomPainter { List buildSemantics(Size size) { final List semantics = []; - for (String label in data) { + for (final String label in data) { Key key; if (label.endsWith('-k')) { key = ValueKey(label); diff --git a/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart b/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart index 16ec930e852..db35bf8a0ec 100644 --- a/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart +++ b/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart @@ -82,7 +82,7 @@ void main() { expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 325.0, 800.0, 600.0)); }); - for (TargetPlatform platform in TargetPlatform.values) { + for (final TargetPlatform platform in TargetPlatform.values) { group('$platform Scroll Physics', () { debugDefaultTargetPlatformOverride = platform; diff --git a/packages/flutter/test/widgets/editable_text_test.dart b/packages/flutter/test/widgets/editable_text_test.dart index 638d47f3cc5..34af7e7d6dd 100644 --- a/packages/flutter/test/widgets/editable_text_test.dart +++ b/packages/flutter/test/widgets/editable_text_test.dart @@ -3180,7 +3180,7 @@ void main() { platform == 'macos' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.altLeft, platform: platform); } - for (LogicalKeyboardKey key in keys) { + for (final LogicalKeyboardKey key in keys) { await tester.sendKeyEvent(key, platform: platform); await tester.pump(); } @@ -4039,7 +4039,7 @@ void main() { final List logOrder = ['TextInput.setClient', 'TextInput.show', 'TextInput.setEditableSizeAndTransform', 'TextInput.setStyle', 'TextInput.setEditingState', 'TextInput.setEditingState', 'TextInput.show']; expect(tester.testTextInput.log.length, 7); int index = 0; - for (MethodCall m in tester.testTextInput.log) { + for (final MethodCall m in tester.testTextInput.log) { expect(m.method, logOrder[index]); index++; } @@ -4083,7 +4083,7 @@ void main() { ]; expect(tester.testTextInput.log.length, logOrder.length); int index = 0; - for (MethodCall m in tester.testTextInput.log) { + for (final MethodCall m in tester.testTextInput.log) { expect(m.method, logOrder[index]); index++; } @@ -4131,7 +4131,7 @@ void main() { ]; expect(tester.testTextInput.log.length, logOrder.length); int index = 0; - for (MethodCall m in tester.testTextInput.log) { + for (final MethodCall m in tester.testTextInput.log) { expect(m.method, logOrder[index]); index++; } diff --git a/packages/flutter/test/widgets/fade_in_image_test.dart b/packages/flutter/test/widgets/fade_in_image_test.dart index b2f06788321..5b3b100ea57 100644 --- a/packages/flutter/test/widgets/fade_in_image_test.dart +++ b/packages/flutter/test/widgets/fade_in_image_test.dart @@ -78,7 +78,7 @@ FadeInImageParts findFadeInImage(WidgetTester tester) { final List elements = []; final Iterable rawImageElements = tester.elementList(find.byType(RawImage)); ComponentElement fadeInImageElement; - for (Element rawImageElement in rawImageElements) { + for (final Element rawImageElement in rawImageElements) { Element fadeTransitionElement; rawImageElement.visitAncestorElements((Element ancestor) { if (ancestor.widget is FadeTransition) { diff --git a/packages/flutter/test/widgets/fitted_box_test.dart b/packages/flutter/test/widgets/fitted_box_test.dart index 721d28cf759..0469a5aa7b8 100644 --- a/packages/flutter/test/widgets/fitted_box_test.dart +++ b/packages/flutter/test/widgets/fitted_box_test.dart @@ -407,10 +407,10 @@ void main() { testWidgets('FittedBox layers - none - clip', (WidgetTester tester) async { final List values = [10.0, 50.0, 100.0]; - for (double a in values) { - for (double b in values) { - for (double c in values) { - for (double d in values) { + for (final double a in values) { + for (final double b in values) { + for (final double c in values) { + for (final double d in values) { await tester.pumpWidget( Center( child: SizedBox( diff --git a/packages/flutter/test/widgets/grid_view_layout_test.dart b/packages/flutter/test/widgets/grid_view_layout_test.dart index f3d22433a4d..5486a9fbd0b 100644 --- a/packages/flutter/test/widgets/grid_view_layout_test.dart +++ b/packages/flutter/test/widgets/grid_view_layout_test.dart @@ -32,7 +32,7 @@ void main() { expect(tester.renderObjectList(find.byType(DecoratedBox)), hasLength(4)); - for (RenderBox box in tester.renderObjectList(find.byType(DecoratedBox))) { + for (final RenderBox box in tester.renderObjectList(find.byType(DecoratedBox))) { expect(box.size.width, equals(100.0), reason: 'child width'); expect(box.size.height, equals(100.0), reason: 'child height'); } @@ -59,7 +59,7 @@ void main() { ), ); - for (RenderBox box in tester.renderObjectList(find.byType(DecoratedBox))) { + for (final RenderBox box in tester.renderObjectList(find.byType(DecoratedBox))) { expect(box.size.width, equals(50.0), reason: 'child width'); expect(box.size.height, equals(50.0), reason: 'child height'); } diff --git a/packages/flutter/test/widgets/image_test.dart b/packages/flutter/test/widgets/image_test.dart index 4a7a9538e81..db2d5e74565 100644 --- a/packages/flutter/test/widgets/image_test.dart +++ b/packages/flutter/test/widgets/image_test.dart @@ -1240,7 +1240,7 @@ class TestImageStreamCompleter extends ImageStreamCompleter { _currentImage = imageInfo; } final List localListeners = listeners.toList(); - for (ImageStreamListener listener in localListeners) { + for (final ImageStreamListener listener in localListeners) { if (imageInfo != null) { listener.onImage(imageInfo, false); } diff --git a/packages/flutter/test/widgets/linked_scroll_view_test.dart b/packages/flutter/test/widgets/linked_scroll_view_test.dart index 7517cbf0039..e8f41291aa1 100644 --- a/packages/flutter/test/widgets/linked_scroll_view_test.dart +++ b/packages/flutter/test/widgets/linked_scroll_view_test.dart @@ -84,7 +84,7 @@ class LinkedScrollController extends ScrollController { Iterable link(LinkedScrollPosition driver) sync* { assert(hasClients); - for (LinkedScrollPosition position in positions.cast()) + for (final LinkedScrollPosition position in positions.cast()) yield position.link(driver); } @@ -129,12 +129,12 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { if (newActivity == null) return; if (_beforeActivities != null) { - for (LinkedScrollActivity activity in _beforeActivities) + for (final LinkedScrollActivity activity in _beforeActivities) activity.unlink(this); _beforeActivities.clear(); } if (_afterActivities != null) { - for (LinkedScrollActivity activity in _afterActivities) + for (final LinkedScrollActivity activity in _afterActivities) activity.unlink(this); _afterActivities.clear(); } @@ -154,7 +154,7 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { final double delta = value - minScrollExtent; _beforeActivities ??= HashSet(); _beforeActivities.addAll(owner.linkWithBefore(this)); - for (LinkedScrollActivity activity in _beforeActivities) + for (final LinkedScrollActivity activity in _beforeActivities) beforeOverscroll = math.min(activity.moveBy(delta), beforeOverscroll); assert(beforeOverscroll <= 0.0); } @@ -164,7 +164,7 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { final double delta = value - maxScrollExtent; _afterActivities ??= HashSet(); _afterActivities.addAll(owner.linkWithAfter(this)); - for (LinkedScrollActivity activity in _afterActivities) + for (final LinkedScrollActivity activity in _afterActivities) afterOverscroll = math.max(activity.moveBy(delta), afterOverscroll); assert(afterOverscroll >= 0.0); } @@ -239,7 +239,7 @@ class LinkedScrollActivity extends ScrollActivity { double moveBy(double delta) { assert(drivers.isNotEmpty); ScrollDirection commonDirection; - for (LinkedScrollPosition driver in drivers) { + for (final LinkedScrollPosition driver in drivers) { commonDirection ??= driver.userScrollDirection; if (driver.userScrollDirection != commonDirection) commonDirection = ScrollDirection.idle; @@ -250,7 +250,7 @@ class LinkedScrollActivity extends ScrollActivity { @override void dispose() { - for (LinkedScrollPosition driver in drivers) + for (final LinkedScrollPosition driver in drivers) driver.unlink(this); super.dispose(); } diff --git a/packages/flutter/test/widgets/list_view_builder_test.dart b/packages/flutter/test/widgets/list_view_builder_test.dart index c90aa74f264..8dae1238be8 100644 --- a/packages/flutter/test/widgets/list_view_builder_test.dart +++ b/packages/flutter/test/widgets/list_view_builder_test.dart @@ -299,7 +299,7 @@ void main() { // ListView's height is 600, so items i0-i5 and s0-s4 fit. await tester.pumpWidget(buildFrame(itemCount: 25)); - for (String s in ['i0', 's0', 'i1', 's1', 'i2', 's2', 'i3', 's3', 'i4', 's4', 'i5']) + for (final String s in ['i0', 's0', 'i1', 's1', 'i2', 's2', 'i3', 's3', 'i4', 's4', 'i5']) expect(find.text(s), findsOneWidget); expect(find.text('s5'), findsNothing); expect(find.text('i6'), findsNothing); @@ -307,10 +307,10 @@ void main() { } void check({ List visible = const [], List hidden = const [] }) { - for (int i in visible) { + for (final int i in visible) { expect(find.text('$i'), findsOneWidget); } - for (int i in hidden) { + for (final int i in hidden) { expect(find.text('$i'), findsNothing); } } diff --git a/packages/flutter/test/widgets/multichild_test.dart b/packages/flutter/test/widgets/multichild_test.dart index 0b0e9cd3583..fe6242a6681 100644 --- a/packages/flutter/test/widgets/multichild_test.dart +++ b/packages/flutter/test/widgets/multichild_test.dart @@ -17,7 +17,7 @@ void checkTree(WidgetTester tester, List expectedDecorations) { final RenderStack renderObject = element.renderObject as RenderStack; try { RenderObject child = renderObject.firstChild; - for (BoxDecoration decoration in expectedDecorations) { + for (final BoxDecoration decoration in expectedDecorations) { expect(child is RenderDecoratedBox, isTrue); final RenderDecoratedBox decoratedBox = child as RenderDecoratedBox; expect(decoratedBox.decoration, equals(decoration)); diff --git a/packages/flutter/test/widgets/page_view_test.dart b/packages/flutter/test/widgets/page_view_test.dart index 405ee458c44..f48c62c2c38 100644 --- a/packages/flutter/test/widgets/page_view_test.dart +++ b/packages/flutter/test/widgets/page_view_test.dart @@ -663,7 +663,7 @@ void main() { await tester.pumpWidget(build()); // The first 3 items should be visible and tappable. - for (int index in visiblePages) { + for (final int index in visiblePages) { expect(find.text(index.toString()), findsOneWidget); // The center of page 2's x-coordinate is 800, so we have to manually // offset it a bit to make sure the tap lands within the screen. @@ -676,7 +676,7 @@ void main() { await tester.pump(); // The last 3 items should be visible and tappable. visiblePages = const [17, 18, 19]; - for (int index in visiblePages) { + for (final int index in visiblePages) { expect(find.text('$index'), findsOneWidget); await tester.tap(find.text('$index')); expect(tappedIndex, index); diff --git a/packages/flutter/test/widgets/parent_data_test.dart b/packages/flutter/test/widgets/parent_data_test.dart index f53377257c2..4b450a44d3d 100644 --- a/packages/flutter/test/widgets/parent_data_test.dart +++ b/packages/flutter/test/widgets/parent_data_test.dart @@ -26,7 +26,7 @@ void checkTree(WidgetTester tester, List expectedParentData) { final RenderStack renderObject = element.renderObject as RenderStack; try { RenderObject child = renderObject.firstChild; - for (TestParentData expected in expectedParentData) { + for (final TestParentData expected in expectedParentData) { expect(child is RenderDecoratedBox, isTrue); final RenderDecoratedBox decoratedBox = child as RenderDecoratedBox; expect(decoratedBox.parentData is StackParentData, isTrue); diff --git a/packages/flutter/test/widgets/routes_test.dart b/packages/flutter/test/widgets/routes_test.dart index 02b8d9cc636..32bde1e1a17 100644 --- a/packages/flutter/test/widgets/routes_test.dart +++ b/packages/flutter/test/widgets/routes_test.dart @@ -82,7 +82,7 @@ class TestRoute extends Route with LocalHistoryRoute { @override void dispose() { log('dispose'); - for (OverlayEntry entry in _entries) + for (final OverlayEntry entry in _entries) entry.remove(); _entries.clear(); routes.remove(this); diff --git a/packages/flutter/test/widgets/scrollbar_test.dart b/packages/flutter/test/widgets/scrollbar_test.dart index f0809b78017..0ad1a7eb6e0 100644 --- a/packages/flutter/test/widgets/scrollbar_test.dart +++ b/packages/flutter/test/widgets/scrollbar_test.dart @@ -123,7 +123,7 @@ void main() { ]; double lastCoefficient; - for (ScrollMetrics metrics in metricsList) { + for (final ScrollMetrics metrics in metricsList) { painter.update(metrics, metrics.axisDirection); painter.paint(testCanvas, size); @@ -154,7 +154,7 @@ void main() { const double minLen = 0; const List margins = [-10, 1, viewportDimension/2 - 0.01]; - for(double margin in margins) { + for (final double margin in margins) { painter = _buildPainter( mainAxisMargin: margin, minLength: minLen, @@ -194,14 +194,14 @@ void main() { const Size size = Size(600, viewportDimension); const double margin = 4; - for(TextDirection textDirection in TextDirection.values) { + for (final TextDirection textDirection in TextDirection.values) { painter = _buildPainter( crossAxisMargin: margin, scrollMetrics: startingMetrics, textDirection: textDirection, ); - for(AxisDirection direction in AxisDirection.values) { + for (final AxisDirection direction in AxisDirection.values) { painter.update( startingMetrics.copyWith(axisDirection: direction), direction, @@ -454,7 +454,7 @@ void main() { viewportDimension: size.height, ); - for(double minLength in [_kMinThumbExtent, double.infinity]) { + for (final double minLength in [_kMinThumbExtent, double.infinity]) { // Disregard `minLength` and `minOverscrollLength` to keep // scroll direction correct, if needed painter = _buildPainter( @@ -471,7 +471,7 @@ void main() { Rect previousRect; - for(ScrollMetrics metrics in metricsList) { + for (final ScrollMetrics metrics in metricsList) { painter.update(metrics, metrics.axisDirection); painter.paint(testCanvas, size); final Rect rect = captureRect(); diff --git a/packages/flutter/test/widgets/semantics_test.dart b/packages/flutter/test/widgets/semantics_test.dart index 8073c7bc65e..2803695d0d2 100644 --- a/packages/flutter/test/widgets/semantics_test.dart +++ b/packages/flutter/test/widgets/semantics_test.dart @@ -436,7 +436,7 @@ void main() { // Do the actions work? final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner; int expectedLength = 1; - for (SemanticsAction action in allActions) { + for (final SemanticsAction action in allActions) { switch (action) { case SemanticsAction.moveCursorBackwardByCharacter: case SemanticsAction.moveCursorForwardByCharacter: diff --git a/packages/flutter/test/widgets/semantics_tester.dart b/packages/flutter/test/widgets/semantics_tester.dart index 3a518db405e..dc3d2e71ee4 100644 --- a/packages/flutter/test/widgets/semantics_tester.dart +++ b/packages/flutter/test/widgets/semantics_tester.dart @@ -380,7 +380,7 @@ class TestSemantics { if (thickness != null) buf.writeln('$indent thickness: $thickness,'); buf.writeln('$indent children: ['); - for (TestSemantics child in children) { + for (final TestSemantics child in children) { buf.writeln('${child.toString(indentAmount + 2)},'); } buf.writeln('$indent ],'); diff --git a/packages/flutter/test/widgets/semantics_tester_generateTestSemanticsExpressionForCurrentSemanticsTree_test.dart b/packages/flutter/test/widgets/semantics_tester_generateTestSemanticsExpressionForCurrentSemanticsTree_test.dart index f5f599a6399..b94bb2d5cd4 100644 --- a/packages/flutter/test/widgets/semantics_tester_generateTestSemanticsExpressionForCurrentSemanticsTree_test.dart +++ b/packages/flutter/test/widgets/semantics_tester_generateTestSemanticsExpressionForCurrentSemanticsTree_test.dart @@ -62,7 +62,7 @@ void _tests() { .trim() + ','; File findThisTestFile(Directory directory) { - for (FileSystemEntity entity in directory.listSync()) { + for (final FileSystemEntity entity in directory.listSync()) { if (entity is Directory) { final File childSearch = findThisTestFile(entity); if (childSearch != null) { diff --git a/packages/flutter/test/widgets/semantics_traversal_test.dart b/packages/flutter/test/widgets/semantics_traversal_test.dart index 9e4578bee9e..b7ee4d06d7d 100644 --- a/packages/flutter/test/widgets/semantics_traversal_test.dart +++ b/packages/flutter/test/widgets/semantics_traversal_test.dart @@ -66,7 +66,7 @@ void main() { // │ B │ // └───┘ testTraversal('Semantics traverses vertically top-to-bottom', (TraversalTester tester) async { - for (TextDirection textDirection in TextDirection.values) { + for (final TextDirection textDirection in TextDirection.values) { await tester.test( textDirection: textDirection, children: { diff --git a/packages/flutter/test/widgets/shadow_test.dart b/packages/flutter/test/widgets/shadow_test.dart index f95f7537ac0..95a1ca97ecc 100644 --- a/packages/flutter/test/widgets/shadow_test.dart +++ b/packages/flutter/test/widgets/shadow_test.dart @@ -56,7 +56,7 @@ void main() { ), ); } - for (int elevation in kElevationToShadow.keys) { + for (final int elevation in kElevationToShadow.keys) { await tester.pumpWidget(build(elevation)); await expectLater( find.byType(Container), @@ -120,7 +120,7 @@ void main() { ), ); } - for (int elevation in kElevationToShadow.keys) { + for (final int elevation in kElevationToShadow.keys) { await tester.pumpWidget(build(elevation.toDouble())); await expectLater( find.byType(Container), diff --git a/packages/flutter/test/widgets/widget_inspector_test.dart b/packages/flutter/test/widgets/widget_inspector_test.dart index 638757ddcbd..70c18dcc436 100644 --- a/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/packages/flutter/test/widgets/widget_inspector_test.dart @@ -1260,7 +1260,7 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { final List propertiesJson = childJson['properties'] as List; final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId'] as String) as DiagnosticsNode; final List expectedProperties = diagnosticsNode.getProperties(); - for (Map propertyJson in propertiesJson.cast>()) { + for (final Map propertyJson in propertiesJson.cast>()) { final Object property = service.toObject(propertyJson['objectId'] as String); expect(property, isInstanceOf()); expect(expectedProperties, contains(property)); @@ -1296,12 +1296,12 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { expect(service.toObject(childJson['valueId'] as String), equals(children[i].value)); expect(service.toObject(childJson['objectId'] as String), isInstanceOf()); final List propertiesJson = childJson['properties'] as List; - for (Map propertyJson in propertiesJson.cast>()) { + for (final Map propertyJson in propertiesJson.cast>()) { expect(propertyJson, isNot(contains('children'))); } final DiagnosticsNode diagnosticsNode = service.toObject(childJson['objectId'] as String) as DiagnosticsNode; final List expectedProperties = diagnosticsNode.getProperties(); - for (Map propertyJson in propertiesJson.cast>()) { + for (final Map propertyJson in propertiesJson.cast>()) { final Object property = service.toObject(propertyJson['objectId'] as String); expect(property, isInstanceOf()); expect(expectedProperties, contains(property)); @@ -1313,9 +1313,9 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { {'arg': id, 'objectGroup': group, 'subtreeDepth': '3'}, ) as Map; final List deepChildrenJson = deepSubtreeJson['children'] as List; - for(Map childJson in deepChildrenJson.cast>()) { + for (final Map childJson in deepChildrenJson.cast>()) { final List propertiesJson = childJson['properties'] as List; - for (Map propertyJson in propertiesJson.cast>()) { + for (final Map propertyJson in propertiesJson.cast>()) { expect(propertyJson, contains('children')); } } @@ -2584,7 +2584,7 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { final List> appBars = >[]; void visitChildren(List children) { - for (Map child in children.cast>()) { + for (final Map child in children.cast>()) { if (child['description'] == 'AppBar') { appBars.add(child); } diff --git a/packages/flutter_driver/lib/src/common/wait.dart b/packages/flutter_driver/lib/src/common/wait.dart index d5ba23d4704..b8f5f0e0067 100644 --- a/packages/flutter_driver/lib/src/common/wait.dart +++ b/packages/flutter_driver/lib/src/common/wait.dart @@ -251,7 +251,7 @@ class CombinedCondition extends SerializableWaitCondition { } final List conditions = []; - for (Map condition in json.decode(jsonMap['conditions'])) { + for (final Map condition in json.decode(jsonMap['conditions'])) { conditions.add(_deserialize(condition.cast())); } return CombinedCondition(conditions); diff --git a/packages/flutter_driver/lib/src/driver/vmservice_driver.dart b/packages/flutter_driver/lib/src/driver/vmservice_driver.dart index 8db6af8a95b..2a421a076d2 100644 --- a/packages/flutter_driver/lib/src/driver/vmservice_driver.dart +++ b/packages/flutter_driver/lib/src/driver/vmservice_driver.dart @@ -416,7 +416,7 @@ class VMServiceFlutterDriver extends FlutterDriver { Future _isPrecompiledMode() async { final List> flags = await getVmFlags(); - for(Map flag in flags) { + for(final Map flag in flags) { if (flag['name'] == 'precompiled_mode') { return flag['valueAsString'] == 'true'; } diff --git a/packages/flutter_driver/lib/src/driver/web_driver.dart b/packages/flutter_driver/lib/src/driver/web_driver.dart index 9059ecf6d1f..ba772a38674 100644 --- a/packages/flutter_driver/lib/src/driver/web_driver.dart +++ b/packages/flutter_driver/lib/src/driver/web_driver.dart @@ -123,7 +123,7 @@ class WebFlutterDriver extends FlutterDriver { _checkBrowserSupportsTimeline(); final List> events = >[]; - for (sync_io.LogEntry entry in _connection.logs) { + for (final sync_io.LogEntry entry in _connection.logs) { if (_startTime.isBefore(entry.timestamp)) { final Map data = jsonDecode(entry.message)['message'] as Map; if (data['method'] == 'Tracing.dataCollected') { diff --git a/packages/flutter_driver/lib/src/extension/wait_conditions.dart b/packages/flutter_driver/lib/src/extension/wait_conditions.dart index 336d48ceda8..fa7dac00329 100644 --- a/packages/flutter_driver/lib/src/extension/wait_conditions.dart +++ b/packages/flutter_driver/lib/src/extension/wait_conditions.dart @@ -185,7 +185,7 @@ class _InternalCombinedCondition implements WaitCondition { @override Future wait() async { while (!condition) { - for (WaitCondition condition in conditions) { + for (final WaitCondition condition in conditions) { assert (condition != null); await condition.wait(); } diff --git a/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart b/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart index 77c4950641c..6e2c00f5275 100644 --- a/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart +++ b/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart @@ -47,7 +47,7 @@ void main() { List> rasterizeTimeSequenceInMillis(List sequence) { final List> result = >[]; int t = 0; - for (int duration in sequence) { + for (final int duration in sequence) { result.add(begin(t)); t += duration * 1000; result.add(end(t)); diff --git a/packages/flutter_goldens/lib/flutter_goldens.dart b/packages/flutter_goldens/lib/flutter_goldens.dart index 574ed7d2442..6ffe4a743b7 100644 --- a/packages/flutter_goldens/lib/flutter_goldens.dart +++ b/packages/flutter_goldens/lib/flutter_goldens.dart @@ -506,7 +506,7 @@ class FlutterLocalFileComparator extends FlutterGoldenFileComparator with LocalC ComparisonResult result; final Map failureDiffs = {}; - for (String expectation in testExpectations) { + for (final String expectation in testExpectations) { final List goldenBytes = await skiaClient.getImageBytes(expectation); result = GoldenFileComparator.compareLists( @@ -520,7 +520,7 @@ class FlutterLocalFileComparator extends FlutterGoldenFileComparator with LocalC failureDiffs[expectation] = result; } - for (MapEntry entry in failureDiffs.entries) { + for (final MapEntry entry in failureDiffs.entries) { if (await skiaClient.isValidDigestForExpectation(entry.key, golden.path)) generateFailureOutput(entry.value, golden, basedir, key: entry.key); } diff --git a/packages/flutter_localizations/test/cupertino/translations_test.dart b/packages/flutter_localizations/test/cupertino/translations_test.dart index 81c18274c55..d13974eb2cf 100644 --- a/packages/flutter_localizations/test/cupertino/translations_test.dart +++ b/packages/flutter_localizations/test/cupertino/translations_test.dart @@ -7,7 +7,7 @@ import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - for (String language in kCupertinoSupportedLanguages) { + for (final String language in kCupertinoSupportedLanguages) { testWidgets('translations exist for $language', (WidgetTester tester) async { final Locale locale = Locale(language); diff --git a/packages/flutter_localizations/test/material/date_picker_test.dart b/packages/flutter_localizations/test/material/date_picker_test.dart index 99d8074d395..3563f174555 100644 --- a/packages/flutter_localizations/test/material/date_picker_test.dart +++ b/packages/flutter_localizations/test/material/date_picker_test.dart @@ -51,7 +51,7 @@ void main() { }, }; - for (Locale locale in testLocales.keys) { + for (final Locale locale in testLocales.keys) { testWidgets('shows dates for $locale', (WidgetTester tester) async { final List expectedDaysOfWeek = testLocales[locale]['expectedDaysOfWeek'] as List; final List expectedDaysOfMonth = testLocales[locale]['expectedDaysOfMonth'] as List; @@ -70,12 +70,12 @@ void main() { expect(find.text(expectedMonthYearHeader), findsOneWidget); - for (String dayOfWeek in expectedDaysOfWeek) { + for (final String dayOfWeek in expectedDaysOfWeek) { expect(find.text(dayOfWeek), findsWidgets); } Offset previousCellOffset; - for (String dayOfMonth in expectedDaysOfMonth) { + for (final String dayOfMonth in expectedDaysOfMonth) { final Finder dayCell = find.descendant(of: find.byType(GridView), matching: find.text(dayOfMonth)); expect(dayCell, findsOneWidget); diff --git a/packages/flutter_localizations/test/material/time_picker_test.dart b/packages/flutter_localizations/test/material/time_picker_test.dart index a4bbc7dcd82..597e2412f96 100644 --- a/packages/flutter_localizations/test/material/time_picker_test.dart +++ b/packages/flutter_localizations/test/material/time_picker_test.dart @@ -68,7 +68,7 @@ void main() { const Locale('zh', 'ZH'): const ['period', 'hour', 'string :', 'minute'], //'ah:mm' }; - for (Locale locale in locales.keys) { + for (final Locale locale in locales.keys) { final Offset center = await startPicker(tester, (TimeOfDay time) { }, locale: locale); final List actual = []; tester.element(find.byType(CustomMultiChildLayout)).visitChildren((Element child) { @@ -114,7 +114,7 @@ void main() { Locale('en', 'GB'), // HH Locale('es', 'ES'), // H ]; - for (Locale locale in locales) { + for (final Locale locale in locales) { // Tap along the segment stretching from the center to the edge at // 12:00 AM position. There are two rings. At ~70% mark, the ring // switches between inner ring and outer ring. diff --git a/packages/flutter_localizations/test/material/translations_test.dart b/packages/flutter_localizations/test/material/translations_test.dart index 782131b6239..fa2c9468e99 100644 --- a/packages/flutter_localizations/test/material/translations_test.dart +++ b/packages/flutter_localizations/test/material/translations_test.dart @@ -7,7 +7,7 @@ import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - for (String language in kMaterialSupportedLanguages) { + for (final String language in kMaterialSupportedLanguages) { testWidgets('translations exist for $language', (WidgetTester tester) async { final Locale locale = Locale(language); diff --git a/packages/flutter_test/lib/src/accessibility.dart b/packages/flutter_test/lib/src/accessibility.dart index 12c617ca4ef..2af0d543f3b 100644 --- a/packages/flutter_test/lib/src/accessibility.dart +++ b/packages/flutter_test/lib/src/accessibility.dart @@ -215,7 +215,7 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline { children.add(child); return true; }); - for (SemanticsNode child in children) { + for (final SemanticsNode child in children) { result += await evaluateNode(child); } if (_shouldSkipNode(data)) { @@ -348,7 +348,7 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline { class _ContrastReport { factory _ContrastReport(List colors) { final Map colorHistogram = {}; - for (int color in colors) { + for (final int color in colors) { colorHistogram[color] = (colorHistogram[color] ?? 0) + 1; } if (colorHistogram.length == 1) { @@ -358,7 +358,7 @@ class _ContrastReport { // to determine the lighter and darker color, partition the colors // by lightness and then choose the mode from each group. double averageLightness = 0.0; - for (int color in colorHistogram.keys) { + for (final int color in colorHistogram.keys) { final HSLColor hslColor = HSLColor.fromColor(Color(color)); averageLightness += hslColor.lightness * colorHistogram[color]; } @@ -369,7 +369,7 @@ class _ContrastReport { int lightCount = 0; int darkCount = 0; // Find the most frequently occurring light and dark color. - for (MapEntry entry in colorHistogram.entries) { + for (final MapEntry entry in colorHistogram.entries) { final HSLColor color = HSLColor.fromColor(Color(entry.key)); final int count = entry.value; if (color.lightness <= averageLightness && count > darkCount) { diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index 32c91c085ec..fbdfab562c2 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -1119,7 +1119,7 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { } debugPrint('Pending timers:'); - for (String timerInfo in _currentFakeAsync.pendingTimersDebugInfo) { + for (final String timerInfo in _currentFakeAsync.pendingTimersDebugInfo) { final int firstLineEnd = timerInfo.indexOf('\n'); assert(firstLineEnd != -1); @@ -1657,7 +1657,7 @@ class _LiveTestRenderView extends RenderView { ..strokeWidth = radius / 10.0 ..style = PaintingStyle.stroke; bool dirty = false; - for (int pointer in _pointers.keys) { + for (final int pointer in _pointers.keys) { final _LiveTestPointerRecord record = _pointers[pointer]; paint.color = record.color.withOpacity(record.decay < 0 ? (record.decay / (_kPointerDecay - 1)) : 1.0); canvas.drawPath(path.shift(record.position), paint); diff --git a/packages/flutter_test/lib/src/event_simulation.dart b/packages/flutter_test/lib/src/event_simulation.dart index 63b62f41726..11cdaea68ec 100644 --- a/packages/flutter_test/lib/src/event_simulation.dart +++ b/packages/flutter_test/lib/src/event_simulation.dart @@ -57,7 +57,7 @@ class KeyEventSimulator { map = kLinuxToPhysicalKey; break; } - for (int code in map.keys) { + for (final int code in map.keys) { if (key.debugName == map[code].debugName) { scanCode = code; break; @@ -84,7 +84,7 @@ class KeyEventSimulator { map = kGlfwToLogicalKey; break; } - for (int code in map.keys) { + for (final int code in map.keys) { if (key.debugName == map[code].debugName) { keyCode = code; break; diff --git a/packages/flutter_test/lib/src/finders.dart b/packages/flutter_test/lib/src/finders.dart index d6d8de60a57..a95c3af2e18 100644 --- a/packages/flutter_test/lib/src/finders.dart +++ b/packages/flutter_test/lib/src/finders.dart @@ -719,7 +719,7 @@ class _AncestorFinder extends Finder { @override Iterable get allCandidates { final List candidates = []; - for (Element root in descendant.evaluate()) { + for (final Element root in descendant.evaluate()) { final List ancestors = []; if (matchRoot) ancestors.add(root); diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart index 866e3d08a06..529774ba835 100644 --- a/packages/flutter_test/lib/src/matchers.dart +++ b/packages/flutter_test/lib/src/matchers.dart @@ -1184,7 +1184,7 @@ class _IsMethodCall extends Matcher { bool _deepEqualsMap(Map a, Map b) { if (a.length != b.length) return false; - for (dynamic key in a.keys) { + for (final dynamic key in a.keys) { if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) return false; } @@ -1782,7 +1782,7 @@ class _MatchesSemanticsData extends Matcher { description.add(' with custom hints: $hintOverrides'); if (children != null) { description.add(' with children:\n'); - for (_MatchesSemanticsData child in children.cast<_MatchesSemanticsData>()) + for (final _MatchesSemanticsData child in children.cast<_MatchesSemanticsData>()) child.describe(description); } return description; @@ -1824,11 +1824,11 @@ class _MatchesSemanticsData extends Matcher { return failWithDescription(matchState, 'maxValueLength was: ${data.maxValueLength}'); if (actions != null) { int actionBits = 0; - for (SemanticsAction action in actions) + for (final SemanticsAction action in actions) actionBits |= action.index; if (actionBits != data.actions) { final List actionSummary = [ - for (SemanticsAction action in SemanticsAction.values.values) + for (final SemanticsAction action in SemanticsAction.values.values) if ((data.actions & action.index) != 0) describeEnum(action), ]; @@ -1858,11 +1858,11 @@ class _MatchesSemanticsData extends Matcher { } if (flags != null) { int flagBits = 0; - for (SemanticsFlag flag in flags) + for (final SemanticsFlag flag in flags) flagBits |= flag.index; if (flagBits != data.flags) { final List flagSummary = [ - for (SemanticsFlag flag in SemanticsFlag.values.values) + for (final SemanticsFlag flag in SemanticsFlag.values.values) if ((data.flags & flag.index) != 0) describeEnum(flag), ]; diff --git a/packages/flutter_test/lib/src/test_async_utils.dart b/packages/flutter_test/lib/src/test_async_utils.dart index 9c507331474..9f8100e179b 100644 --- a/packages/flutter_test/lib/src/test_async_utils.dart +++ b/packages/flutter_test/lib/src/test_async_utils.dart @@ -274,7 +274,7 @@ class TestAsyncUtils { ErrorSummary('Asynchronous call to guarded function leaked.'), ErrorHint('You must use "await" with all Future-returning test APIs.') ]; - for (_AsyncScope scope in _scopeStack) { + for (final _AsyncScope scope in _scopeStack) { final _StackEntry guarder = _findResponsibleMethod(scope.creationStack, 'guard', information); if (guarder != null) { information.add(ErrorDescription( diff --git a/packages/flutter_test/lib/src/test_compat.dart b/packages/flutter_test/lib/src/test_compat.dart index c4f5496a340..f157a370d70 100644 --- a/packages/flutter_test/lib/src/test_compat.dart +++ b/packages/flutter_test/lib/src/test_compat.dart @@ -54,7 +54,7 @@ Future _runGroup(Suite suiteConfig, Group group, List parents, _Rep setUpAllSucceeded = liveTest.state.result.isPassing; } if (setUpAllSucceeded) { - for (GroupEntry entry in group.entries) { + for (final GroupEntry entry in group.entries) { if (entry is Group) { await _runGroup(suiteConfig, entry, parents, reporter); } else if (entry.metadata.skip) { @@ -502,7 +502,7 @@ String _prefixLines(String text, String prefix, { String first, String last, Str } final StringBuffer buffer = StringBuffer('$first${lines.first}\n'); // Write out all but the first and last lines with [prefix]. - for (String line in lines.skip(1).take(lines.length - 2)) { + for (final String line in lines.skip(1).take(lines.length - 2)) { buffer.writeln('$prefix$line'); } buffer.write('$last${lines.last}'); diff --git a/packages/flutter_test/lib/src/widget_tester.dart b/packages/flutter_test/lib/src/widget_tester.dart index 49760cf2c89..afac83bdb83 100644 --- a/packages/flutter_test/lib/src/widget_tester.dart +++ b/packages/flutter_test/lib/src/widget_tester.dart @@ -117,7 +117,7 @@ void testWidgets( assert(variant.values.isNotEmpty, 'There must be at least on value to test in the testing variant'); final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as TestWidgetsFlutterBinding; final WidgetTester tester = WidgetTester._(binding); - for (dynamic value in variant.values) { + for (final dynamic value in variant.values) { final String variationDescription = variant.describeValue(value); final String combinedDescription = variationDescription.isNotEmpty ? '$description ($variationDescription)' : description; test( @@ -629,7 +629,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker int numberOfTypes = 0; int totalNumber = 0; debugPrint('Some possible finders for the widgets at ${binding.globalToLocal(event.position)}:'); - for (Element element in candidates) { + for (final Element element in candidates) { if (totalNumber > 13) // an arbitrary number of finders that feels useful without being overwhelming break; totalNumber += 1; // optimistically assume we'll be able to describe it @@ -755,7 +755,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker void verifyTickersWereDisposed([ String when = 'when none should have been' ]) { assert(when != null); if (_tickers != null) { - for (Ticker ticker in _tickers) { + for (final Ticker ticker in _tickers) { if (ticker.isActive) { throw FlutterError.fromParts([ ErrorSummary('A Ticker was active $when.'), diff --git a/packages/flutter_test/test/event_simulation_test.dart b/packages/flutter_test/test/event_simulation_test.dart index f4d74ad221c..91fefce391a 100644 --- a/packages/flutter_test/test/event_simulation_test.dart +++ b/packages/flutter_test/test/event_simulation_test.dart @@ -25,7 +25,7 @@ void main() { focusNode.requestFocus(); await tester.idle(); - for (String platform in platforms) { + for (final String platform in platforms) { await tester.sendKeyEvent(LogicalKeyboardKey.shiftLeft, platform: platform); await tester.sendKeyEvent(LogicalKeyboardKey.shift, platform: platform); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform); diff --git a/packages/flutter_test/test/matchers_test.dart b/packages/flutter_test/test/matchers_test.dart index ecd0f18b3e7..79af0619813 100644 --- a/packages/flutter_test/test/matchers_test.dart +++ b/packages/flutter_test/test/matchers_test.dart @@ -530,9 +530,9 @@ void main() { int actions = 0; int flags = 0; const CustomSemanticsAction action = CustomSemanticsAction(label: 'test'); - for (int index in SemanticsAction.values.keys) + for (final int index in SemanticsAction.values.keys) actions |= index; - for (int index in SemanticsFlag.values.keys) + for (final int index in SemanticsFlag.values.keys) // TODO(mdebbar): Remove this if after https://github.com/flutter/engine/pull/9894 if (SemanticsFlag.values[index] != SemanticsFlag.isMultiline) flags |= index; diff --git a/packages/flutter_test/test/test_config/config_test_utils.dart b/packages/flutter_test/test/test_config/config_test_utils.dart index 31d2c3e2c74..a7397a81166 100644 --- a/packages/flutter_test/test/test_config/config_test_utils.dart +++ b/packages/flutter_test/test/test_config/config_test_utils.dart @@ -20,7 +20,7 @@ void testConfig( test(description, () { expect(actualStringValue, expectedStringValue); - for (Type key in otherExpectedValues.keys) { + for (final Type key in otherExpectedValues.keys) { expect(otherActualValues[key], otherExpectedValues[key]); } }); diff --git a/packages/flutter_tools/bin/fuchsia_asset_builder.dart b/packages/flutter_tools/bin/fuchsia_asset_builder.dart index 5e980aa3339..dd75c654bbc 100644 --- a/packages/flutter_tools/bin/fuchsia_asset_builder.dart +++ b/packages/flutter_tools/bin/fuchsia_asset_builder.dart @@ -86,7 +86,7 @@ Future writeFuchsiaManifest(AssetBundle assets, String outputBase, String await destFile.create(recursive: true); final libfs.IOSink outFile = destFile.openWrite(); - for (String path in assets.entries.keys) { + for (final String path in assets.entries.keys) { outFile.write('data/$componentName/$path=$outputBase/$path\n'); } await outFile.flush(); diff --git a/packages/flutter_tools/bin/fuchsia_tester.dart b/packages/flutter_tools/bin/fuchsia_tester.dart index b23d98022e1..0e60a9619e6 100644 --- a/packages/flutter_tools/bin/fuchsia_tester.dart +++ b/packages/flutter_tools/bin/fuchsia_tester.dart @@ -105,7 +105,7 @@ Future run(List args) async { final Directory sdkRootDest = globals.fs.directory(globals.artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath)); sdkRootDest.createSync(recursive: true); - for (FileSystemEntity artifact in sdkRootSrc.listSync()) { + for (final FileSystemEntity artifact in sdkRootSrc.listSync()) { globals.fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path); } // TODO(tvolkert): Remove once flutter_tester no longer looks for this. @@ -136,7 +136,7 @@ Future run(List args) async { final Map tests = {}; final List> jsonList = List>.from( (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List).cast>()); - for (Map map in jsonList) { + for (final Map map in jsonList) { final String source = globals.fs.file(map['source']).resolveSymbolicLinksSync(); final String dill = globals.fs.file(map['dill']).resolveSymbolicLinksSync(); tests[source] = dill; diff --git a/packages/flutter_tools/lib/src/android/android_builder.dart b/packages/flutter_tools/lib/src/android/android_builder.dart index 17b5d5dc6c7..40ddbd65633 100644 --- a/packages/flutter_tools/lib/src/android/android_builder.dart +++ b/packages/flutter_tools/lib/src/android/android_builder.dart @@ -68,7 +68,7 @@ class _AndroidBuilderImpl extends AndroidBuilder { // Module projects artifacts are located in `build/host`. outputDirectory = outputDirectory.childDirectory('host'); } - for (AndroidBuildInfo androidBuildInfo in androidBuildInfo) { + for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { await buildGradleAar( project: project, androidBuildInfo: androidBuildInfo, diff --git a/packages/flutter_tools/lib/src/android/android_device.dart b/packages/flutter_tools/lib/src/android/android_device.dart index 3b8d6b58bdf..384e3b09eb0 100644 --- a/packages/flutter_tools/lib/src/android/android_device.dart +++ b/packages/flutter_tools/lib/src/android/android_device.dart @@ -732,7 +732,7 @@ class AndroidDevice extends Device { Map parseAdbDeviceProperties(String str) { final Map properties = {}; final RegExp propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]'); - for (Match match in propertyExp.allMatches(str)) { + for (final Match match in propertyExp.allMatches(str)) { properties[match.group(1)] = match.group(2); } return properties; @@ -932,7 +932,7 @@ void parseADBDeviceOutput( return; } - for (String line in text.trim().split('\n')) { + for (final String line in text.trim().split('\n')) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) { continue; @@ -958,7 +958,7 @@ void parseADBDeviceOutput( final Map info = {}; if (rest != null && rest.isNotEmpty) { rest = rest.trim(); - for (String data in rest.split(' ')) { + for (final String data in rest.split(' ')) { if (data.contains(':')) { final List fields = data.split(':'); info[fields[0]] = fields[1]; @@ -1165,7 +1165,7 @@ class _AndroidDevicePortForwarder extends DevicePortForwarder { } final List lines = LineSplitter.split(stdout).toList(); - for (String line in lines) { + for (final String line in lines) { if (!line.startsWith(device.id)) { continue; } @@ -1260,7 +1260,7 @@ class _AndroidDevicePortForwarder extends DevicePortForwarder { @override Future dispose() async { - for (ForwardedPort port in forwardedPorts) { + for (final ForwardedPort port in forwardedPorts) { await unforward(port); } } diff --git a/packages/flutter_tools/lib/src/android/android_emulator.dart b/packages/flutter_tools/lib/src/android/android_emulator.dart index 5a7a04eb292..b7c0557d200 100644 --- a/packages/flutter_tools/lib/src/android/android_emulator.dart +++ b/packages/flutter_tools/lib/src/android/android_emulator.dart @@ -85,7 +85,7 @@ List getEmulatorAvds() { /// Parse the given `emulator -list-avds` output in [text], and fill out the given list /// of emulators by reading information from the relevant ini files. void extractEmulatorAvdInfo(String text, List emulators) { - for (String id in text.trim().split('\n').where((String l) => l != '')) { + for (final String id in text.trim().split('\n').where((String l) => l != '')) { emulators.add(_loadEmulatorInfo(id)); } } @@ -125,7 +125,7 @@ Map parseIniLines(List contents) { // Split into name/value .map>((String l) => l.split('=')); - for (List property in properties) { + for (final List property in properties) { results[property[0].trim()] = property[1].trim(); } diff --git a/packages/flutter_tools/lib/src/android/android_sdk.dart b/packages/flutter_tools/lib/src/android/android_sdk.dart index 7c4ab747cf0..50fc605fee3 100644 --- a/packages/flutter_tools/lib/src/android/android_sdk.dart +++ b/packages/flutter_tools/lib/src/android/android_sdk.dart @@ -215,7 +215,7 @@ class AndroidNdk { .map((String line) => line.trim()) .where((String line) => line.isNotEmpty); final Map properties = {}; - for (String line in propertiesFileLines) { + for (final String line in propertiesFileLines) { final List parts = line.split(' = '); if (parts.length == 2) { properties[parts[0]] = parts[1]; diff --git a/packages/flutter_tools/lib/src/android/android_studio.dart b/packages/flutter_tools/lib/src/android/android_studio.dart index 32014e265f4..f7ebfb42877 100644 --- a/packages/flutter_tools/lib/src/android/android_studio.dart +++ b/packages/flutter_tools/lib/src/android/android_studio.dart @@ -183,7 +183,7 @@ class AndroidStudio implements Comparable { .directory(path) .listSync(followLinks: false) .whereType(); - for (Directory directory in directories) { + for (final Directory directory in directories) { final String name = directory.basename; // An exact match, or something like 'Android Studio 3.0 Preview.app'. if (name.startsWith('Android Studio') && name.endsWith('.app')) { @@ -236,7 +236,7 @@ class AndroidStudio implements Comparable { // Read all $HOME/.AndroidStudio*/system/.home files. There may be several // pointing to the same installation, so we grab only the latest one. if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) { - for (FileSystemEntity entity in globals.fs.directory(homeDirPath).listSync(followLinks: false)) { + for (final FileSystemEntity entity in globals.fs.directory(homeDirPath).listSync(followLinks: false)) { if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) { final AndroidStudio studio = AndroidStudio.fromHomeDot(entity); if (studio != null && !_hasStudioAt(studio.directory, newerThan: studio.version)) { diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index 676599a8fd6..82364a1595f 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -116,7 +116,7 @@ bool _isSupportedVersion(AndroidProject project) { if (!appGradle.existsSync()) { return false; } - for (String line in appGradle.readAsLinesSync()) { + for (final String line in appGradle.readAsLinesSync()) { if (line.contains(RegExp(r'apply from: .*/flutter.gradle')) || line.contains("def flutterPluginVersion = 'managed'")) { return true; @@ -184,7 +184,7 @@ void createSettingsAarGradle(Directory androidDirectory) { existingVariants.add(settingsAarContent); bool exactMatch = false; - for (String fileContentVariant in existingVariants) { + for (final String fileContentVariant in existingVariants) { if (currentFileContent.trim() == fileContentVariant.trim()) { exactMatch = true; break; @@ -465,7 +465,7 @@ Future buildGradleApp({ final File apkShaFile = apkDirectory.childFile('app.apk.sha1'); apkShaFile.writeAsStringSync(_calculateSha(apkFiles.first)); - for (File apkFile in apkFiles) { + for (final File apkFile in apkFiles) { final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsMB(apkFile.lengthSync())})'; @@ -618,7 +618,7 @@ ${globals.terminal.bolden('Consuming the Module')} dependencies {'''); - for (String buildMode in buildModes) { + for (final String buildMode in buildModes) { globals.printStatus(''' ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'''); } @@ -647,7 +647,7 @@ ${globals.terminal.bolden('Consuming the Module')} String _hex(List bytes) { final StringBuffer result = StringBuffer(); - for (int part in bytes) { + for (final int part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); } return result.toString(); @@ -707,7 +707,7 @@ Future buildPluginsAsAar( return; } final List plugins = flutterPluginFile.readAsStringSync().split('\n'); - for (String plugin in plugins) { + for (final String plugin in plugins) { final List pluginParts = plugin.split('='); if (pluginParts.length != 2) { continue; @@ -882,7 +882,7 @@ String _getLocalArtifactVersion(String pomPath) { } final Iterable project = document.findElements('project'); assert(project.isNotEmpty); - for (xml.XmlElement versionElement in document.findAllElements('version')) { + for (final xml.XmlElement versionElement in document.findAllElements('version')) { if (versionElement.parent == project.first) { return versionElement.text; } @@ -919,7 +919,7 @@ Directory _getLocalEngineRepo({ 'flutter_embedding_$buildMode.pom', ) ); - for (String artifact in const ['pom', 'jar']) { + for (final String artifact in const ['pom', 'jar']) { // The Android embedding artifacts. _createSymlink( globals.fs.path.join( diff --git a/packages/flutter_tools/lib/src/android/gradle_errors.dart b/packages/flutter_tools/lib/src/android/gradle_errors.dart index be2c00aa1df..9d5e63ba4e1 100644 --- a/packages/flutter_tools/lib/src/android/gradle_errors.dart +++ b/packages/flutter_tools/lib/src/android/gradle_errors.dart @@ -283,7 +283,7 @@ final GradleHandledError flavorUndefinedHandler = GradleHandledError( ); // Extract build types and product flavors. final Set variants = {}; - for (String task in tasksRunResult.stdout.split('\n')) { + for (final String task in tasksRunResult.stdout.split('\n')) { final Match match = _assembleTaskPattern.matchAsPrefix(task); if (match != null) { final String variant = match.group(1).toLowerCase(); diff --git a/packages/flutter_tools/lib/src/aot.dart b/packages/flutter_tools/lib/src/aot.dart index bbf4c0e96b6..976eb09d228 100644 --- a/packages/flutter_tools/lib/src/aot.dart +++ b/packages/flutter_tools/lib/src/aot.dart @@ -89,7 +89,7 @@ class AotBuilder { if (platform == TargetPlatform.ios) { // Determine which iOS architectures to build for. final Map iosBuilds = {}; - for (DarwinArch arch in iosBuildArchs) { + for (final DarwinArch arch in iosBuildArchs) { iosBuilds[arch] = globals.fs.path.join(outputPath, getNameForDarwinArch(arch)); } @@ -224,7 +224,7 @@ class AotBuilder { )); status?.stop(); if (!result.success) { - for (ExceptionMeasurement measurement in result.exceptions.values) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart index 27625a3d26f..034f02d2fda 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart @@ -213,16 +213,16 @@ class AndroidApk extends ApplicationPackage { final String packageId = manifests.first.getAttribute('package'); String launchActivity; - for (xml.XmlElement activity in document.findAllElements('activity')) { + for (final xml.XmlElement activity in document.findAllElements('activity')) { final String enabled = activity.getAttribute('android:enabled'); if (enabled != null && enabled == 'false') { continue; } - for (xml.XmlElement element in activity.findElements('intent-filter')) { + for (final xml.XmlElement element in activity.findElements('intent-filter')) { String actionName = ''; String categoryName = ''; - for (xml.XmlNode node in element.children) { + for (final xml.XmlNode node in element.children) { if (node is! xml.XmlElement) { continue; } @@ -511,7 +511,7 @@ class ApkManifestData { static bool isAttributeWithValuePresent(_Element baseElement, String childElement, String attributeName, String attributeValue) { final Iterable<_Element> allElements = baseElement.allElements(childElement); - for (_Element oneElement in allElements) { + for (final _Element oneElement in allElements) { final String elementAttributeValue = oneElement ?.firstAttribute(attributeName) ?.value; @@ -535,7 +535,7 @@ class ApkManifestData { final _Element manifest = _Element.fromLine(lines[manifestLine], null); _Element currentElement = manifest; - for (String line in lines.skip(manifestLine)) { + for (final String line in lines.skip(manifestLine)) { final String trimLine = line.trimLeft(); final int level = line.length - trimLine.length; @@ -564,7 +564,7 @@ class ApkManifestData { final Iterable<_Element> activities = application.allElements('activity'); _Element launchActivity; - for (_Element activity in activities) { + for (final _Element activity in activities) { final _Attribute enabled = activity.firstAttribute('android:enabled'); final Iterable<_Element> intentFilters = activity.allElements('intent-filter'); final bool isEnabledByDefault = enabled == null; @@ -573,7 +573,7 @@ class ApkManifestData { continue; } - for (_Element element in intentFilters) { + for (final _Element element in intentFilters) { final bool isMainAction = isAttributeWithValuePresent( element, 'action', 'android:name', '"android.intent.action.MAIN"'); if (!isMainAction) { diff --git a/packages/flutter_tools/lib/src/artifacts.dart b/packages/flutter_tools/lib/src/artifacts.dart index 60f6ef697ac..e9d7c46172c 100644 --- a/packages/flutter_tools/lib/src/artifacts.dart +++ b/packages/flutter_tools/lib/src/artifacts.dart @@ -509,7 +509,7 @@ class LocalEngineArtifacts extends Artifacts { String _genSnapshotPath() { const List clangDirs = ['.', 'clang_x64', 'clang_x86', 'clang_i386']; final String genSnapshotName = _artifactToFileName(Artifact.genSnapshot); - for (String clangDir in clangDirs) { + for (final String clangDir in clangDirs) { final String genSnapshotPath = globals.fs.path.join(engineOutPath, clangDir, genSnapshotName); if (globals.processManager.canRun(genSnapshotPath)) { return genSnapshotPath; diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart index 3c151c949fb..d1a47064a81 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart @@ -89,11 +89,11 @@ class _ManifestAssetBundle implements AssetBundle { return true; } - for (Directory directory in _wildcardDirectories.values) { + for (final Directory directory in _wildcardDirectories.values) { if (!directory.existsSync()) { return true; // directory was deleted. } - for (File file in directory.listSync().whereType()) { + for (final File file in directory.listSync().whereType()) { final DateTime dateTime = file.statSync().modified; if (dateTime == null) { continue; @@ -166,7 +166,7 @@ class _ManifestAssetBundle implements AssetBundle { ); // Add fonts and assets from packages. - for (String packageName in packageMap.map.keys) { + for (final String packageName in packageMap.map.keys) { final Uri package = packageMap.map[packageName]; if (package != null && package.scheme == 'file') { final String packageManifestPath = globals.fs.path.fromUri(package.resolve('../pubspec.yaml')); @@ -204,7 +204,7 @@ class _ManifestAssetBundle implements AssetBundle { // Save the contents of each image, image variant, and font // asset in entries. - for (_Asset asset in assetVariants.keys) { + for (final _Asset asset in assetVariants.keys) { if (!asset.assetFileExists && assetVariants[asset].isEmpty) { globals.printStatus('Error detected in pubspec.yaml:', emphasis: true); globals.printError('No file or variants found for $asset.\n'); @@ -220,7 +220,7 @@ class _ManifestAssetBundle implements AssetBundle { assert(!assetVariants[asset].contains(asset)); assetVariants[asset].insert(0, asset); } - for (_Asset variant in assetVariants[asset]) { + for (final _Asset variant in assetVariants[asset]) { assert(variant.assetFileExists); entries[variant.entryUri.path] ??= DevFSFileContent(variant.assetFile); } @@ -230,13 +230,13 @@ class _ManifestAssetBundle implements AssetBundle { if (flutterManifest.usesMaterialDesign && includeDefaultFonts) ..._getMaterialAssets(_fontSetMaterial), ]; - for (_Asset asset in materialAssets) { + for (final _Asset asset in materialAssets) { assert(asset.assetFileExists); entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile); } // Update wildcard directories we we can detect changes in them. - for (Uri uri in wildcardDirectories) { + for (final Uri uri in wildcardDirectories) { _wildcardDirectories[uri] ??= globals.fs.directory(uri); } @@ -321,8 +321,8 @@ List> _getMaterialFonts(String fontSet) { List<_Asset> _getMaterialAssets(String fontSet) { final List<_Asset> result = <_Asset>[]; - for (Map family in _getMaterialFonts(fontSet)) { - for (Map font in family['fonts']) { + for (final Map family in _getMaterialFonts(fontSet)) { + for (final Map font in family['fonts']) { final Uri entryUri = globals.fs.path.toUri(font['asset'] as String); result.add(_Asset( baseDir: globals.fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'), @@ -358,7 +358,7 @@ DevFSContent _obtainLicenses( // sources, and might need to include a license for each one.) final Map> packageLicenses = >{}; final Set allPackages = {}; - for (String packageName in packageMap.map.keys) { + for (final String packageName in packageMap.map.keys) { final Uri package = packageMap.map[packageName]; if (package == null || package.scheme != 'file') { continue; @@ -369,7 +369,7 @@ DevFSContent _obtainLicenses( } final List rawLicenses = file.readAsStringSync().split(_licenseSeparator); - for (String rawLicense in rawLicenses) { + for (final String rawLicense in rawLicenses) { List packageNames; String licenseText; if (rawLicenses.length > 1) { @@ -421,9 +421,9 @@ DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) { .keys.toList() ..sort(_byBasename); - for (_Asset main in sortedKeys) { + for (final _Asset main in sortedKeys) { jsonObject[main.entryUri.path] = [ - for (_Asset variant in assetVariants[main]) + for (final _Asset variant in assetVariants[main]) variant.entryUri.path, ]; } @@ -458,9 +458,9 @@ List _parsePackageFonts( PackageMap packageMap, ) { final List packageFonts = []; - for (Font font in manifest.fonts) { + for (final Font font in manifest.fonts) { final List packageFontAssets = []; - for (FontAsset fontAsset in font.fontAssets) { + for (final FontAsset fontAsset in font.fontAssets) { final Uri assetUri = fontAsset.assetUri; if (assetUri.pathSegments.first == 'packages' && !globals.fs.isFileSync(globals.fs.path.fromUri(packageMap.map[packageName].resolve('../${assetUri.path}')))) { @@ -513,7 +513,7 @@ class _AssetDirectoryCache { if (_cache[directory] == null) { final List paths = []; - for (FileSystemEntity entity in globals.fs.directory(directory).listSync(recursive: true)) { + for (final FileSystemEntity entity in globals.fs.directory(directory).listSync(recursive: true)) { final String path = entity.path; if (globals.fs.isFileSync(path) && !_excluded.any((String exclude) => path.startsWith(exclude))) { paths.add(path); @@ -521,7 +521,7 @@ class _AssetDirectoryCache { } final Map> variants = >{}; - for (String path in paths) { + for (final String path in paths) { final String variantName = globals.fs.path.basename(path); if (directory == globals.fs.path.dirname(path)) { continue; @@ -572,7 +572,7 @@ Map<_Asset, List<_Asset>> _parseAssets( final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{}; final _AssetDirectoryCache cache = _AssetDirectoryCache(excludeDirs); - for (Uri assetUri in flutterManifest.assets) { + for (final Uri assetUri in flutterManifest.assets) { if (assetUri.toString().endsWith('/')) { wildcardDirectories.add(assetUri); _parseAssetsFromFolder(packageMap, flutterManifest, assetBase, @@ -586,8 +586,8 @@ Map<_Asset, List<_Asset>> _parseAssets( } // Add assets referenced in the fonts section of the manifest. - for (Font font in flutterManifest.fonts) { - for (FontAsset fontAsset in font.fontAssets) { + for (final Font font in flutterManifest.fonts) { + for (final FontAsset fontAsset in font.fontAssets) { final _Asset baseAsset = _resolveAsset( packageMap, assetBase, @@ -626,7 +626,7 @@ void _parseAssetsFromFolder( final List lister = globals.fs.directory(directoryPath).listSync(); - for (FileSystemEntity entity in lister) { + for (final FileSystemEntity entity in lister) { if (entity is File) { final String relativePath = globals.fs.path.relative(entity.path, from: assetBase); @@ -655,7 +655,7 @@ void _parseAssetFromFile( packageName, ); final List<_Asset> variants = <_Asset>[]; - for (String path in cache.variantsFor(asset.assetFile.path)) { + for (final String path in cache.variantsFor(asset.assetFile.path)) { final String relativePath = globals.fs.path.relative(path, from: asset.baseDir); final Uri relativeUri = globals.fs.path.toUri(relativePath); final Uri entryUri = asset.symbolicPrefixUri == null diff --git a/packages/flutter_tools/lib/src/base/build.dart b/packages/flutter_tools/lib/src/base/build.dart index 9d5c8fce23a..15e7bc9e625 100644 --- a/packages/flutter_tools/lib/src/base/build.dart +++ b/packages/flutter_tools/lib/src/base/build.dart @@ -185,7 +185,7 @@ class AOTSnapshotter { final bool stripSymbols = platform == TargetPlatform.ios && buildMode == BuildMode.release && bitcode; if (stripSymbols) { final IOSink sink = globals.fs.file('$assembly.stripped.S').openWrite(); - for (String line in globals.fs.file(assembly).readAsLinesSync()) { + for (final String line in globals.fs.file(assembly).readAsLinesSync()) { if (line.startsWith('.section __DWARF')) { break; } diff --git a/packages/flutter_tools/lib/src/base/file_system.dart b/packages/flutter_tools/lib/src/base/file_system.dart index 4100d778083..6e3ccce7b23 100644 --- a/packages/flutter_tools/lib/src/base/file_system.dart +++ b/packages/flutter_tools/lib/src/base/file_system.dart @@ -42,7 +42,7 @@ void copyDirectorySync( destDir.createSync(recursive: true); } - for (FileSystemEntity entity in srcDir.listSync()) { + for (final FileSystemEntity entity in srcDir.listSync()) { final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename); if (entity is File) { final File newFile = destDir.fileSystem.file(newPath); diff --git a/packages/flutter_tools/lib/src/base/fingerprint.dart b/packages/flutter_tools/lib/src/base/fingerprint.dart index 5fc0b2fb2d4..9ef80c7380f 100644 --- a/packages/flutter_tools/lib/src/base/fingerprint.dart +++ b/packages/flutter_tools/lib/src/base/fingerprint.dart @@ -87,7 +87,7 @@ class Fingerprinter { List _getPaths() { final Set paths = { ..._paths, - for (String depfilePath in _depfilePaths) + for (final String depfilePath in _depfilePaths) ...readDepfile(depfilePath), }; final FingerprintPathFilter filter = _pathFilter ?? (String path) => true; @@ -108,7 +108,7 @@ class Fingerprint { } _checksums = {}; - for (File file in files) { + for (final File file in files) { final List bytes = file.readAsBytesSync(); _checksums[file.path] = md5.convert(bytes).toString(); } diff --git a/packages/flutter_tools/lib/src/base/net.dart b/packages/flutter_tools/lib/src/base/net.dart index 150e1a100fe..38fa19ccf67 100644 --- a/packages/flutter_tools/lib/src/base/net.dart +++ b/packages/flutter_tools/lib/src/base/net.dart @@ -187,7 +187,7 @@ class _MemoryIOSink implements IOSink { @override void writeAll(Iterable objects, [ String separator = '' ]) { bool addSeparator = false; - for (dynamic object in objects) { + for (final dynamic object in objects) { if (addSeparator) { write(separator); } diff --git a/packages/flutter_tools/lib/src/base/os.dart b/packages/flutter_tools/lib/src/base/os.dart index f07c75839f4..b0cd1d4d53e 100644 --- a/packages/flutter_tools/lib/src/base/os.dart +++ b/packages/flutter_tools/lib/src/base/os.dart @@ -248,7 +248,7 @@ class _WindowsUtils extends OperatingSystemUtils { @override void zip(Directory data, File zipFile) { final Archive archive = Archive(); - for (FileSystemEntity entity in data.listSync(recursive: true)) { + for (final FileSystemEntity entity in data.listSync(recursive: true)) { if (entity is! File) { continue; } @@ -299,7 +299,7 @@ class _WindowsUtils extends OperatingSystemUtils { } void _unpackArchive(Archive archive, Directory targetDirectory) { - for (ArchiveFile archiveFile in archive.files) { + for (final ArchiveFile archiveFile in archive.files) { // The archive package doesn't correctly set isFile. if (!archiveFile.isFile || archiveFile.name.endsWith('/')) { continue; diff --git a/packages/flutter_tools/lib/src/base/process.dart b/packages/flutter_tools/lib/src/base/process.dart index e2e612863a2..fb634e8dc62 100644 --- a/packages/flutter_tools/lib/src/base/process.dart +++ b/packages/flutter_tools/lib/src/base/process.dart @@ -78,11 +78,11 @@ Future runShutdownHooks() async { globals.printTrace('Running shutdown hooks'); _shutdownHooksRunning = true; try { - for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { + for (final ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { globals.printTrace('Shutdown hook priority ${stage.priority}'); final List hooks = _shutdownHooks.remove(stage); final List> futures = >[]; - for (ShutdownHook shutdownHook in hooks) { + for (final ShutdownHook shutdownHook in hooks) { final FutureOr result = shutdownHook(); if (result is Future) { futures.add(result); diff --git a/packages/flutter_tools/lib/src/base/signals.dart b/packages/flutter_tools/lib/src/base/signals.dart index 3899d4f3a91..28b9e67e866 100644 --- a/packages/flutter_tools/lib/src/base/signals.dart +++ b/packages/flutter_tools/lib/src/base/signals.dart @@ -114,7 +114,7 @@ class _DefaultSignals implements Signals { } Future _handleSignal(ProcessSignal s) async { - for (SignalHandler handler in _handlersList[s]) { + for (final SignalHandler handler in _handlersList[s]) { try { await asyncGuard(() async => handler(s)); } catch (e) { diff --git a/packages/flutter_tools/lib/src/base/utils.dart b/packages/flutter_tools/lib/src/base/utils.dart index 0cfcc72fed3..b246d1016e6 100644 --- a/packages/flutter_tools/lib/src/base/utils.dart +++ b/packages/flutter_tools/lib/src/base/utils.dart @@ -319,7 +319,7 @@ String wrapText(String text, { int columnWidth, int hangingIndent, int indent, b hangingIndent ??= 0; final List splitText = text.split('\n'); final List result = []; - for (String line in splitText) { + for (final String line in splitText) { String trimmedText = line.trimLeft(); final String leadingWhitespace = line.substring(0, line.length - trimmedText.length); List notIndented; @@ -433,7 +433,7 @@ List _wrapTextAsLines(String text, { int start = 0, int columnWidth, boo final RegExp characterOrCode = RegExp('(\u001b\[[0-9;]*m|.)', multiLine: true); List<_AnsiRun> result = <_AnsiRun>[]; final StringBuffer current = StringBuffer(); - for (Match match in characterOrCode.allMatches(input)) { + for (final Match match in characterOrCode.allMatches(input)) { current.write(match[0]); if (match[0].length < 4) { // This is a regular character, write it out. @@ -461,7 +461,7 @@ List _wrapTextAsLines(String text, { int start = 0, int columnWidth, boo final List result = []; final int effectiveLength = max(columnWidth - start, kMinColumnWidth); - for (String line in text.split('\n')) { + for (final String line in text.split('\n')) { // If the line is short enough, even with ANSI codes, then we can just add // add it and move on. if (line.length <= effectiveLength || !shouldWrap) { diff --git a/packages/flutter_tools/lib/src/base/version.dart b/packages/flutter_tools/lib/src/base/version.dart index 5e794354367..e89772c463e 100644 --- a/packages/flutter_tools/lib/src/base/version.dart +++ b/packages/flutter_tools/lib/src/base/version.dart @@ -52,7 +52,7 @@ class Version implements Comparable { /// This is the highest-numbered stable version. static Version primary(List versions) { Version primary; - for (Version version in versions) { + for (final Version version in versions) { if (primary == null || (version > primary)) { primary = version; } diff --git a/packages/flutter_tools/lib/src/build_runner/build_runner.dart b/packages/flutter_tools/lib/src/build_runner/build_runner.dart index 082605f07a0..0a9334ed791 100644 --- a/packages/flutter_tools/lib/src/build_runner/build_runner.dart +++ b/packages/flutter_tools/lib/src/build_runner/build_runner.dart @@ -78,7 +78,7 @@ class BuildRunner extends CodeGenerator { stringBuffer.writeln('dependencies:'); final YamlMap builders = flutterProject.builders; if (builders != null) { - for (String name in builders.keys.cast()) { + for (final String name in builders.keys.cast()) { final Object node = builders[name]; // For relative paths, make sure it is accounted for // parent directories. diff --git a/packages/flutter_tools/lib/src/build_runner/web_compilation_delegate.dart b/packages/flutter_tools/lib/src/build_runner/web_compilation_delegate.dart index de5f20d416a..df9c642a4e8 100644 --- a/packages/flutter_tools/lib/src/build_runner/web_compilation_delegate.dart +++ b/packages/flutter_tools/lib/src/build_runner/web_compilation_delegate.dart @@ -60,7 +60,7 @@ class BuildRunnerWebCompilationProxy extends WebCompilationProxy { ); client.startBuild(); bool success = true; - await for (BuildResults results in client.buildResults) { + await for (final BuildResults results in client.buildResults) { final BuildResult result = results.results.firstWhere((BuildResult result) { return result.target == 'web'; }); @@ -81,7 +81,7 @@ class BuildRunnerWebCompilationProxy extends WebCompilationProxy { final Iterable childDirectories = rootDirectory .listSync() .whereType(); - for (Directory childDirectory in childDirectories) { + for (final Directory childDirectory in childDirectories) { final String path = globals.fs.path.join(testOutputDir, 'packages', globals.fs.path.basename(childDirectory.path)); copyDirectorySync(childDirectory.childDirectory('lib'), globals.fs.directory(path)); @@ -135,7 +135,7 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader { Stream findAssets(Glob glob, {String package}) async* { if (package == null || packageGraph.root.name == package) { final String generatedRoot = globals.fs.path.join(generatedDirectory.path, packageGraph.root.name); - await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: packageGraph.root.path)) { + await for (final io.FileSystemEntity entity in glob.list(followLinks: true, root: packageGraph.root.path)) { if (entity is io.File && _isNotHidden(entity) && !globals.fs.path.isWithin(generatedRoot, entity.path)) { yield _fileToAssetId(entity, packageGraph.root); } @@ -143,7 +143,7 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader { if (!globals.fs.isDirectorySync(generatedRoot)) { return; } - await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: generatedRoot)) { + await for (final io.FileSystemEntity entity in glob.list(followLinks: true, root: generatedRoot)) { if (entity is io.File && _isNotHidden(entity)) { yield _fileToAssetId(entity, packageGraph.root, globals.fs.path.relative(generatedRoot), true); } diff --git a/packages/flutter_tools/lib/src/build_runner/web_fs.dart b/packages/flutter_tools/lib/src/build_runner/web_fs.dart index 1e9c0bd5c68..f4c97b68958 100644 --- a/packages/flutter_tools/lib/src/build_runner/web_fs.dart +++ b/packages/flutter_tools/lib/src/build_runner/web_fs.dart @@ -154,7 +154,7 @@ class WebFs { return true; } _client.startBuild(); - await for (BuildResults results in _client.buildResults) { + await for (final BuildResults results in _client.buildResults) { final BuildResult result = results.results.firstWhere((BuildResult result) { return result.target == kBuildTargetName; }); @@ -367,7 +367,7 @@ class ReleaseAssetServer extends AssetServer { @override Future handle(Request request) async { Uri fileUri; - for (Uri uri in _searchPaths) { + for (final Uri uri in _searchPaths) { final Uri potential = uri.resolve(request.url.path); if (potential == null || !globals.fs.isFileSync(potential.toFilePath())) { continue; @@ -445,7 +445,7 @@ class DebugAssetServer extends AssetServer { final Archive archive = TarDecoder().decodeBytes(dart2jsArchive.readAsBytesSync()); partFiles = globals.fs.systemTempDirectory.createTempSync('flutter_tool.') ..createSync(); - for (ArchiveFile file in archive) { + for (final ArchiveFile file in archive) { partFiles.childFile(file.name).writeAsBytesSync(file.content as List); } } @@ -664,7 +664,7 @@ class BuildDaemonCreator { '--define', 'flutter_tools:shell=initializePlatform=$initializePlatform', // The following will cause build runner to only build tests that were requested. if (testTargets != null && testTargets.hasBuildFilters) - for (String buildFilter in testTargets.buildFilters) + for (final String buildFilter in testTargets.buildFilters) '--build-filter=$buildFilter', ]; diff --git a/packages/flutter_tools/lib/src/build_system/build_system.dart b/packages/flutter_tools/lib/src/build_system/build_system.dart index 1f67a56a76a..6f4f85a8f43 100644 --- a/packages/flutter_tools/lib/src/build_system/build_system.dart +++ b/packages/flutter_tools/lib/src/build_system/build_system.dart @@ -138,7 +138,7 @@ abstract class Target { inputsFiles.sources, outputFiles.sources, [ - for (Target target in dependencies) target._toNode(environment), + for (final Target target in dependencies) target._toNode(environment), ], environment, inputsFiles.containsNewDepfile, @@ -160,11 +160,11 @@ abstract class Target { ) { final File stamp = _findStampFile(environment); final List inputPaths = []; - for (File input in inputs) { + for (final File input in inputs) { inputPaths.add(input.path); } final List outputPaths = []; - for (File output in outputs) { + for (final File output in outputs) { outputPaths.add(output.path); } final Map result = { @@ -207,13 +207,13 @@ abstract class Target { return { 'name': name, 'dependencies': [ - for (Target target in dependencies) target.name, + for (final Target target in dependencies) target.name, ], 'inputs': [ - for (File file in resolveInputs(environment).sources) file.path, + for (final File file in resolveInputs(environment).sources) file.path, ], 'outputs': [ - for (File file in resolveOutputs(environment).sources) file.path, + for (final File file in resolveOutputs(environment).sources) file.path, ], 'stamp': _findStampFile(environment).absolute.path, }; @@ -229,7 +229,7 @@ abstract class Target { List depfiles, Environment environment, { bool implicit = true, bool inputs = true, }) { final SourceVisitor collector = SourceVisitor(environment, inputs); - for (Source source in config) { + for (final Source source in config) { source.accept(collector); } depfiles.forEach(collector.visitDepfile); @@ -292,7 +292,7 @@ class Environment { String buildPrefix; final List keys = defines.keys.toList()..sort(); final StringBuffer buffer = StringBuffer(); - for (String key in keys) { + for (final String key in keys) { buffer.write(key); buffer.write(defines[key]); } @@ -502,10 +502,10 @@ class _BuildInstance { // these files are included as both inputs and outputs then it isn't // possible to construct a DAG describing the build. void updateGraph() { - for (File output in node.outputs) { + for (final File output in node.outputs) { outputFiles[output.path] = output; } - for (File input in node.inputs) { + for (final File input in node.inputs) { final String resolvedPath = input.absolute.path; if (outputFiles.containsKey(resolvedPath)) { continue; @@ -550,7 +550,7 @@ class _BuildInstance { // Delete outputs from previous stages that are no longer a part of the // build. - for (String previousOutput in node.previousOutputs) { + for (final String previousOutput in node.previousOutputs) { if (outputFiles.containsKey(previousOutput)) { continue; } @@ -614,7 +614,7 @@ void checkCycles(Target initial) { } visited.add(target); stack.add(target); - for (Target dependency in target.dependencies) { + for (final Target dependency in target.dependencies) { checkInternal(dependency, visited, stack); } stack.remove(target); @@ -627,7 +627,7 @@ void verifyOutputDirectories(List outputs, Environment environment, Target final String buildDirectory = environment.buildDir.resolveSymbolicLinksSync(); final String projectDirectory = environment.projectDir.resolveSymbolicLinksSync(); final List missingOutputs = []; - for (File sourceFile in outputs) { + for (final File sourceFile in outputs) { if (!sourceFile.existsSync()) { missingOutputs.add(sourceFile); continue; @@ -733,13 +733,13 @@ class Node { FileHashStore fileHashStore, ) async { final Set currentOutputPaths = { - for (File file in outputs) file.path, + for (final File file in outputs) file.path, }; // For each input, first determine if we've already computed the hash // for it. Then collect it to be sent off for hashing as a group. final List sourcesToHash = []; final List missingInputs = []; - for (File file in inputs) { + for (final File file in inputs) { if (!file.existsSync()) { missingInputs.add(file); continue; @@ -760,7 +760,7 @@ class Node { // For each output, first determine if we've already computed the hash // for it. Then collect it to be sent off for hashing as a group. - for (String previousOutput in previousOutputs) { + for (final String previousOutput in previousOutputs) { // output paths changed. if (!currentOutputPaths.contains(previousOutput)) { _dirty = true; diff --git a/packages/flutter_tools/lib/src/build_system/depfile.dart b/packages/flutter_tools/lib/src/build_system/depfile.dart index 6e777af6bac..6ae60212b6e 100644 --- a/packages/flutter_tools/lib/src/build_system/depfile.dart +++ b/packages/flutter_tools/lib/src/build_system/depfile.dart @@ -31,7 +31,7 @@ class Depfile { /// file must be manually specified. factory Depfile.parseDart2js(File file, File output) { final List inputs = []; - for (String rawUri in file.readAsLinesSync()) { + for (final String rawUri in file.readAsLinesSync()) { if (rawUri.trim().isEmpty) { continue; } @@ -72,7 +72,7 @@ class Depfile { } void _writeFilesToBuffer(List files, StringBuffer buffer) { - for (File outputFile in files) { + for (final File outputFile in files) { if (globals.platform.isWindows) { // Paths in a depfile have to be escaped on windows. final String escapedPath = outputFile.path.replaceAll(r'\', r'\\'); diff --git a/packages/flutter_tools/lib/src/build_system/file_hash_store.dart b/packages/flutter_tools/lib/src/build_system/file_hash_store.dart index 72925ee2e44..0879c7b3d98 100644 --- a/packages/flutter_tools/lib/src/build_system/file_hash_store.dart +++ b/packages/flutter_tools/lib/src/build_system/file_hash_store.dart @@ -24,7 +24,7 @@ class FileStorage { final int version = json['version'] as int; final List> rawCachedFiles = (json['files'] as List).cast>(); final List cachedFiles = [ - for (Map rawFile in rawCachedFiles) FileHash.fromJson(rawFile), + for (final Map rawFile in rawCachedFiles) FileHash.fromJson(rawFile), ]; return FileStorage(version, cachedFiles); } @@ -36,7 +36,7 @@ class FileStorage { final Map json = { 'version': version, 'files': [ - for (FileHash file in files) file.toJson(), + for (final FileHash file in files) file.toJson(), ], }; return utf8.encode(jsonEncode(json)); @@ -118,7 +118,7 @@ class FileHashStore { cacheFile.deleteSync(); return; } - for (FileHash fileHash in fileStorage.files) { + for (final FileHash fileHash in fileStorage.files) { previousHashes[fileHash.path] = fileHash.hash; } globals.printTrace('Done initializing file store'); @@ -132,7 +132,7 @@ class FileHashStore { cacheFile.createSync(recursive: true); } final List fileHashes = []; - for (MapEntry entry in currentHashes.entries) { + for (final MapEntry entry in currentHashes.entries) { fileHashes.add(FileHash(entry.key, entry.value)); } final FileStorage fileStorage = FileStorage( @@ -158,7 +158,7 @@ class FileHashStore { final List dirty = []; final Pool openFiles = Pool(kMaxOpenFiles); await Future.wait(>[ - for (File file in files) _hashFile(file, dirty, openFiles) + for (final File file in files) _hashFile(file, dirty, openFiles) ]); return dirty; } diff --git a/packages/flutter_tools/lib/src/build_system/source.dart b/packages/flutter_tools/lib/src/build_system/source.dart index eb35f959a65..e0df5cb4ed1 100644 --- a/packages/flutter_tools/lib/src/build_system/source.dart +++ b/packages/flutter_tools/lib/src/build_system/source.dart @@ -146,7 +146,7 @@ class SourceVisitor implements ResolvedFiles { if (!globals.fs.directory(filePath).existsSync()) { throw Exception('$filePath does not exist!'); } - for (FileSystemEntity entity in globals.fs.directory(filePath).listSync()) { + for (final FileSystemEntity entity in globals.fs.directory(filePath).listSync()) { final String filename = globals.fs.path.basename(entity.path); if (wildcardSegments.isEmpty) { sources.add(globals.fs.file(entity.absolute)); diff --git a/packages/flutter_tools/lib/src/build_system/targets/ios.dart b/packages/flutter_tools/lib/src/build_system/targets/ios.dart index 1d9152af0a0..032e270c694 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/ios.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/ios.dart @@ -59,7 +59,7 @@ abstract class AotAssemblyBase extends Target { // If we're building multiple iOS archs the binaries need to be lipo'd // together. final List> pending = >[]; - for (DarwinArch iosArch in iosArchs) { + for (final DarwinArch iosArch in iosArchs) { pending.add(snapshotter.build( platform: targetPlatform, buildMode: buildMode, diff --git a/packages/flutter_tools/lib/src/build_system/targets/linux.dart b/packages/flutter_tools/lib/src/build_system/targets/linux.dart index 706b788472d..8375ecd9b75 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/linux.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/linux.dart @@ -59,7 +59,7 @@ class UnpackLinuxDebug extends Target { ); // The native linux artifacts are composed of 6 files and a directory (listed above) // which need to be copied to the target directory. - for (String artifact in _kLinuxArtifacts) { + for (final String artifact in _kLinuxArtifacts) { final String entityPath = globals.fs.path.join(basePath, artifact); // If this artifact is a file, just copy the source over. if (globals.fs.isFileSync(entityPath)) { @@ -79,7 +79,7 @@ class UnpackLinuxDebug extends Target { } // If the artifact is the directory cpp_client_wrapper, recursively // copy every file from it. - for (File input in globals.fs.directory(entityPath) + for (final File input in globals.fs.directory(entityPath) .listSync(recursive: true) .whereType()) { final String outputPath = globals.fs.path.join( diff --git a/packages/flutter_tools/lib/src/build_system/targets/web.dart b/packages/flutter_tools/lib/src/build_system/targets/web.dart index 97e0a00350f..00d9f634935 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/web.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/web.dart @@ -170,7 +170,7 @@ class Dart2JSTarget extends Target { '-Ddart.vm.profile=true' else '-Ddart.vm.product=true', - for (String dartDefine in parseDartDefines(environment)) + for (final String dartDefine in parseDartDefines(environment)) '-D$dartDefine', environment.buildDir.childFile('main.dart').path, ]); @@ -224,7 +224,7 @@ class WebReleaseBundle extends Target { @override Future build(Environment environment) async { - for (File outputFile in environment.buildDir.listSync(recursive: true).whereType()) { + for (final File outputFile in environment.buildDir.listSync(recursive: true).whereType()) { if (!globals.fs.path.basename(outputFile.path).contains('main.dart.js')) { continue; } diff --git a/packages/flutter_tools/lib/src/build_system/targets/windows.dart b/packages/flutter_tools/lib/src/build_system/targets/windows.dart index 5b05aa13d93..ce1ee7b6045 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/windows.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/windows.dart @@ -41,7 +41,7 @@ class UnpackWindows extends Target { Future build(Environment environment) async { // This path needs to match the prefix in the rule below. final String basePath = globals.artifacts.getArtifactPath(Artifact.windowsDesktopPath); - for (File input in globals.fs.directory(basePath) + for (final File input in globals.fs.directory(basePath) .listSync(recursive: true) .whereType()) { final String outputPath = globals.fs.path.join( diff --git a/packages/flutter_tools/lib/src/bundle.dart b/packages/flutter_tools/lib/src/bundle.dart index 2a3c9382fb0..b49658704c1 100644 --- a/packages/flutter_tools/lib/src/bundle.dart +++ b/packages/flutter_tools/lib/src/bundle.dart @@ -126,7 +126,7 @@ Future buildWithAssemble({ final BuildResult result = await buildSystem.build(target, environment); if (!result.success) { - for (ExceptionMeasurement measurement in result.exceptions.values) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace diff --git a/packages/flutter_tools/lib/src/cache.dart b/packages/flutter_tools/lib/src/cache.dart index 821f4c2500c..4320f34d81f 100644 --- a/packages/flutter_tools/lib/src/cache.dart +++ b/packages/flutter_tools/lib/src/cache.dart @@ -108,7 +108,7 @@ class Cache { _artifacts.add(MacOSFuchsiaSDKArtifacts(this)); _artifacts.add(FlutterRunnerSDKArtifacts(this)); _artifacts.add(FlutterRunnerDebugSymbols(this)); - for (String artifactName in IosUsbArtifacts.artifactNames) { + for (final String artifactName in IosUsbArtifacts.artifactNames) { _artifacts.add(IosUsbArtifacts(artifactName, this)); } } else { @@ -300,7 +300,7 @@ class Cache { return _dyLdLibEntry; } final List paths = []; - for (ArtifactSet artifact in _artifacts) { + for (final ArtifactSet artifact in _artifacts) { final Map env = artifact.environment; if (env == null || !env.containsKey('DYLD_LIBRARY_PATH')) { continue; @@ -378,7 +378,7 @@ class Cache { if (!_lockEnabled) { return; } - for (ArtifactSet artifact in _artifacts) { + for (final ArtifactSet artifact in _artifacts) { if (!requiredArtifacts.contains(artifact.developmentArtifact)) { globals.printTrace('Artifact $artifact is not required, skipping update.'); continue; @@ -409,7 +409,7 @@ class Cache { final bool includeAllPlatformsState = globals.cache.includeAllPlatforms; bool allAvailible = true; globals.cache.includeAllPlatforms = includeAllPlatforms; - for (ArtifactSet cachedArtifact in _artifacts) { + for (final ArtifactSet cachedArtifact in _artifacts) { if (cachedArtifact is EngineCachedArtifact) { allAvailible &= await cachedArtifact.checkForArtifacts(engineVersion); } @@ -496,7 +496,7 @@ abstract class CachedArtifact extends ArtifactSet { /// Clear any zip/gzip files downloaded. void _removeDownloadedFiles() { - for (File f in downloadedFiles) { + for (final File f in downloadedFiles) { try { f.deleteSync(); } on FileSystemException catch (e) { @@ -606,7 +606,7 @@ class FlutterWebSdk extends CachedArtifact { final Uri url = Uri.parse('${cache.storageBaseUrl}/flutter_infra/flutter/$version/$platformName.zip'); await _downloadZipArchive('Downloading Web SDK...', url, location); // This is a temporary work-around for not being able to safely download into a shared directory. - for (FileSystemEntity entity in location.listSync(recursive: true)) { + for (final FileSystemEntity entity in location.listSync(recursive: true)) { if (entity is File) { final List segments = globals.fs.path.split(entity.path); segments.remove('flutter_web_sdk'); @@ -643,21 +643,21 @@ abstract class EngineCachedArtifact extends CachedArtifact { @override bool isUpToDateInner() { final Directory pkgDir = cache.getCacheDir('pkg'); - for (String pkgName in getPackageDirs()) { + for (final String pkgName in getPackageDirs()) { final String pkgPath = globals.fs.path.join(pkgDir.path, pkgName); if (!globals.fs.directory(pkgPath).existsSync()) { return false; } } - for (List toolsDir in getBinaryDirs()) { + for (final List toolsDir in getBinaryDirs()) { final Directory dir = globals.fs.directory(globals.fs.path.join(location.path, toolsDir[0])); if (!dir.existsSync()) { return false; } } - for (String licenseDir in getLicenseDirs()) { + for (final String licenseDir in getLicenseDirs()) { final File file = globals.fs.file(globals.fs.path.join(location.path, licenseDir, 'LICENSE')); if (!file.existsSync()) { return false; @@ -671,11 +671,11 @@ abstract class EngineCachedArtifact extends CachedArtifact { final String url = '${cache.storageBaseUrl}/flutter_infra/flutter/$version/'; final Directory pkgDir = cache.getCacheDir('pkg'); - for (String pkgName in getPackageDirs()) { + for (final String pkgName in getPackageDirs()) { await _downloadZipArchive('Downloading package $pkgName...', Uri.parse(url + pkgName + '.zip'), pkgDir); } - for (List toolsDir in getBinaryDirs()) { + for (final List toolsDir in getBinaryDirs()) { final String cacheDir = toolsDir[0]; final String urlPath = toolsDir[1]; final Directory dir = globals.fs.directory(globals.fs.path.join(location.path, cacheDir)); @@ -684,7 +684,7 @@ abstract class EngineCachedArtifact extends CachedArtifact { _makeFilesExecutable(dir); const List frameworkNames = ['Flutter', 'FlutterMacOS']; - for (String frameworkName in frameworkNames) { + for (final String frameworkName in frameworkNames) { final File frameworkZip = globals.fs.file(globals.fs.path.join(dir.path, '$frameworkName.framework.zip')); if (frameworkZip.existsSync()) { final Directory framework = globals.fs.directory(globals.fs.path.join(dir.path, '$frameworkName.framework')); @@ -695,7 +695,7 @@ abstract class EngineCachedArtifact extends CachedArtifact { } final File licenseSource = cache.getLicenseFile(); - for (String licenseDir in getLicenseDirs()) { + for (final String licenseDir in getLicenseDirs()) { final String licenseDestinationPath = globals.fs.path.join(location.path, licenseDir, 'LICENSE'); await licenseSource.copy(licenseDestinationPath); } @@ -706,7 +706,7 @@ abstract class EngineCachedArtifact extends CachedArtifact { final String url = '${cache.storageBaseUrl}/flutter_infra/flutter/$engineVersion/'; bool exists = false; - for (String pkgName in getPackageDirs()) { + for (final String pkgName in getPackageDirs()) { exists = await _doesRemoteExist('Checking package $pkgName is available...', Uri.parse(url + pkgName + '.zip')); if (!exists) { @@ -714,7 +714,7 @@ abstract class EngineCachedArtifact extends CachedArtifact { } } - for (List toolsDir in getBinaryDirs()) { + for (final List toolsDir in getBinaryDirs()) { final String cacheDir = toolsDir[0]; final String urlPath = toolsDir[1]; exists = await _doesRemoteExist('Checking $cacheDir tools are available...', @@ -728,7 +728,7 @@ abstract class EngineCachedArtifact extends CachedArtifact { void _makeFilesExecutable(Directory dir) { os.chmod(dir, 'a+r,a+x'); - for (FileSystemEntity entity in dir.listSync(recursive: true)) { + for (final FileSystemEntity entity in dir.listSync(recursive: true)) { if (entity is File) { final FileStat stat = entity.statSync(); final bool isUserExecutable = ((stat.mode >> 6) & 0x1) == 1; @@ -1000,7 +1000,7 @@ class GradleWrapper extends CachedArtifact { if (!globals.fs.directory(wrapperDir).existsSync()) { return false; } - for (String scriptName in _gradleScripts) { + for (final String scriptName in _gradleScripts) { final File scriptFile = globals.fs.file(globals.fs.path.join(wrapperDir.path, scriptName)); if (!scriptFile.existsSync()) { return false; @@ -1189,7 +1189,7 @@ class IosUsbArtifacts extends CachedArtifact { if (executables == null) { return true; } - for (String executable in executables) { + for (final String executable in executables) { if (!location.childFile(executable).existsSync()) { return false; } diff --git a/packages/flutter_tools/lib/src/codegen.dart b/packages/flutter_tools/lib/src/codegen.dart index 75e10727fe1..6be4fed1e73 100644 --- a/packages/flutter_tools/lib/src/codegen.dart +++ b/packages/flutter_tools/lib/src/codegen.dart @@ -118,7 +118,7 @@ class CodeGeneratingKernelCompiler implements KernelCompiler { codeGenerator.updatePackages(flutterProject); final CodegenDaemon codegenDaemon = await codeGenerator.daemon(flutterProject); codegenDaemon.startBuild(); - await for (CodegenStatus codegenStatus in codegenDaemon.buildResults) { + await for (final CodegenStatus codegenStatus in codegenDaemon.buildResults) { if (codegenStatus == CodegenStatus.Failed) { globals.printError('Code generation failed, build may have compile errors.'); break; diff --git a/packages/flutter_tools/lib/src/commands/analyze_base.dart b/packages/flutter_tools/lib/src/commands/analyze_base.dart index 568e1170d02..63fb3dce1d6 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_base.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_base.dart @@ -86,8 +86,8 @@ class PackageDependency { bool get hasConflict => values.length > 1; bool get hasConflictAffectingFlutterRepo { assert(globals.fs.path.isAbsolute(Cache.flutterRoot)); - for (List targetSources in values.values) { - for (String source in targetSources) { + for (final List targetSources in values.values) { + for (final String source in targetSources) { assert(globals.fs.path.isAbsolute(source)); if (globals.fs.path.isWithin(Cache.flutterRoot, source)) { return true; @@ -100,11 +100,11 @@ class PackageDependency { assert(hasConflict); final List targets = values.keys.toList(); targets.sort((String a, String b) => values[b].length.compareTo(values[a].length)); - for (String target in targets) { + for (final String target in targets) { final int count = values[target].length; result.writeln(' $count ${count == 1 ? 'source wants' : 'sources want'} "$target":'); bool canonical = false; - for (String source in values[target]) { + for (final String source in values[target]) { result.writeln(' $source'); if (source == canonicalSource) { canonical = true; @@ -140,7 +140,7 @@ class PackageDependencyTracker { .readAsStringSync() .split('\n') .where((String line) => !line.startsWith(RegExp(r'^ *#'))); - for (String line in lines) { + for (final String line in lines) { final int colon = line.indexOf(':'); if (colon > 0) { final String packageName = line.substring(0, colon); @@ -165,7 +165,7 @@ class PackageDependencyTracker { } void checkForConflictingDependencies(Iterable pubSpecDirectories, PackageDependencyTracker dependencies) { - for (Directory directory in pubSpecDirectories) { + for (final Directory directory in pubSpecDirectories) { final String pubSpecYamlPath = globals.fs.path.join(directory.path, 'pubspec.yaml'); final File pubSpecYamlFile = globals.fs.file(pubSpecYamlPath); if (pubSpecYamlFile.existsSync()) { @@ -219,7 +219,7 @@ class PackageDependencyTracker { String generateConflictReport() { assert(hasConflicts); final StringBuffer result = StringBuffer(); - for (String package in packages.keys.where((String package) => packages[package].hasConflict)) { + for (final String package in packages.keys.where((String package) => packages[package].hasConflict)) { result.writeln('Package "$package" has conflicts:'); packages[package].describeConflict(result); } @@ -228,7 +228,7 @@ class PackageDependencyTracker { Map asPackageMap() { final Map result = {}; - for (String package in packages.keys) { + for (final String package in packages.keys) { result[package] = packages[package].target; } return result; diff --git a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart index 2e9802c316f..c6271d5dcb1 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart @@ -43,7 +43,7 @@ class AnalyzeContinuously extends AnalyzeBase { analysisTarget = 'Flutter repository'; globals.printTrace('Analyzing Flutter repository:'); - for (String projectPath in repoRoots) { + for (final String projectPath in repoRoots) { globals.printTrace(' ${globals.fs.path.relative(projectPath)}'); } } else { @@ -91,7 +91,7 @@ class AnalyzeContinuously extends AnalyzeBase { // Remove errors for deleted files, sort, and print errors. final List errors = []; - for (String path in analysisErrors.keys.toList()) { + for (final String path in analysisErrors.keys.toList()) { if (globals.fs.isFileSync(path)) { errors.addAll(analysisErrors[path]); } else { @@ -112,7 +112,7 @@ class AnalyzeContinuously extends AnalyzeBase { errors.sort(); - for (AnalysisError error in errors) { + for (final AnalysisError error in errors) { globals.printStatus(error.toString()); if (error.code != null) { globals.printTrace('error code: ${error.code}'); diff --git a/packages/flutter_tools/lib/src/commands/analyze_once.dart b/packages/flutter_tools/lib/src/commands/analyze_once.dart index aaa44dfdd41..db2b7245093 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_once.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_once.dart @@ -41,7 +41,7 @@ class AnalyzeOnce extends AnalyzeBase { final Set directories = Set.from(argResults.rest .map((String path) => globals.fs.path.canonicalize(path))); if (directories.isNotEmpty) { - for (String directory in directories) { + for (final String directory in directories) { final FileSystemEntityType type = globals.fs.typeSync(directory); if (type == FileSystemEntityType.notFound) { @@ -138,7 +138,7 @@ class AnalyzeOnce extends AnalyzeBase { globals.printStatus(''); } errors.sort(); - for (AnalysisError error in errors) { + for (final AnalysisError error in errors) { globals.printStatus(error.toString(), hangingIndent: 7); } diff --git a/packages/flutter_tools/lib/src/commands/assemble.dart b/packages/flutter_tools/lib/src/commands/assemble.dart index 583412b869d..75fc58d635a 100644 --- a/packages/flutter_tools/lib/src/commands/assemble.dart +++ b/packages/flutter_tools/lib/src/commands/assemble.dart @@ -115,11 +115,11 @@ class AssembleCommand extends FlutterCommand { } final String name = argResults.rest.first; final Map targetMap = { - for (Target target in _kDefaultTargets) + for (final Target target in _kDefaultTargets) target.name: target }; final List results = [ - for (String targetName in argResults.rest) + for (final String targetName in argResults.rest) if (targetMap.containsKey(targetName)) targetMap[targetName] ]; @@ -153,7 +153,7 @@ class AssembleCommand extends FlutterCommand { Map _parseDefines(List values) { final Map results = {}; - for (String chunk in values) { + for (final String chunk in values) { final int indexEquals = chunk.indexOf('='); if (indexEquals == -1) { throwToolExit('Improperly formatted define flag: $chunk'); @@ -179,7 +179,7 @@ class AssembleCommand extends FlutterCommand { : null, )); if (!result.success) { - for (ExceptionMeasurement measurement in result.exceptions.values) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace @@ -209,7 +209,7 @@ void writeListIfChanged(List files, String path) { final File file = globals.fs.file(path); final StringBuffer buffer = StringBuffer(); // These files are already sorted. - for (File file in files) { + for (final File file in files) { buffer.writeln(file.path); } final String newContents = buffer.toString(); diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index 3ce4a892276..421b425c000 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart @@ -226,7 +226,7 @@ class AttachCommand extends FlutterCommand { } catch (_) { isolateDiscoveryProtocol?.dispose(); final List ports = device.portForwarder.forwardedPorts.toList(); - for (ForwardedPort port in ports) { + for (final ForwardedPort port in ports) { await device.portForwarder.unforward(port); } rethrow; @@ -329,7 +329,7 @@ class AttachCommand extends FlutterCommand { } } finally { final List ports = device.portForwarder.forwardedPorts.toList(); - for (ForwardedPort port in ports) { + for (final ForwardedPort port in ports) { await device.portForwarder.unforward(port); } } diff --git a/packages/flutter_tools/lib/src/commands/build_aar.dart b/packages/flutter_tools/lib/src/commands/build_aar.dart index 84a83d8e90b..7b798c62d2a 100644 --- a/packages/flutter_tools/lib/src/commands/build_aar.dart +++ b/packages/flutter_tools/lib/src/commands/build_aar.dart @@ -101,7 +101,7 @@ class BuildAarCommand extends BuildSubCommand { ? stringArg('build-number') : '1.0'; - for (String buildMode in const ['debug', 'profile', 'release']) { + for (final String buildMode in const ['debug', 'profile', 'release']) { if (boolArg(buildMode)) { androidBuildInfo.add(AndroidBuildInfo( BuildInfo(BuildMode.fromName(buildMode), stringArg('flavor')), diff --git a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart index bd48a1297ef..3ac3b489fe9 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart @@ -158,7 +158,7 @@ class BuildIOSFrameworkCommand extends BuildSubCommand { bundleBuilder ??= BundleBuilder(); cache ??= globals.cache; - for (BuildMode mode in buildModes) { + for (final BuildMode mode in buildModes) { globals.printStatus('Building framework for $iosProject in ${getNameForBuildMode(mode)} mode...'); final String xcodeBuildConfiguration = toTitleCase(getNameForBuildMode(mode)); final Directory modeDirectory = outputDirectory.childDirectory(xcodeBuildConfiguration); @@ -470,8 +470,8 @@ end final Directory iPhoneBuildConfiguration = iPhoneBuildOutput.childDirectory('$xcodeBuildConfiguration-iphoneos'); final Directory simulatorBuildConfiguration = simulatorBuildOutput.childDirectory('$xcodeBuildConfiguration-iphonesimulator'); - for (Directory builtProduct in iPhoneBuildConfiguration.listSync(followLinks: false).whereType()) { - for (FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) { + for (final Directory builtProduct in iPhoneBuildConfiguration.listSync(followLinks: false).whereType()) { + for (final FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) { final String podFrameworkName = podProduct.basename; if (globals.fs.path.extension(podFrameworkName) == '.framework') { final String binaryName = globals.fs.path.basenameWithoutExtension(podFrameworkName); diff --git a/packages/flutter_tools/lib/src/commands/clean.dart b/packages/flutter_tools/lib/src/commands/clean.dart index 5d7bc070bc7..db78584f9e8 100644 --- a/packages/flutter_tools/lib/src/commands/clean.dart +++ b/packages/flutter_tools/lib/src/commands/clean.dart @@ -73,7 +73,7 @@ class CleanCommand extends FlutterCommand { try { final Directory xcodeWorkspace = xcodeProject.xcodeWorkspace; final XcodeProjectInfo projectInfo = await xcodeProjectInterpreter.getInfo(xcodeWorkspace.parent.path); - for (String scheme in projectInfo.schemes) { + for (final String scheme in projectInfo.schemes) { xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme); } } catch (error) { diff --git a/packages/flutter_tools/lib/src/commands/config.dart b/packages/flutter_tools/lib/src/commands/config.dart index d1626acc2bb..c4ab2c897cb 100644 --- a/packages/flutter_tools/lib/src/commands/config.dart +++ b/packages/flutter_tools/lib/src/commands/config.dart @@ -30,7 +30,7 @@ class ConfigCommand extends FlutterCommand { negatable: false, hide: !verboseHelp, help: 'Print config values as json.'); - for (Feature feature in allFeatures) { + for (final Feature feature in allFeatures) { if (feature.configSetting == null) { continue; } @@ -69,7 +69,7 @@ class ConfigCommand extends FlutterCommand { // are available. final Map featuresByName = {}; final String channel = FlutterVersion.instance.channel; - for (Feature feature in allFeatures) { + for (final Feature feature in allFeatures) { if (feature.configSetting != null) { featuresByName[feature.configSetting] = feature; } @@ -105,7 +105,7 @@ class ConfigCommand extends FlutterCommand { } if (boolArg('clear-features')) { - for (Feature feature in allFeatures) { + for (final Feature feature in allFeatures) { if (feature.configSetting != null) { globals.config.removeValue(feature.configSetting); } @@ -140,7 +140,7 @@ class ConfigCommand extends FlutterCommand { _updateConfig('build-dir', buildDir); } - for (Feature feature in allFeatures) { + for (final Feature feature in allFeatures) { if (feature.configSetting == null) { continue; } @@ -163,7 +163,7 @@ class ConfigCommand extends FlutterCommand { Future handleMachine() async { // Get all the current values. final Map results = {}; - for (String key in globals.config.keys) { + for (final String key in globals.config.keys) { results[key] = globals.config.getValue(key); } diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 823da6acefa..3de6c2b8444 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -44,7 +44,7 @@ enum _ProjectType { _ProjectType _stringToProjectType(String value) { _ProjectType result; - for (_ProjectType type in _ProjectType.values) { + for (final _ProjectType type in _ProjectType.values) { if (value == getEnumName(type)) { result = type; break; @@ -306,7 +306,7 @@ class CreateCommand extends FlutterCommand { if (argResults.rest.length > 1) { String message = 'Multiple output directories specified.'; - for (String arg in argResults.rest) { + for (final String arg in argResults.rest) { if (arg.startsWith('-')) { message += '\nTry moving $arg to be immediately following $name'; break; diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 0c30d603033..1b7cf438918 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -204,7 +204,7 @@ class Daemon { void shutdown({ dynamic error }) { _commandSubscription?.cancel(); - for (Domain domain in _domainMap.values) { + for (final Domain domain in _domainMap.values) { domain.dispose(); } if (!_onExitCompleter.isCompleted) { @@ -791,15 +791,15 @@ class DeviceDomain extends Domain { /// of properties (id, name, platform, ...). Future>> getDevices([ Map args ]) async { return >[ - for (PollingDeviceDiscovery discoverer in _discoverers) - for (Device device in await discoverer.devices) + for (final PollingDeviceDiscovery discoverer in _discoverers) + for (final Device device in await discoverer.devices) await _deviceToMap(device), ]; } /// Enable device events. Future enable(Map args) { - for (PollingDeviceDiscovery discoverer in _discoverers) { + for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.startPolling(); } return Future.value(); @@ -807,7 +807,7 @@ class DeviceDomain extends Domain { /// Disable device events. Future disable(Map args) { - for (PollingDeviceDiscovery discoverer in _discoverers) { + for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.stopPolling(); } return Future.value(); @@ -845,14 +845,14 @@ class DeviceDomain extends Domain { @override void dispose() { - for (PollingDeviceDiscovery discoverer in _discoverers) { + for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.dispose(); } } /// Return the device matching the deviceId field in the args. Future _getDevice(String deviceId) async { - for (PollingDeviceDiscovery discoverer in _discoverers) { + for (final PollingDeviceDiscovery discoverer in _discoverers) { final Device device = (await discoverer.devices).firstWhere((Device device) => device.id == deviceId, orElse: () => null); if (device != null) { return device; diff --git a/packages/flutter_tools/lib/src/commands/devices.dart b/packages/flutter_tools/lib/src/commands/devices.dart index dbae6671c9f..5b478e94a04 100644 --- a/packages/flutter_tools/lib/src/commands/devices.dart +++ b/packages/flutter_tools/lib/src/commands/devices.dart @@ -38,7 +38,7 @@ class DevicesCommand extends FlutterCommand { final List diagnostics = await deviceManager.getDeviceDiagnostics(); if (diagnostics.isNotEmpty) { globals.printStatus(''); - for (String diagnostic in diagnostics) { + for (final String diagnostic in diagnostics) { globals.printStatus('• $diagnostic', hangingIndent: 2); } } diff --git a/packages/flutter_tools/lib/src/commands/generate.dart b/packages/flutter_tools/lib/src/commands/generate.dart index 7b23bae532b..6d58beacf7c 100644 --- a/packages/flutter_tools/lib/src/commands/generate.dart +++ b/packages/flutter_tools/lib/src/commands/generate.dart @@ -26,7 +26,7 @@ class GenerateCommand extends FlutterCommand { final FlutterProject flutterProject = FlutterProject.current(); final CodegenDaemon codegenDaemon = await codeGenerator.daemon(flutterProject); codegenDaemon.startBuild(); - await for (CodegenStatus codegenStatus in codegenDaemon.buildResults) { + await for (final CodegenStatus codegenStatus in codegenDaemon.buildResults) { if (codegenStatus == CodegenStatus.Failed) { globals.printError('Code generation failed.'); break; @@ -44,7 +44,7 @@ class GenerateCommand extends FlutterCommand { return null; } final Directory errorCache = errorCacheParent.childDirectory('error_cache'); - for (File errorFile in errorCache.listSync(recursive: true).whereType()) { + for (final File errorFile in errorCache.listSync(recursive: true).whereType()) { try { final List errorData = json.decode(errorFile.readAsStringSync()) as List; final List stackData = errorData[1] as List; diff --git a/packages/flutter_tools/lib/src/commands/ide_config.dart b/packages/flutter_tools/lib/src/commands/ide_config.dart index fd1c6fcae6a..f42899abca9 100644 --- a/packages/flutter_tools/lib/src/commands/ide_config.dart +++ b/packages/flutter_tools/lib/src/commands/ide_config.dart @@ -126,7 +126,7 @@ class IdeConfigCommand extends FlutterCommand { final Set manifest = {}; final Iterable flutterFiles = _flutterRoot.listSync(recursive: true).whereType(); - for (File srcFile in flutterFiles) { + for (final File srcFile in flutterFiles) { final String relativePath = globals.fs.path.relative(srcFile.path, from: _flutterRoot.absolute.path); // Skip template files in both the ide_templates and templates @@ -186,7 +186,7 @@ class IdeConfigCommand extends FlutterCommand { // Look for any files under the template dir that don't exist in the manifest and remove // them. final Iterable templateFiles = _templateDirectory.listSync(recursive: true).whereType(); - for (File templateFile in templateFiles) { + for (final File templateFile in templateFiles) { final String relativePath = globals.fs.path.relative( templateFile.absolute.path, from: _templateDirectory.absolute.path, diff --git a/packages/flutter_tools/lib/src/commands/precache.dart b/packages/flutter_tools/lib/src/commands/precache.dart index d9a6dd20a69..10b0316b6e5 100644 --- a/packages/flutter_tools/lib/src/commands/precache.dart +++ b/packages/flutter_tools/lib/src/commands/precache.dart @@ -66,7 +66,7 @@ class PrecacheCommand extends FlutterCommand { globals.cache.useUnsignedMacBinaries = true; } final Set requiredArtifacts = {}; - for (DevelopmentArtifact artifact in DevelopmentArtifact.values) { + for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) { // Don't include unstable artifacts on stable branches. if (!FlutterVersion.instance.isMaster && artifact.unstable) { continue; diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 0fe5581f57c..e42857901da 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -245,7 +245,7 @@ class RunCommand extends RunCommandBase { deviceType = 'multiple'; deviceOsVersion = 'multiple'; isEmulator = false; - for (Device device in devices) { + for (final Device device in devices) { final TargetPlatform platform = await device.targetPlatform; anyAndroidDevices = anyAndroidDevices || (platform == TargetPlatform.android); anyIOSDevices = anyIOSDevices || (platform == TargetPlatform.ios); @@ -426,7 +426,7 @@ class RunCommand extends RunCommandBase { 'channel.', null); } - for (Device device in devices) { + for (final Device device in devices) { if (!device.supportsFastStart && boolArg('fast-start')) { globals.printStatus( 'Using --fast-start option with device ${device.name}, but this device ' @@ -456,7 +456,7 @@ class RunCommand extends RunCommandBase { } if (hotMode) { - for (Device device in devices) { + for (final Device device in devices) { if (!device.supportsHotReload) { throwToolExit('Hot reload is not supported by ${device.name}. Run with --no-hot.'); } @@ -470,7 +470,7 @@ class RunCommand extends RunCommandBase { } final FlutterProject flutterProject = FlutterProject.current(); final List flutterDevices = [ - for (Device device in devices) + for (final Device device in devices) await FlutterDevice.create( device, flutterProject: flutterProject, diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 21e2e0fbc05..efdaecc38ed 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -222,7 +222,7 @@ class TestCommand extends FastFlutterCommand { if (flutterProject.hasBuilders) { final CodegenDaemon codegenDaemon = await codeGenerator.daemon(flutterProject); codegenDaemon.startBuild(); - await for (CodegenStatus status in codegenDaemon.buildResults) { + await for (final CodegenStatus status in codegenDaemon.buildResults) { if (status == CodegenStatus.Succeeded) { break; } @@ -296,7 +296,7 @@ class TestCommand extends FastFlutterCommand { return true; } - for (DevFSFileContent entry in entries.values.whereType()) { + for (final DevFSFileContent entry in entries.values.whereType()) { // Calling isModified to access file stats first in order for isModifiedAfter // to work. if (entry.isModified && entry.isModifiedAfter(lastModified)) { diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index 169e276079b..b892a4f5e37 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart @@ -134,7 +134,7 @@ class UpdatePackagesCommand extends FlutterCommand { if (isVerifyOnly) { bool needsUpdate = false; globals.printStatus('Verifying pubspecs...'); - for (Directory directory in packages) { + for (final Directory directory in packages) { PubspecYaml pubspec; try { pubspec = PubspecYaml(directory); @@ -153,7 +153,7 @@ class UpdatePackagesCommand extends FlutterCommand { } // all dependencies in the pubspec sorted lexically. final Map checksumDependencies = {}; - for (PubspecLine data in pubspec.inputData) { + for (final PubspecLine data in pubspec.inputData) { if (data is PubspecDependency && data.kind == DependencyKind.normal) { checksumDependencies[data.name] = data.version; } @@ -194,7 +194,7 @@ class UpdatePackagesCommand extends FlutterCommand { final List pubspecs = []; final Map dependencies = {}; final Set specialDependencies = {}; - for (Directory directory in packages) { // these are all the directories with pubspec.yamls we care about + for (final Directory directory in packages) { // these are all the directories with pubspec.yamls we care about globals.printTrace('Reading pubspec.yaml from: ${directory.path}'); PubspecYaml pubspec; try { @@ -203,7 +203,7 @@ class UpdatePackagesCommand extends FlutterCommand { throwToolExit(message); } pubspecs.add(pubspec); // remember it for later - for (PubspecDependency dependency in pubspec.allDependencies) { // this is all the explicit dependencies + for (final PubspecDependency dependency in pubspec.allDependencies) { // this is all the explicit dependencies if (dependencies.containsKey(dependency.name)) { // If we've seen the dependency before, make sure that we are // importing it the same way. There's several ways to import a @@ -272,13 +272,13 @@ class UpdatePackagesCommand extends FlutterCommand { // The transitive dependency tree for the fake package does not contain // dependencies between Flutter SDK packages and pub packages. We add them // here. - for (PubspecYaml pubspec in pubspecs) { + for (final PubspecYaml pubspec in pubspecs) { final String package = pubspec.name; specialDependencies.add(package); tree._versions[package] = pubspec.version; assert(!tree._dependencyTree.containsKey(package)); tree._dependencyTree[package] = {}; - for (PubspecDependency dependency in pubspec.dependencies) { + for (final PubspecDependency dependency in pubspec.dependencies) { if (dependency.kind == DependencyKind.normal) { tree._dependencyTree[package].add(dependency.name); } @@ -305,7 +305,7 @@ class UpdatePackagesCommand extends FlutterCommand { // to specific versions because they are explicitly pinned by their // constraints. Here we list the names we earlier established we didn't // need to pin because they come from the Dart or Flutter SDKs. - for (PubspecYaml pubspec in pubspecs) { + for (final PubspecYaml pubspec in pubspecs) { pubspec.apply(tree, specialDependencies); } @@ -318,7 +318,7 @@ class UpdatePackagesCommand extends FlutterCommand { final Stopwatch timer = Stopwatch()..start(); int count = 0; - for (Directory dir in packages) { + for (final Directory dir in packages) { await pub.get(context: PubContext.updatePackages, directory: dir.path, checkLastModified: false); count += 1; } @@ -356,7 +356,7 @@ class UpdatePackagesCommand extends FlutterCommand { if (link.from != null) { visited.add(link.from.to); } - for (String dependency in tree._dependencyTree[link.to]) { + for (final String dependency in tree._dependencyTree[link.to]) { if (!visited.contains(dependency)) { traversalQueue.addFirst(_DependencyLink(from: link, to: dependency)); } @@ -483,7 +483,7 @@ class PubspecYaml { // the dependency. So we track what is the "current" (or "last") dependency // that we are dealing with using this variable. PubspecDependency lastDependency; - for (String line in lines) { + for (final String line in lines) { if (lastDependency == null) { // First we look to see if we're transitioning to a new top-level section. // The PubspecHeader.parse static method can recognize those headers. @@ -614,7 +614,7 @@ class PubspecYaml { // overridden by subsequent entries in the same file and any that have the // magic comment flagging them as auto-generated transitive dependencies // that we added in a previous run. - for (PubspecLine data in inputData) { + for (final PubspecLine data in inputData) { if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency) { yield data; } @@ -623,7 +623,7 @@ class PubspecYaml { /// This returns all regular dependencies and all dev dependencies. Iterable get allDependencies sync* { - for (PubspecLine data in inputData) { + for (final PubspecLine data in inputData) { if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive) { yield data; } @@ -652,7 +652,7 @@ class PubspecYaml { // blank lines, and trailing blank lines, and ensuring the file ends with a // newline. This cleanup lets us be a little more aggressive while building // the output. - for (PubspecLine data in inputData) { + for (final PubspecLine data in inputData) { if (data is PubspecHeader) { // This line was a header of some sort. // @@ -754,10 +754,10 @@ class PubspecYaml { // Create a new set to hold the list of packages we've already processed, so // that we don't redundantly process them multiple times. final Set done = {}; - for (String package in directDependencies) { + for (final String package in directDependencies) { transitiveDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); } - for (String package in devDependencies) { + for (final String package in devDependencies) { transitiveDevDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); } @@ -770,10 +770,10 @@ class PubspecYaml { } // Add a line for each transitive dependency and transitive dev dependency using our magic string to recognize them later. - for (String package in transitiveDependenciesAsList) { + for (final String package in transitiveDependenciesAsList) { transitiveDependencyOutput.add(computeTransitiveDependencyLineFor(package)); } - for (String package in transitiveDevDependenciesAsList) { + for (final String package in transitiveDevDependenciesAsList) { transitiveDevDependencyOutput.add(computeTransitiveDependencyLineFor(package)); } @@ -1148,10 +1148,10 @@ String _generateFakePubspec(Iterable dependencies) { if (_kManuallyPinnedDependencies.isNotEmpty) { globals.printStatus('WARNING: the following packages use hard-coded version constraints:'); final Set allTransitive = { - for (PubspecDependency dependency in dependencies) + for (final PubspecDependency dependency in dependencies) dependency.name, }; - for (String package in _kManuallyPinnedDependencies.keys) { + for (final String package in _kManuallyPinnedDependencies.keys) { // Don't add pinned dependency if it is not in the set of all transitive dependencies. if (!allTransitive.contains(package)) { globals.printStatus('Skipping $package because it was not transitive'); @@ -1162,7 +1162,7 @@ String _generateFakePubspec(Iterable dependencies) { globals.printStatus(' - $package: $version'); } } - for (PubspecDependency dependency in dependencies) { + for (final PubspecDependency dependency in dependencies) { if (!dependency.pointsToSdk) { dependency.describeForFakePubspec(result, overrides); } @@ -1256,7 +1256,7 @@ class PubDependencyTree { // because they were omitted from pubspec.yaml used for 'pub upgrade' run. return; } - for (String dependency in _dependencyTree[package]) { + for (final String dependency in _dependencyTree[package]) { if (!seen.contains(dependency)) { if (!exclude.contains(dependency)) { yield dependency; @@ -1279,7 +1279,7 @@ String _computeChecksum(Iterable names, String getVersion(String name)) int lowerCheck = 0; int upperCheck = 0; final List sortedNames = names.toList()..sort(); - for (String name in sortedNames) { + for (final String name in sortedNames) { final String version = getVersion(name); assert(version != ''); if (version == null) { @@ -1287,7 +1287,7 @@ String _computeChecksum(Iterable names, String getVersion(String name)) } final String value = '$name: $version'; // Each code unit is 16 bits. - for (int codeUnit in value.codeUnits) { + for (final int codeUnit in value.codeUnits) { final int upper = codeUnit >> 8; final int lower = codeUnit & 0xFF; lowerCheck = (lowerCheck + upper) % 255; diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart index 30a03bbf6b5..af7ce54acdf 100644 --- a/packages/flutter_tools/lib/src/compile.dart +++ b/packages/flutter_tools/lib/src/compile.dart @@ -198,7 +198,7 @@ class PackageUriMapper { PackageUriMapper(String scriptPath, String packagesPath, String fileSystemScheme, List fileSystemRoots) { final Map packageMap = PackageMap(globals.fs.path.absolute(packagesPath)).map; final String scriptUri = Uri.file(scriptPath, windows: globals.platform.isWindows).toString(); - for (String packageName in packageMap.keys) { + for (final String packageName in packageMap.keys) { final String prefix = packageMap[packageName].toString(); // Only perform a multi-root mapping if there are multiple roots. if (fileSystemScheme != null @@ -227,7 +227,7 @@ class PackageUriMapper { return null; } final String scriptUri = Uri.file(scriptPath, windows: globals.platform.isWindows).toString(); - for (String uriPrefix in _uriPrefixes) { + for (final String uriPrefix in _uriPrefixes) { if (scriptUri.startsWith(uriPrefix)) { return Uri.parse('package:$_packageName/${scriptUri.substring(uriPrefix.length)}'); } @@ -314,7 +314,7 @@ class KernelCompiler { sdkRoot, '--target=$targetModel', '-Ddart.developer.causal_async_stacks=$causalAsyncStacks', - for (Object dartDefine in dartDefines) + for (final Object dartDefine in dartDefines) '-D$dartDefine', ..._buildModeOptions(buildMode), if (trackWidgetCreation) '--track-widget-creation', @@ -336,7 +336,7 @@ class KernelCompiler { depFilePath, ], if (fileSystemRoots != null) - for (String root in fileSystemRoots) ...[ + for (final String root in fileSystemRoots) ...[ '--filesystem-root', root, ], @@ -608,7 +608,7 @@ class DefaultResidentCompiler implements ResidentCompiler { : ''; _server.stdin.writeln('recompile $mainUri$inputKey'); globals.printTrace('<- recompile $mainUri$inputKey'); - for (Uri fileUri in request.invalidatedFiles) { + for (final Uri fileUri in request.invalidatedFiles) { _server.stdin.writeln(_mapFileUri(fileUri.toString(), packageUriMapper)); globals.printTrace('${_mapFileUri(fileUri.toString(), packageUriMapper)}'); } @@ -651,7 +651,7 @@ class DefaultResidentCompiler implements ResidentCompiler { '--incremental', '--target=$targetModel', '-Ddart.developer.causal_async_stacks=$causalAsyncStacks', - for (Object dartDefine in dartDefines) + for (final Object dartDefine in dartDefines) '-D$dartDefine', if (outputPath != null) ...[ '--output-dill', @@ -667,7 +667,7 @@ class DefaultResidentCompiler implements ResidentCompiler { ..._buildModeOptions(buildMode), if (trackWidgetCreation) '--track-widget-creation', if (fileSystemRoots != null) - for (String root in fileSystemRoots) ...[ + for (final String root in fileSystemRoots) ...[ '--filesystem-root', root, ], @@ -824,7 +824,7 @@ class DefaultResidentCompiler implements ResidentCompiler { } if (fileSystemRoots != null) { - for (String root in fileSystemRoots) { + for (final String root in fileSystemRoots) { if (filename.startsWith(root)) { return Uri( scheme: fileSystemScheme, path: filename.substring(root.length)) diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 375fdd38fa1..a2a5c4e6361 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -29,7 +29,7 @@ Pub get pub => context.get(); // We have server-side tooling that assumes the values are consistent. class PubContext { PubContext._(this._values) { - for (String item in _values) { + for (final String item in _values) { if (!_validContext.hasMatch(item)) { throw ArgumentError.value( _values, 'value', 'Must match RegExp ${_validContext.pattern}'); diff --git a/packages/flutter_tools/lib/src/desktop_device.dart b/packages/flutter_tools/lib/src/desktop_device.dart index 0922824a4c1..65a2339001a 100644 --- a/packages/flutter_tools/lib/src/desktop_device.dart +++ b/packages/flutter_tools/lib/src/desktop_device.dart @@ -130,7 +130,7 @@ abstract class DesktopDevice extends Device { bool succeeded = true; // Walk a copy of _runningProcesses, since the exit handler removes from the // set. - for (Process process in Set.from(_runningProcesses)) { + for (final Process process in Set.from(_runningProcesses)) { succeeded &= process.kill(); } return succeeded; diff --git a/packages/flutter_tools/lib/src/device.dart b/packages/flutter_tools/lib/src/device.dart index d7ac1514be4..9109845151a 100644 --- a/packages/flutter_tools/lib/src/device.dart +++ b/packages/flutter_tools/lib/src/device.dart @@ -118,7 +118,7 @@ class DeviceManager { } // Match on a id or name starting with [deviceId]. - for (Device device in devices.where(startsWithDeviceId)) { + for (final Device device in devices.where(startsWithDeviceId)) { yield device; } } @@ -136,8 +136,8 @@ class DeviceManager { /// Return the list of all connected devices. Stream getAllConnectedDevices() async* { - for (DeviceDiscovery discoverer in _platformDiscoverers) { - for (Device device in await discoverer.devices) { + for (final DeviceDiscovery discoverer in _platformDiscoverers) { + for (final Device device in await discoverer.devices) { yield device; } } @@ -151,7 +151,7 @@ class DeviceManager { /// Get diagnostics about issues with any connected devices. Future> getDeviceDiagnostics() async { return [ - for (DeviceDiscovery discoverer in _platformDiscoverers) + for (final DeviceDiscovery discoverer in _platformDiscoverers) ...await discoverer.getDiagnostics(), ]; } @@ -178,7 +178,7 @@ class DeviceManager { // compilers, and web requires an entirely different resident runner. if (hasSpecifiedAllDevices) { devices = [ - for (Device device in devices) + for (final Device device in devices) if (await device.targetPlatform != TargetPlatform.fuchsia_arm64 && await device.targetPlatform != TargetPlatform.fuchsia_x64 && await device.targetPlatform != TargetPlatform.web_javascript) @@ -191,7 +191,7 @@ class DeviceManager { // 'android' folder then don't attempt to launch with an Android device. if (devices.length > 1 && !hasSpecifiedDeviceId) { devices = [ - for (Device device in devices) + for (final Device device in devices) if (isDeviceSupportedForProject(device, flutterProject)) device, ]; @@ -460,7 +460,7 @@ abstract class Device { // Extract device information final List> table = >[]; - for (Device device in devices) { + for (final Device device in devices) { String supportIndicator = device.isSupported() ? '' : ' (unsupported)'; final TargetPlatform targetPlatform = await device.targetPlatform; if (await device.isLocalEmulator) { @@ -478,12 +478,12 @@ abstract class Device { // Calculate column widths final List indices = List.generate(table[0].length - 1, (int i) => i); List widths = indices.map((int i) => 0).toList(); - for (List row in table) { + for (final List row in table) { widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList(); } // Join columns into lines of text - for (List row in table) { + for (final List row in table) { yield indices.map((int i) => row[i].padRight(widths[i])).join(' • ') + ' • ${row.last}'; } } diff --git a/packages/flutter_tools/lib/src/doctor.dart b/packages/flutter_tools/lib/src/doctor.dart index ccaf6902165..366e2f1b885 100644 --- a/packages/flutter_tools/lib/src/doctor.dart +++ b/packages/flutter_tools/lib/src/doctor.dart @@ -147,7 +147,7 @@ class Doctor { /// Return a list of [ValidatorTask] objects and starts validation on all /// objects in [validators]. List startValidatorTasks() => [ - for (DoctorValidator validator in validators) + for (final DoctorValidator validator in validators) ValidatorTask( validator, // We use an asyncGuard() here to be absolutely certain that @@ -178,7 +178,7 @@ class Doctor { bool missingComponent = false; bool sawACrash = false; - for (DoctorValidator validator in validators) { + for (final DoctorValidator validator in validators) { final StringBuffer lineBuffer = StringBuffer(); ValidationResult result; try { @@ -248,7 +248,7 @@ class Doctor { bool doctorResult = true; int issues = 0; - for (ValidatorTask validatorTask in startValidatorTasks()) { + for (final ValidatorTask validatorTask in startValidatorTasks()) { final DoctorValidator validator = validatorTask.validator; final Status status = Status.withSpinner( timeout: timeoutConfiguration.fastOperation, @@ -291,12 +291,12 @@ class Doctor { hangingIndent: result.leadingBox.length + 1); } - for (ValidationMessage message in result.messages) { + for (final ValidationMessage message in result.messages) { if (message.type != ValidationMessageType.information || verbose == true) { int hangingIndent = 2; int indent = 4; final String indicator = showColor ? message.coloredIndicator : message.indicator; - for (String line in '$indicator ${message.message}'.split('\n')) { + for (final String line in '$indicator ${message.message}'.split('\n')) { globals.printStatus(line, hangingIndent: hangingIndent, indent: indent, emphasis: true); // Only do hanging indent for the first line. hangingIndent = 0; @@ -402,7 +402,7 @@ class GroupedValidator extends DoctorValidator { @override Future validate() async { final List tasks = [ - for (DoctorValidator validator in subValidators) + for (final DoctorValidator validator in subValidators) ValidatorTask( validator, asyncGuard(() => validator.validate()), @@ -410,7 +410,7 @@ class GroupedValidator extends DoctorValidator { ]; final List results = []; - for (ValidatorTask subValidator in tasks) { + for (final ValidatorTask subValidator in tasks) { _currentSlowWarning = subValidator.validator.slowWarning; try { results.add(await subValidator.result); @@ -429,7 +429,7 @@ class GroupedValidator extends DoctorValidator { final List mergedMessages = []; String statusInfo; - for (ValidationResult result in results) { + for (final ValidationResult result in results) { statusInfo ??= result.statusInfo; switch (result.type) { case ValidationType.installed: @@ -753,7 +753,7 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator { validators.add(validator); } - for (FileSystemEntity dir in globals.fs.directory(homeDirPath).listSync()) { + for (final FileSystemEntity dir in globals.fs.directory(homeDirPath).listSync()) { if (dir is Directory) { final String name = globals.fs.path.basename(dir.path); IntelliJValidator._idToTitle.forEach((String id, String title) { @@ -808,10 +808,10 @@ class IntelliJValidatorOnMac extends IntelliJValidator { .map>((Directory dir) => dir.existsSync() ? dir.listSync() : []) .expand((List mappedDirs) => mappedDirs) .whereType(); - for (Directory dir in installDirs) { + for (final Directory dir in installDirs) { checkForIntelliJ(dir); if (!dir.path.endsWith('.app')) { - for (FileSystemEntity subdir in dir.listSync()) { + for (final FileSystemEntity subdir in dir.listSync()) { if (subdir is Directory) { checkForIntelliJ(subdir); } diff --git a/packages/flutter_tools/lib/src/emulator.dart b/packages/flutter_tools/lib/src/emulator.dart index d29f2812aea..3cfcac6048b 100644 --- a/packages/flutter_tools/lib/src/emulator.dart +++ b/packages/flutter_tools/lib/src/emulator.dart @@ -250,7 +250,7 @@ abstract class Emulator { // Extract emulators information final List> table = >[ - for (Emulator emulator in emulators) + for (final Emulator emulator in emulators) [ emulator.id ?? '', emulator.name ?? '', @@ -262,7 +262,7 @@ abstract class Emulator { // Calculate column widths final List indices = List.generate(table[0].length - 1, (int i) => i); List widths = indices.map((int i) => 0).toList(); - for (List row in table) { + for (final List row in table) { widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList(); } diff --git a/packages/flutter_tools/lib/src/flutter_manifest.dart b/packages/flutter_tools/lib/src/flutter_manifest.dart index f3351a322ff..36c25efecef 100644 --- a/packages/flutter_tools/lib/src/flutter_manifest.dart +++ b/packages/flutter_tools/lib/src/flutter_manifest.dart @@ -197,7 +197,7 @@ class FlutterManifest { return const []; } final List results = []; - for (Object asset in assets) { + for (final Object asset in assets) { if (asset is! String || asset == null || asset == '') { globals.printError('Asset manifest contains a null or empty uri.'); continue; @@ -225,7 +225,7 @@ class FlutterManifest { } final List fonts = []; - for (Map fontFamily in _rawFontsDescriptor) { + for (final Map fontFamily in _rawFontsDescriptor) { final YamlList fontFiles = fontFamily['fonts'] as YamlList; final String familyName = fontFamily['family'] as String; if (familyName == null) { @@ -238,7 +238,7 @@ class FlutterManifest { } final List fontAssets = []; - for (Map fontFile in fontFiles.cast>()) { + for (final Map fontFile in fontFiles.cast>()) { final String asset = fontFile['asset'] as String; if (asset == null) { globals.printError('Warning: Missing asset in fonts for $familyName', emphasis: true); @@ -431,7 +431,7 @@ void _validateFonts(YamlList fonts, List errors) { continue; } final YamlMap fontMap = fontListEntry as YamlMap; - for (dynamic key in fontMap.keys.where((dynamic key) => key != 'family' && key != 'fonts')) { + for (final dynamic key in fontMap.keys.where((dynamic key) => key != 'family' && key != 'fonts')) { errors.add('Unexpected child "$key" found under "fonts".'); } if (fontMap['family'] != null && fontMap['family'] is! String) { diff --git a/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart b/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart index 24f14196ef7..9ccc04c4896 100644 --- a/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart +++ b/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart @@ -148,7 +148,7 @@ Future _buildAssets( await destFile.create(recursive: true); final IOSink outFile = destFile.openWrite(); - for (String path in assets.entries.keys) { + for (final String path in assets.entries.keys) { outFile.write('data/$appName/$path=$assetDir/$path\n'); } await outFile.flush(); diff --git a/packages/flutter_tools/lib/src/fuchsia/fuchsia_device.dart b/packages/flutter_tools/lib/src/fuchsia/fuchsia_device.dart index 5ae5a89c205..21e1fbe398f 100644 --- a/packages/flutter_tools/lib/src/fuchsia/fuchsia_device.dart +++ b/packages/flutter_tools/lib/src/fuchsia/fuchsia_device.dart @@ -164,7 +164,7 @@ class FuchsiaDevices extends PollingDeviceDiscovery { @visibleForTesting List parseListDevices(String text) { final List devices = []; - for (String rawLine in text.trim().split('\n')) { + for (final String rawLine in text.trim().split('\n')) { final String line = rawLine.trim(); // ['ip', 'device name'] final List words = line.split(' '); @@ -501,7 +501,7 @@ class FuchsiaDevice extends Device { return null; } final List ports = []; - for (String path in findOutput.split('\n')) { + for (final String path in findOutput.split('\n')) { if (path == '') { continue; } @@ -512,7 +512,7 @@ class FuchsiaDevice extends Device { return null; } final String lsOutput = lsResult.stdout; - for (String line in lsOutput.split('\n')) { + for (final String line in lsOutput.split('\n')) { if (line == '') { continue; } @@ -557,7 +557,7 @@ class FuchsiaDevice extends Device { // TODO(jonahwilliams): replacing this with the hub will require an update // to the flutter_runner. Future findIsolatePort(String isolateName, List ports) async { - for (int port in ports) { + for (final int port in ports) { try { // Note: The square-bracket enclosure for using the IPv6 loopback // didn't appear to work, but when assigning to the IPv4 loopback device, @@ -567,7 +567,7 @@ class FuchsiaDevice extends Device { final VMService vmService = await VMService.connect(uri); await vmService.getVM(); await vmService.refreshViews(); - for (FlutterView flutterView in vmService.vm.views) { + for (final FlutterView flutterView in vmService.vm.views) { if (flutterView.uiIsolate == null) { continue; } @@ -647,7 +647,7 @@ class FuchsiaIsolateDiscoveryProtocol { Future _findIsolate() async { final List ports = await _device.servicePorts(); - for (int port in ports) { + for (final int port in ports) { VMService service; if (_ports.containsKey(port)) { service = _ports[port]; @@ -664,7 +664,7 @@ class FuchsiaIsolateDiscoveryProtocol { } await service.getVM(); await service.refreshViews(); - for (FlutterView flutterView in service.vm.views) { + for (final FlutterView flutterView in service.vm.views) { if (flutterView.uiIsolate == null) { continue; } @@ -753,7 +753,7 @@ class _FuchsiaPortForwarder extends DevicePortForwarder { @override Future dispose() async { - for (ForwardedPort port in forwardedPorts) { + for (final ForwardedPort port in forwardedPorts) { await unforward(port); } } diff --git a/packages/flutter_tools/lib/src/fuchsia/tiles_ctl.dart b/packages/flutter_tools/lib/src/fuchsia/tiles_ctl.dart index 5357a9f5545..21ab56f3b46 100644 --- a/packages/flutter_tools/lib/src/fuchsia/tiles_ctl.dart +++ b/packages/flutter_tools/lib/src/fuchsia/tiles_ctl.dart @@ -26,7 +26,7 @@ class FuchsiaTilesCtl { globals.printTrace('tiles_ctl is not running'); return -1; } - for (MapEntry entry in runningApps.entries) { + for (final MapEntry entry in runningApps.entries) { if (entry.value.contains('$appName#meta')) { return entry.key; } @@ -70,7 +70,7 @@ class FuchsiaTilesCtl { return null; } // Find lines beginning with 'Tile' - for (String line in result.stdout.split('\n')) { + for (final String line in result.stdout.split('\n')) { final List words = line.split(' '); if (words.isNotEmpty && words[0] == 'Tile') { final int key = int.tryParse(words[2]); diff --git a/packages/flutter_tools/lib/src/intellij/intellij.dart b/packages/flutter_tools/lib/src/intellij/intellij.dart index aa2fd203161..48a9a50d753 100644 --- a/packages/flutter_tools/lib/src/intellij/intellij.dart +++ b/packages/flutter_tools/lib/src/intellij/intellij.dart @@ -22,7 +22,7 @@ class IntelliJPlugins { String title, { Version minVersion, }) { - for (String packageName in packageNames) { + for (final String packageName in packageNames) { if (!_hasPackage(packageName)) { continue; } diff --git a/packages/flutter_tools/lib/src/ios/devices.dart b/packages/flutter_tools/lib/src/ios/devices.dart index 5b5fd275f21..c9b43412890 100644 --- a/packages/flutter_tools/lib/src/ios/devices.dart +++ b/packages/flutter_tools/lib/src/ios/devices.dart @@ -660,7 +660,7 @@ class IOSDeviceLogReader extends DeviceLogReader { @override void dispose() { - for (StreamSubscription loggingSubscription in _loggingSubscriptions) { + for (final StreamSubscription loggingSubscription in _loggingSubscriptions) { loggingSubscription.cancel(); } _idevicesyslogProcess?.kill(); @@ -747,7 +747,7 @@ class IOSDevicePortForwarder extends DevicePortForwarder { @override Future dispose() async { - for (ForwardedPort forwardedPort in _forwardedPorts) { + for (final ForwardedPort forwardedPort in _forwardedPorts) { forwardedPort.dispose(); } } diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index 7974313e3f5..a220b42f4a1 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -371,7 +371,7 @@ Future buildXcodeProject({ } if (autoSigningConfigs != null) { - for (MapEntry signingConfig in autoSigningConfigs.entries) { + for (final MapEntry signingConfig in autoSigningConfigs.entries) { buildCommands.add('${signingConfig.key}=${signingConfig.value}'); } buildCommands.add('-allowProvisioningUpdates'); @@ -379,7 +379,7 @@ Future buildXcodeProject({ } final List contents = app.project.hostAppRoot.listSync(); - for (FileSystemEntity entity in contents) { + for (final FileSystemEntity entity in contents) { if (globals.fs.path.extension(entity.path) == '.xcworkspace') { buildCommands.addAll([ '-workspace', globals.fs.path.basename(entity.path), @@ -426,7 +426,7 @@ Future buildXcodeProject({ Future listenToScriptOutputLine() async { final List lines = await scriptOutputPipeFile.readAsLines(); - for (String line in lines) { + for (final String line in lines) { if (line == 'done' || line == 'all done') { buildSubStatus?.stop(); buildSubStatus = null; diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index 748d1dcc87b..72b7aa61cad 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -112,10 +112,10 @@ class SimControl { final Map devicesSection = await _list(SimControlListSection.devices); - for (String deviceCategory in devicesSection.keys) { + for (final String deviceCategory in devicesSection.keys) { final Object devicesData = devicesSection[deviceCategory]; if (devicesData != null && devicesData is List) { - for (Map data in devicesData.map>(castStringKeyedMap)) { + for (final Map data in devicesData.map>(castStringKeyedMap)) { devices.add(SimDevice(deviceCategory, data)); } } @@ -809,7 +809,7 @@ class _IOSSimulatorDevicePortForwarder extends DevicePortForwarder { @override Future dispose() async { - for (ForwardedPort port in _ports) { + for (final ForwardedPort port in _ports) { await unforward(port); } } diff --git a/packages/flutter_tools/lib/src/ios/xcodeproj.dart b/packages/flutter_tools/lib/src/ios/xcodeproj.dart index ff966cbdda7..09b50ca1bd5 100644 --- a/packages/flutter_tools/lib/src/ios/xcodeproj.dart +++ b/packages/flutter_tools/lib/src/ios/xcodeproj.dart @@ -106,7 +106,7 @@ void _updateGeneratedEnvironmentVariablesScript({ localsBuffer.writeln('#!/bin/sh'); localsBuffer.writeln('# This is a generated file; do not edit or check into version control.'); - for (String line in xcodeBuildSettings) { + for (final String line in xcodeBuildSettings) { localsBuffer.writeln('export "$line"'); } @@ -372,7 +372,7 @@ List environmentVariablesAsXcodeBuildSettings() { Map parseXcodeBuildSettings(String showBuildSettingsOutput) { final Map settings = {}; - for (Match match in showBuildSettingsOutput.split('\n').map(_settingExpr.firstMatch)) { + for (final Match match in showBuildSettingsOutput.split('\n').map(_settingExpr.firstMatch)) { if (match != null) { settings[match[1]] = match[2]; } @@ -402,7 +402,7 @@ class XcodeProjectInfo { final List buildConfigurations = []; final List schemes = []; List collector; - for (String line in output.split('\n')) { + for (final String line in output.split('\n')) { if (line.isEmpty) { collector = null; continue; @@ -454,7 +454,7 @@ class XcodeProjectInfo { /// regard to case. bool hasBuildConfiguratinForBuildMode(String buildMode) { buildMode = buildMode.toLowerCase(); - for (String name in buildConfigurations) { + for (final String name in buildConfigurations) { if (name.toLowerCase() == buildMode) { return true; } diff --git a/packages/flutter_tools/lib/src/linux/makefile.dart b/packages/flutter_tools/lib/src/linux/makefile.dart index 3569082b7ab..94331ac1d97 100644 --- a/packages/flutter_tools/lib/src/linux/makefile.dart +++ b/packages/flutter_tools/lib/src/linux/makefile.dart @@ -11,7 +11,7 @@ const String _kBinaryNameVariable = 'BINARY_NAME='; /// /// Returns `null` if it cannot be found. String makefileExecutableName(LinuxProject project) { - for (String line in project.makeFile.readAsLinesSync()) { + for (final String line in project.makeFile.readAsLinesSync()) { if (line.startsWith(_kBinaryNameVariable)) { return line.split(_kBinaryNameVariable).last.trim(); } diff --git a/packages/flutter_tools/lib/src/mdns_discovery.dart b/packages/flutter_tools/lib/src/mdns_discovery.dart index 033e0977039..dea4976803a 100644 --- a/packages/flutter_tools/lib/src/mdns_discovery.dart +++ b/packages/flutter_tools/lib/src/mdns_discovery.dart @@ -75,7 +75,7 @@ class MDnsObservatoryDiscovery { String domainName; if (applicationId != null) { - for (String name in uniqueDomainNames) { + for (final String name in uniqueDomainNames) { if (name.toLowerCase().startsWith(applicationId.toLowerCase())) { domainName = name; break; @@ -206,10 +206,10 @@ class MDnsObservatoryDiscovery { } void _logInterfaces(List interfaces) { - for (NetworkInterface interface in interfaces) { + for (final NetworkInterface interface in interfaces) { if (globals.logger.isVerbose) { globals.printTrace('Found interface "${interface.name}":'); - for (InternetAddress address in interface.addresses) { + for (final InternetAddress address in interface.addresses) { final String linkLocal = address.isLinkLocal ? 'link local' : ''; globals.printTrace('\tBound address: "${address.address}" $linkLocal'); } diff --git a/packages/flutter_tools/lib/src/plugins.dart b/packages/flutter_tools/lib/src/plugins.dart index 22f506b790e..cd7eb4361dc 100644 --- a/packages/flutter_tools/lib/src/plugins.dart +++ b/packages/flutter_tools/lib/src/plugins.dart @@ -321,10 +321,10 @@ bool _writeFlutterPluginsList(FlutterProject project, List plugins) { final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n'); final Set pluginNames = {}; - for (Plugin plugin in plugins) { + for (final Plugin plugin in plugins) { pluginNames.add(plugin.name); } - for (Plugin plugin in plugins) { + for (final Plugin plugin in plugins) { flutterPluginsBuffer.write('${plugin.name}=${escapePath(plugin.path)}\n'); directAppDependencies.add({ 'name': plugin.name, @@ -439,7 +439,7 @@ public final class GeneratedPluginRegistrant { List> _extractPlatformMaps(List plugins, String type) { final List> pluginConfigs = >[]; - for (Plugin p in plugins) { + for (final Plugin p in plugins) { final PluginPlatform platformPlugin = p.platforms[type]; if (platformPlugin != null) { pluginConfigs.add(platformPlugin.toMap()); @@ -484,7 +484,7 @@ Future _writeAndroidPluginRegistrant(FlutterProject project, List templateContext['needsShim'] = false; // If a plugin is using an embedding version older than 2.0 and the app is using 2.0, // then add shim for the old plugins. - for (Map plugin in androidPlugins) { + for (final Map plugin in androidPlugins) { if (plugin['supportsEmbeddingV1'] as bool && !(plugin['supportsEmbeddingV2'] as bool)) { templateContext['needsShim'] = true; if (project.isModule) { @@ -504,7 +504,7 @@ Future _writeAndroidPluginRegistrant(FlutterProject project, List break; case AndroidEmbeddingVersion.v1: default: - for (Map plugin in androidPlugins) { + for (final Map plugin in androidPlugins) { if (!(plugin['supportsEmbeddingV1'] as bool) && plugin['supportsEmbeddingV2'] as bool) { throwToolExit( 'The plugin `${plugin['name']}` requires your app to be migrated to ' diff --git a/packages/flutter_tools/lib/src/project.dart b/packages/flutter_tools/lib/src/project.dart index 234a266aa6b..6d14011e9c9 100644 --- a/packages/flutter_tools/lib/src/project.dart +++ b/packages/flutter_tools/lib/src/project.dart @@ -699,7 +699,7 @@ class AndroidProject { throwToolExit('Error reading $appManifestFile even though it exists. ' 'Please ensure that you have read permission to this file and try again.'); } - for (xml.XmlElement metaData in document.findAllElements('meta-data')) { + for (final xml.XmlElement metaData in document.findAllElements('meta-data')) { final String name = metaData.getAttribute('android:name'); if (name == 'flutterEmbedding') { final String embeddingVersionString = metaData.getAttribute('android:value'); @@ -764,7 +764,7 @@ Match _firstMatchInFile(File file, RegExp regExp) { if (!file.existsSync()) { return null; } - for (String line in file.readAsLinesSync()) { + for (final String line in file.readAsLinesSync()) { final Match match = regExp.firstMatch(line); if (match != null) { return match; diff --git a/packages/flutter_tools/lib/src/protocol_discovery.dart b/packages/flutter_tools/lib/src/protocol_discovery.dart index 6133048b36f..a13878e47e4 100644 --- a/packages/flutter_tools/lib/src/protocol_discovery.dart +++ b/packages/flutter_tools/lib/src/protocol_discovery.dart @@ -157,7 +157,7 @@ class _BufferedStreamController { StreamController get _streamController { _streamControllerInstance ??= StreamController.broadcast(onListen: () { - for (dynamic event in _events) { + for (final dynamic event in _events) { assert(T is! List); if (event is T) { _streamControllerInstance.add(event); diff --git a/packages/flutter_tools/lib/src/proxy_validator.dart b/packages/flutter_tools/lib/src/proxy_validator.dart index 3a8931e43a8..95896f2c111 100644 --- a/packages/flutter_tools/lib/src/proxy_validator.dart +++ b/packages/flutter_tools/lib/src/proxy_validator.dart @@ -34,7 +34,7 @@ class ProxyValidator extends DoctorValidator { messages.add(ValidationMessage.hint('NO_PROXY is not set')); } else { messages.add(ValidationMessage('NO_PROXY is $_noProxy')); - for (String host in const ['127.0.0.1', 'localhost']) { + for (final String host in const ['127.0.0.1', 'localhost']) { final ValidationMessage msg = _noProxy.contains(host) ? ValidationMessage('NO_PROXY contains $host') : ValidationMessage.hint('NO_PROXY does not contain $host'); diff --git a/packages/flutter_tools/lib/src/reporting/github_template.dart b/packages/flutter_tools/lib/src/reporting/github_template.dart index 367232ed1ea..ff35e3b2686 100644 --- a/packages/flutter_tools/lib/src/reporting/github_template.dart +++ b/packages/flutter_tools/lib/src/reporting/github_template.dart @@ -99,7 +99,7 @@ ${_projectMetadataInformation()} description.writeln('### Plugins'); // Format is: // camera=/path/to/.pub-cache/hosted/pub.dartlang.org/camera-0.5.7+2/ - for (String plugin in project.flutterPluginsFile.readAsLinesSync()) { + for (final String plugin in project.flutterPluginsFile.readAsLinesSync()) { final List pluginParts = plugin.split('='); if (pluginParts.length != 2) { continue; diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index 15e4b036b5c..9e4669447f8 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -249,7 +249,7 @@ class FlutterDevice { return; } final List> futures = >[]; - for (FlutterView view in flutterViews) { + for (final FlutterView view in flutterViews) { if (view != null && view.uiIsolate != null) { assert(!view.uiIsolate.pauseEvent.isPauseEvent); futures.add(view.uiIsolate.flutterExit()); @@ -283,7 +283,7 @@ class FlutterDevice { final Uri deviceEntryUri = devFS.baseUri.resolveUri(globals.fs.path.toUri(entryPath)); final Uri devicePackagesUri = devFS.baseUri.resolve('.packages'); return >>[ - for (FlutterView view in views) + for (final FlutterView view in views) view.uiIsolate.reloadSources( pause: pause, rootLibUri: deviceEntryUri, @@ -302,68 +302,68 @@ class FlutterDevice { } Future debugDumpApp() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterDebugDumpApp(); } } Future debugDumpRenderTree() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterDebugDumpRenderTree(); } } Future debugDumpLayerTree() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterDebugDumpLayerTree(); } } Future debugDumpSemanticsTreeInTraversalOrder() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterDebugDumpSemanticsTreeInTraversalOrder(); } } Future debugDumpSemanticsTreeInInverseHitTestOrder() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterDebugDumpSemanticsTreeInInverseHitTestOrder(); } } Future toggleDebugPaintSizeEnabled() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterToggleDebugPaintSizeEnabled(); } } Future toggleDebugCheckElevationsEnabled() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterToggleDebugCheckElevationsEnabled(); } } Future debugTogglePerformanceOverlayOverride() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterTogglePerformanceOverlayOverride(); } } Future toggleWidgetInspector() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterToggleWidgetInspector(); } } Future toggleProfileWidgetBuilds() async { - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterToggleProfileWidgetBuilds(); } } Future togglePlatform({ String from }) async { final String to = nextPlatform(from, featureFlags); - for (FlutterView view in views) { + for (final FlutterView view in views) { await view.uiIsolate.flutterPlatformOverride(to); } return to; @@ -578,7 +578,7 @@ final RegExp kAndroidQHttpConnectionClosedExp = RegExp(r'^HttpException\:.+\, ur /// Returns `true` if any of the devices is running Android Q. Future hasDeviceRunningAndroidQ(List flutterDevices) async { - for (FlutterDevice flutterDevice in flutterDevices) { + for (final FlutterDevice flutterDevice in flutterDevices) { final String sdkNameAndVersion = await flutterDevice.device.sdkNameAndVersion; if (sdkNameAndVersion != null && sdkNameAndVersion.startsWith('Android 10')) { return true; @@ -755,77 +755,77 @@ abstract class ResidentRunner { Future refreshViews() async { final List> futures = >[ - for (FlutterDevice device in flutterDevices) device.refreshViews(), + for (final FlutterDevice device in flutterDevices) device.refreshViews(), ]; await Future.wait(futures); } Future debugDumpApp() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugDumpApp(); } } Future debugDumpRenderTree() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugDumpRenderTree(); } } Future debugDumpLayerTree() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugDumpLayerTree(); } } Future debugDumpSemanticsTreeInTraversalOrder() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugDumpSemanticsTreeInTraversalOrder(); } } Future debugDumpSemanticsTreeInInverseHitTestOrder() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugDumpSemanticsTreeInInverseHitTestOrder(); } } Future debugToggleDebugPaintSizeEnabled() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.toggleDebugPaintSizeEnabled(); } } Future debugToggleDebugCheckElevationsEnabled() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.toggleDebugCheckElevationsEnabled(); } } Future debugTogglePerformanceOverlayOverride() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.debugTogglePerformanceOverlayOverride(); } } Future debugToggleWidgetInspector() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.toggleWidgetInspector(); } } Future debugToggleProfileWidgetBuilds() async { await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.toggleProfileWidgetBuilds(); } } @@ -845,7 +845,7 @@ abstract class ResidentRunner { if (supportsServiceProtocol && isRunningDebug) { await device.refreshViews(); try { - for (FlutterView view in device.views) { + for (final FlutterView view in device.views) { await view.uiIsolate.flutterDebugAllowBanner(false); } } catch (error) { @@ -859,7 +859,7 @@ abstract class ResidentRunner { } finally { if (supportsServiceProtocol && isRunningDebug) { try { - for (FlutterView view in device.views) { + for (final FlutterView view in device.views) { await view.uiIsolate.flutterDebugAllowBanner(true); } } catch (error) { @@ -882,7 +882,7 @@ abstract class ResidentRunner { await refreshViews(); final String from = await flutterDevices[0].views[0].uiIsolate.flutterPlatformOverride(); String to; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { to = await device.togglePlatform(from: from); } globals.printStatus('Switched operating system to $to'); @@ -913,7 +913,7 @@ abstract class ResidentRunner { _finished = Completer(); bool viewFound = false; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { await device.connect( reloadSources: reloadSources, restart: restart, @@ -935,7 +935,7 @@ abstract class ResidentRunner { } // Listen for service protocol connection to close. - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { // This hooks up callbacks for when the connection stops in the future. // We don't want to wait for them. We don't handle errors in those callbacks' // futures either because they just print to logger and is not critical. @@ -993,7 +993,7 @@ abstract class ResidentRunner { Future exitApp() async { final List> futures = >[ - for (FlutterDevice device in flutterDevices) device.exitApps(), + for (final FlutterDevice device in flutterDevices) device.exitApps(), ]; await Future.wait(futures); appFinished(); @@ -1116,7 +1116,7 @@ class TerminalHandler { /// Unregisters terminal signal and keystroke handlers. void stop() { assert(residentRunner.stayResident); - for (MapEntry entry in _signalTokens.entries) { + for (final MapEntry entry in _signalTokens.entries) { signals.removeHandler(entry.key, entry.value); } _signalTokens.clear(); @@ -1154,7 +1154,7 @@ class TerminalHandler { final List views = residentRunner.flutterDevices .expand((FlutterDevice d) => d.views).toList(); globals.printStatus('Connected ${pluralize('view', views.length)}:'); - for (FlutterView v in views) { + for (final FlutterView v in views) { globals.printStatus('${v.uiIsolate.name} (${v.uiIsolate.id})', indent: 2); } return true; @@ -1189,7 +1189,7 @@ class TerminalHandler { await residentRunner.exit(); return true; case 's': - for (FlutterDevice device in residentRunner.flutterDevices) { + for (final FlutterDevice device in residentRunner.flutterDevices) { if (device.device.supportsScreenshot) { await residentRunner.screenshot(device); } diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart index 02f95ae8f3c..12114527ca8 100644 --- a/packages/flutter_tools/lib/src/run_cold.dart +++ b/packages/flutter_tools/lib/src/run_cold.dart @@ -60,7 +60,7 @@ class ColdRunner extends ResidentRunner { } } - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final int result = await device.runCold( coldRunner: this, route: route, @@ -90,7 +90,7 @@ class ColdRunner extends ResidentRunner { globals.printTrace('Application running.'); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (device.vmService == null) { continue; } @@ -142,12 +142,12 @@ class ColdRunner extends ResidentRunner { } return 2; } - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { device.initLogReader(); } await refreshViews(); - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { globals.printTrace('Connected to $view.'); } } @@ -170,7 +170,7 @@ class ColdRunner extends ResidentRunner { @override Future cleanupAtFinish() async { - for (FlutterDevice flutterDevice in flutterDevices) { + for (final FlutterDevice flutterDevice in flutterDevices) { await flutterDevice.device.dispose(); } @@ -181,7 +181,7 @@ class ColdRunner extends ResidentRunner { void printHelp({ @required bool details }) { bool haveDetails = false; bool haveAnything = false; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final String dname = device.device.name; if (device.vmService != null) { globals.printStatus('An Observatory debugger and profiler on $dname is ' @@ -209,7 +209,7 @@ class ColdRunner extends ResidentRunner { @override Future preExit() async { - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { // If we're running in release mode, stop the app using the device logic. if (device.vmService == null) { await device.device.stopApp(device.package); diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index e8d933713a7..2eadea5a9f8 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -137,7 +137,7 @@ class HotRunner extends ResidentRunner { String klass, bool isStatic, ) async { - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (device.generator != null) { final CompilerOutput compilerOutput = await device.generator.compileExpression(expression, definitions, @@ -155,7 +155,7 @@ class HotRunner extends ResidentRunner { final Stopwatch stopwatch = Stopwatch()..start(); final UpdateFSReport results = UpdateFSReport(success: true); final List invalidated = [Uri.parse(libraryId)]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { results.incorporateResults(await device.updateDevFS( mainPath: mainPath, target: target, @@ -178,7 +178,7 @@ class HotRunner extends ResidentRunner { getReloadPath(fullRestart: false), from: projectRootPath, ); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final List>> reportFutures = device.reloadSources( entryPath, pause: false, ); @@ -190,8 +190,8 @@ class HotRunner extends ResidentRunner { return OperationResult(1, error.toString()); } - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { await view.uiIsolate.flutterFastReassemble(classId); } } @@ -227,7 +227,7 @@ class HotRunner extends ResidentRunner { return 2; } - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { device.initLogReader(); } try { @@ -257,13 +257,13 @@ class HotRunner extends ResidentRunner { } await refreshViews(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { // VM must have accepted the kernel binary, there will be no reload // report, so we let incremental compiler know that source code was accepted. if (device.generator != null) { device.generator.accept(); } - for (FlutterView view in device.views) { + for (final FlutterView view in device.views) { globals.printTrace('Connected to $view.'); } } @@ -330,7 +330,7 @@ class HotRunner extends ResidentRunner { firstBuildTime = DateTime.now(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final int result = await device.runHot( hotRunner: this, route: route, @@ -349,7 +349,7 @@ class HotRunner extends ResidentRunner { Future> _initDevFS() async { final String fsName = globals.fs.path.basename(projectRootPath); return [ - for (FlutterDevice device in flutterDevices) + for (final FlutterDevice device in flutterDevices) await device.setupDevFS( fsName, globals.fs.directory(projectRootPath), @@ -378,7 +378,7 @@ class HotRunner extends ResidentRunner { asyncScanning: hotRunnerConfig.asyncScanning, ); final UpdateFSReport results = UpdateFSReport(success: true); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { results.incorporateResults(await device.updateDevFS( mainPath: mainPath, target: target, @@ -397,14 +397,14 @@ class HotRunner extends ResidentRunner { } void _resetDirtyAssets() { - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { device.devFS.assetPathsToEvict.clear(); } } Future _cleanupDevFS() async { final List> futures = >[]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (device.devFS != null) { // Cleanup the devFS, but don't wait indefinitely. // We ignore any errors, because it's not clear what we would do anyway. @@ -426,7 +426,7 @@ class HotRunner extends ResidentRunner { Uri assetsDirectoryUri, ) { return Future.wait(>[ - for (FlutterView view in device.views) + for (final FlutterView view in device.views) view.runFromSource(entryUri, packagesUri, assetsDirectoryUri), ]); } @@ -434,7 +434,7 @@ class HotRunner extends ResidentRunner { Future _launchFromDevFS(String mainScript) async { final String entryUri = globals.fs.path.relative(mainScript, from: projectRootPath); final List> futures = >[]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final Uri deviceEntryUri = device.devFS.baseUri.resolveUri( globals.fs.path.toUri(entryUri)); final Uri devicePackagesUri = device.devFS.baseUri.resolve('.packages'); @@ -448,8 +448,8 @@ class HotRunner extends ResidentRunner { await Future.wait(futures); if (benchmarkMode) { futures.clear(); - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { futures.add(view.flushUIThreadTasks()); } } @@ -471,7 +471,7 @@ class HotRunner extends ResidentRunner { // compiler for full application recompilation on restart. final UpdateFSReport updatedDevFS = await _updateDevFS(fullRestart: true); if (!updatedDevFS.success) { - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (device.generator != null) { await device.generator.reject(); } @@ -479,7 +479,7 @@ class HotRunner extends ResidentRunner { return OperationResult(1, 'DevFS synchronization failed'); } _resetDirtyAssets(); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { // VM must have accepted the kernel binary, there will be no reload // report, so we let incremental compiler know that source code was accepted. if (device.generator != null) { @@ -488,8 +488,8 @@ class HotRunner extends ResidentRunner { } // Check if the isolate is paused and resume it. final List> futures = >[]; - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { if (view.uiIsolate == null) { continue; } @@ -522,12 +522,12 @@ class HotRunner extends ResidentRunner { // In benchmark mode, make sure all stream notifications have finished. if (benchmarkMode) { final List> isolateNotifications = >[]; - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { isolateNotifications.add( view.owner.vm.vmService.onIsolateEvent .then((Stream serviceEvents) async { - await for (ServiceEvent serviceEvent in serviceEvents) { + await for (final ServiceEvent serviceEvent in serviceEvents) { if (serviceEvent.owner.name.contains('_spawn') && serviceEvent.kind == ServiceEvent.kIsolateExit) { return; @@ -575,7 +575,7 @@ class HotRunner extends ResidentRunner { if (!(reloadReport['success'] as bool)) { if (printErrors) { globals.printError('Hot reload was rejected:'); - for (Map notice in reloadReport['details']['notices']) { + for (final Map notice in reloadReport['details']['notices']) { globals.printError('${notice['message']}'); } } @@ -747,8 +747,8 @@ class HotRunner extends ResidentRunner { String reason, void Function(String message) onSlow, }) async { - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { if (view.uiIsolate == null) { return OperationResult(2, 'Application isolate not found', fatal: true); } @@ -785,7 +785,7 @@ class HotRunner extends ResidentRunner { from: projectRootPath, ); final List> allReportsFutures = >[]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (_runningFromSnapshot) { // Asset directory has to be set only once when we switch from // running from snapshot to running from uploaded files. @@ -809,7 +809,7 @@ class HotRunner extends ResidentRunner { )); } final List reports = await Future.wait(allReportsFutures); - for (DeviceReloadReport report in reports) { + for (final DeviceReloadReport report in reports) { final Map reloadReport = report.reports[0]; if (!validateReloadReport(reloadReport)) { // Reload failed. @@ -859,10 +859,10 @@ class HotRunner extends ResidentRunner { final Stopwatch reassembleTimer = Stopwatch()..start(); // Reload the isolate. final List> allDevices = >[]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { globals.printTrace('Sending reload events to ${device.device.name}'); final List> futuresViews = >[]; - for (FlutterView view in device.views) { + for (final FlutterView view in device.views) { globals.printTrace('Sending reload event to "${view.uiIsolate.name}"'); futuresViews.add(view.uiIsolate.reload()); } @@ -878,8 +878,8 @@ class HotRunner extends ResidentRunner { final List reassembleViews = []; String serviceEventKind; int pausedIsolatesFound = 0; - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { // Check if the isolate is paused, and if so, don't reassemble. Ignore the // PostPauseEvent event - the client requesting the pause will resume the app. final ServiceEvent pauseEvent = view.uiIsolate.pauseEvent; @@ -910,7 +910,7 @@ class HotRunner extends ResidentRunner { globals.printTrace('Reassembling application'); bool failedReassemble = false; final List> futures = >[ - for (FlutterView view in reassembleViews) + for (final FlutterView view in reassembleViews) () async { try { await view.uiIsolate.flutterReassemble(); @@ -933,7 +933,7 @@ class HotRunner extends ResidentRunner { globals.printTrace('This is taking a long time; will now check for paused isolates.'); int postReloadPausedIsolatesFound = 0; String serviceEventKind; - for (FlutterView view in reassembleViews) { + for (final FlutterView view in reassembleViews) { await view.uiIsolate.reload(); final ServiceEvent pauseEvent = view.uiIsolate.pauseEvent; if (pauseEvent != null && pauseEvent.isPauseEvent) { @@ -1030,8 +1030,8 @@ class HotRunner extends ResidentRunner { } bool _isPaused() { - for (FlutterDevice device in flutterDevices) { - for (FlutterView view in device.views) { + for (final FlutterDevice device in flutterDevices) { + for (final FlutterView view in device.views) { if (view.uiIsolate != null) { final ServiceEvent pauseEvent = view.uiIsolate.pauseEvent; if (pauseEvent != null && pauseEvent.isPauseEvent) { @@ -1055,7 +1055,7 @@ class HotRunner extends ResidentRunner { TerminalColor.red, ); globals.printStatus(message); - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { final String dname = device.device.name; globals.printStatus('An Observatory debugger and profiler on $dname is ' 'available at: ${device.vmService.httpAddress}'); @@ -1073,7 +1073,7 @@ class HotRunner extends ResidentRunner { Future _evictDirtyAssets() { final List>> futures = >>[]; - for (FlutterDevice device in flutterDevices) { + for (final FlutterDevice device in flutterDevices) { if (device.devFS.assetPathsToEvict.isEmpty) { continue; } @@ -1081,7 +1081,7 @@ class HotRunner extends ResidentRunner { globals.printError('Application isolate not found for $device'); continue; } - for (String assetPath in device.devFS.assetPathsToEvict) { + for (final String assetPath in device.devFS.assetPathsToEvict) { futures.add(device.views.first.uiIsolate.flutterEvictAsset(assetPath)); } device.devFS.assetPathsToEvict.clear(); @@ -1109,7 +1109,7 @@ class HotRunner extends ResidentRunner { @override Future cleanupAtFinish() async { - for (FlutterDevice flutterDevice in flutterDevices) { + for (final FlutterDevice flutterDevice in flutterDevices) { await flutterDevice.device.dispose(); } await _cleanupDevFS(); @@ -1161,7 +1161,7 @@ class ProjectFileInvalidator { final Stopwatch stopwatch = Stopwatch()..start(); final List urisToScan = [ // Don't watch pub cache directories to speed things up a little. - for (Uri uri in urisToMonitor) + for (final Uri uri in urisToMonitor) if (_isNotInPubCache(uri)) uri, // We need to check the .packages file too since it is not used in compilation. diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index a04e4029241..0d81d6fb8f3 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -445,7 +445,7 @@ abstract class FlutterCommand extends Command { : null; if (argParser.options.containsKey(FlutterOptions.kEnableExperiment) && argResults[FlutterOptions.kEnableExperiment] != null) { - for (String expFlag in stringsArg(FlutterOptions.kEnableExperiment)) { + for (final String expFlag in stringsArg(FlutterOptions.kEnableExperiment)) { final String flag = '--enable-experiment=' + expFlag; if (extraFrontEndOptions != null) { extraFrontEndOptions += ',' + flag; @@ -743,7 +743,7 @@ mixin DeviceBasedDevelopmentArtifacts on FlutterCommand { final Set artifacts = { DevelopmentArtifact.universal, }; - for (Device device in devices) { + for (final Device device in devices) { final TargetPlatform targetPlatform = await device.targetPlatform; final DevelopmentArtifact developmentArtifact = _artifactFromTargetPlatform(targetPlatform); if (developmentArtifact != null) { diff --git a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart index ca6d67214d2..7731bd02298 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart @@ -206,7 +206,7 @@ class FlutterCommandRunner extends CommandRunner { } Command command = commands[error.commands.first]; - for (String commandName in error.commands.skip(1)) { + for (final String commandName in error.commands.skip(1)) { command = command.subcommands[commandName]; } @@ -386,7 +386,7 @@ class FlutterCommandRunner extends CommandRunner { tmpBasename = tmpBasename.substring(tmpBasename.indexOf('_') + 1); // Strip suffix for various archs. final List suffixes = ['_arm', '_arm64', '_x86', '_x64']; - for (String suffix in suffixes) { + for (final String suffix in suffixes) { tmpBasename = tmpBasename.replaceFirst(RegExp('$suffix\$'), ''); } return 'host_' + tmpBasename; diff --git a/packages/flutter_tools/lib/src/template.dart b/packages/flutter_tools/lib/src/template.dart index f47f450f984..e37fdddc501 100644 --- a/packages/flutter_tools/lib/src/template.dart +++ b/packages/flutter_tools/lib/src/template.dart @@ -33,7 +33,7 @@ class Template { final List templateFiles = templateSource.listSync(recursive: true); - for (FileSystemEntity entity in templateFiles) { + for (final FileSystemEntity entity in templateFiles) { if (entity is! File) { // We are only interesting in template *file* URIs. continue; diff --git a/packages/flutter_tools/lib/src/test/coverage_collector.dart b/packages/flutter_tools/lib/src/test/coverage_collector.dart index b9dad7274b8..2d8e6a8e906 100644 --- a/packages/flutter_tools/lib/src/test/coverage_collector.dart +++ b/packages/flutter_tools/lib/src/test/coverage_collector.dart @@ -188,7 +188,7 @@ Future> collect(Uri serviceUri, bool Function(String) libra Future> _getAllCoverage(VMService service, bool Function(String) libraryPredicate) async { await service.getVM(); final List> coverage = >[]; - for (Isolate isolateRef in service.vm.isolates) { + for (final Isolate isolateRef in service.vm.isolates) { await isolateRef.load(); final Map scriptList = await isolateRef.invokeRpcRaw('getScripts', params: {'isolateId': isolateRef.id}); final List> futures = >[]; @@ -204,7 +204,7 @@ Future> _getAllCoverage(VMService service, bool Function(St if (scriptList['scripts'] == null) { continue; } - for (Map script in scriptList['scripts']) { + for (final Map script in scriptList['scripts']) { if (!libraryPredicate(script['uri'] as String)) { continue; } @@ -243,9 +243,9 @@ void _buildCoverageMap( List> coverage, ) { final Map> hitMaps = >{}; - for (String scriptId in scripts.keys) { + for (final String scriptId in scripts.keys) { final Map sourceReport = sourceReports[scriptId]; - for (Map range in sourceReport['ranges']) { + for (final Map range in sourceReport['ranges']) { final Map coverage = castStringKeyedMap(range['coverage']); // Coverage reports may sometimes be null for a Script. if (coverage == null) { @@ -264,14 +264,14 @@ void _buildCoverageMap( continue; } if (hits != null) { - for (int hit in hits) { + for (final int hit in hits) { final int line = _lineAndColumn(hit, tokenPositions)[0]; final int current = hitMap[line] ?? 0; hitMap[line] = current + 1; } } if (misses != null) { - for (int miss in misses) { + for (final int miss in misses) { final int line = _lineAndColumn(miss, tokenPositions)[0]; hitMap[line] ??= 0; } diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 8b73b578ed3..c47af1efc3b 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -678,7 +678,7 @@ class FlutterPlatform extends PlatformPlugin { } finally { globals.printTrace('test $ourTestCount: cleaning up...'); // Finalizers are treated like a stack; run them in reverse order. - for (Finalizer finalizer in finalizers.reversed) { + for (final Finalizer finalizer in finalizers.reversed) { try { await finalizer(); } catch (error, stack) { @@ -850,7 +850,7 @@ class FlutterPlatform extends PlatformPlugin { void reportObservatoryUri(Uri uri), }) { const String observatoryString = 'Observatory listening on '; - for (Stream> stream in >>[ + for (final Stream> stream in >>[ process.stderr, process.stdout, ]) { diff --git a/packages/flutter_tools/lib/src/test/flutter_web_platform.dart b/packages/flutter_tools/lib/src/test/flutter_web_platform.dart index 7aa705b0555..c638f67f0ad 100644 --- a/packages/flutter_tools/lib/src/test/flutter_web_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_web_platform.dart @@ -440,7 +440,7 @@ class PathHandler { /// the longest matching prefix wins. void add(String path, shelf.Handler handler) { _Node node = _paths; - for (String component in p.url.split(path)) { + for (final String component in p.url.split(path)) { node = node.children.putIfAbsent(component, () => _Node()); } node.handler = handler; @@ -489,7 +489,7 @@ class BrowserManager { // Start this canceled because we don't want it to start ticking until we // get some response from the iframe. _timer = RestartableTimer(const Duration(seconds: 3), () { - for (RunnerSuiteController controller in _controllers) { + for (final RunnerSuiteController controller in _controllers) { controller.setDebugging(true); } }) @@ -503,7 +503,7 @@ class BrowserManager { if (!_closed) { _timer.reset(); } - for (RunnerSuiteController controller in _controllers) { + for (final RunnerSuiteController controller in _controllers) { controller.setDebugging(false); } @@ -933,7 +933,7 @@ void main() async { .transform(utf8.decoder) .transform(const LineSplitter()) .map(jsonDecode); - await for (Object command in commands) { + await for (final Object command in commands) { if (command is Map) { File imageFile = File(command['imageFile']); Uri goldenKey = Uri.parse(command['key']); diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index 593603df7f5..490cf504282 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart @@ -61,9 +61,9 @@ Future runTests( else ...['-r', 'compact'], '--concurrency=$concurrency', - for (String name in names) + for (final String name in names) ...['--name', name], - for (String plainName in plainNames) + for (final String plainName in plainNames) ...['--plain-name', plainName], '--test-randomize-ordering-seed=$randomSeed', ]; diff --git a/packages/flutter_tools/lib/src/tracing.dart b/packages/flutter_tools/lib/src/tracing.dart index 623a10d65af..020d06816a7 100644 --- a/packages/flutter_tools/lib/src/tracing.dart +++ b/packages/flutter_tools/lib/src/tracing.dart @@ -51,7 +51,7 @@ class Tracing { } }); bool done = false; - for (FlutterView view in vmService.vm.views) { + for (final FlutterView view in vmService.vm.views) { if (await view.uiIsolate.flutterAlreadyPaintedFirstUsefulFrame()) { done = true; break; diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart index 9d0450ecb52..99adc781dc3 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart @@ -856,7 +856,7 @@ class VM extends ServiceObjectOwner { void _removeDeadIsolates(List newIsolates) { // Build a set of new isolates. final Set newIsolateSet = {}; - for (Isolate iso in newIsolates) { + for (final Isolate iso in newIsolates) { newIsolateSet.add(iso.id); } diff --git a/packages/flutter_tools/lib/src/vscode/vscode.dart b/packages/flutter_tools/lib/src/vscode/vscode.dart index 64104931130..b11004656b1 100644 --- a/packages/flutter_tools/lib/src/vscode/vscode.dart +++ b/packages/flutter_tools/lib/src/vscode/vscode.dart @@ -204,7 +204,7 @@ class VsCode { final List results = []; - for (_VsCodeInstallLocation searchLocation in searchLocations) { + for (final _VsCodeInstallLocation searchLocation in searchLocations) { if (globals.fs.isDirectorySync(searchLocation.installPath)) { final String extensionDirectory = globals.fs.path.join(homeDirPath, searchLocation.extensionsFolder, 'extensions'); diff --git a/packages/flutter_tools/lib/src/web/compile.dart b/packages/flutter_tools/lib/src/web/compile.dart index 8f024d240e9..c0620314ee6 100644 --- a/packages/flutter_tools/lib/src/web/compile.dart +++ b/packages/flutter_tools/lib/src/web/compile.dart @@ -53,7 +53,7 @@ Future buildWeb( }, )); if (!result.success) { - for (ExceptionMeasurement measurement in result.exceptions.values) { + for (final ExceptionMeasurement measurement in result.exceptions.values) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: measurement.fatal ? measurement.stackTrace diff --git a/packages/flutter_tools/lib/src/web/devfs_web.dart b/packages/flutter_tools/lib/src/web/devfs_web.dart index c28815b4aff..e24ef5ec8b5 100644 --- a/packages/flutter_tools/lib/src/web/devfs_web.dart +++ b/packages/flutter_tools/lib/src/web/devfs_web.dart @@ -177,7 +177,7 @@ class WebAssetServer { final Uint8List codeBytes = codeFile.readAsBytesSync(); final Uint8List sourcemapBytes = sourcemapFile.readAsBytesSync(); final Map manifest = castStringKeyedMap(json.decode(manifestFile.readAsStringSync())); - for (String filePath in manifest.keys) { + for (final String filePath in manifest.keys) { if (filePath == null) { globals.printTrace('Invalid manfiest file: $filePath'); continue; diff --git a/packages/flutter_tools/lib/src/windows/windows_device.dart b/packages/flutter_tools/lib/src/windows/windows_device.dart index 1161d6d0c62..f7f0b65d0e0 100644 --- a/packages/flutter_tools/lib/src/windows/windows_device.dart +++ b/packages/flutter_tools/lib/src/windows/windows_device.dart @@ -93,7 +93,7 @@ List runningProcess(String processName) { if (result.exitCode != 0) { return null; } - for (String rawProcess in result.stdout.split('\n')) { + for (final String rawProcess in result.stdout.split('\n')) { final String process = rawProcess.trim(); if (!process.contains(processName)) { continue; diff --git a/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart index 52922ca1538..7565fa3a4d6 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart @@ -106,7 +106,7 @@ void main() { globals.fs.path.join('bin', 'cache', 'dart-sdk', 'bin', 'dart'), globals.fs.path.join('bin', 'cache', 'dart-sdk '), ]; - for (String dependency in dependencies) { + for (final String dependency in dependencies) { globals.fs.file(dependency).createSync(recursive: true); } diff --git a/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart index dc775570262..a9db5b9422b 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart @@ -31,7 +31,7 @@ void main() { globals.fs.path.join('usr', 'local', 'bin', 'adb'), globals.fs.path.join('Android', 'platform-tools', 'adb.exe'), ]; - for (String path in paths) { + for (final String path in paths) { globals.fs.file(path).createSync(recursive: true); } }, overrides: { diff --git a/packages/flutter_tools/test/commands.shard/hermetic/doctor_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/doctor_test.dart index 5b3e077dbac..a6ec89b8210 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/doctor_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/doctor_test.dart @@ -499,11 +499,11 @@ void main() { expect(await FlutterValidatorDoctor().diagnose(verbose: false), isTrue); final List statusLines = testLogger.statusText.split('\n'); - for (String msg in userMessages.flutterBinariesDoNotRun.split('\n')) { + for (final String msg in userMessages.flutterBinariesDoNotRun.split('\n')) { expect(statusLines, contains(contains(msg))); } if (globals.platform.isLinux) { - for (String msg in userMessages.flutterBinariesLinuxRepairCommands.split('\n')) { + for (final String msg in userMessages.flutterBinariesLinuxRepairCommands.split('\n')) { expect(statusLines, contains(contains(msg))); } } diff --git a/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart b/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart index 3e228685921..adda297cf66 100644 --- a/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart +++ b/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart @@ -29,7 +29,7 @@ void main() { return relativePath; }).toList(); final Map contents = {}; - for (String path in paths) { + for (final String path in paths) { final String absPath = globals.fs.path.join(tempPath, path); if (globals.fs.isDirectorySync(absPath)) { contents[path] = 'dir'; @@ -56,12 +56,12 @@ void main() { } void _populateDir(Map manifest) { - for (String key in manifest.keys) { + for (final String key in manifest.keys) { if (manifest[key] == 'dir') { tempDir.childDirectory(key)..createSync(recursive: true); } } - for (String key in manifest.keys) { + for (final String key in manifest.keys) { if (manifest[key] != 'dir') { tempDir.childFile(key) ..createSync(recursive: true) @@ -90,7 +90,7 @@ void main() { ...args, ]); - for (String path in expectedContents.keys) { + for (final String path in expectedContents.keys) { final String absPath = globals.fs.path.join(tempDir.absolute.path, path); expect(_fileOrDirectoryExists(globals.fs.path.join(dir.path, path)), true, reason: "$path doesn't exist"); @@ -99,7 +99,7 @@ void main() { reason: "$path contents don't match"); } } - for (String path in unexpectedPaths) { + for (final String path in unexpectedPaths) { expect(_fileOrDirectoryExists(globals.fs.path.join(dir.path, path)), false, reason: '$path exists'); } } diff --git a/packages/flutter_tools/test/commands.shard/permeable/analyze_once_test.dart b/packages/flutter_tools/test/commands.shard/permeable/analyze_once_test.dart index 9ff81a88efc..5d988d012c0 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/analyze_once_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/analyze_once_test.dart @@ -258,7 +258,7 @@ void assertContains(String text, List patterns) { if (patterns == null) { expect(text, isEmpty); } else { - for (String pattern in patterns) { + for (final String pattern in patterns) { expect(text, contains(pattern)); } } diff --git a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart index b1d284eca2d..049bec84687 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/create_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/create_test.dart @@ -645,7 +645,7 @@ void main() { expect(actualContents.contains('flutter_test.dart'), true); - for (FileSystemEntity file in projectDir.listSync(recursive: true)) { + for (final FileSystemEntity file in projectDir.listSync(recursive: true)) { if (file is File && file.path.endsWith('.dart')) { final String original = file.readAsStringSync(); @@ -737,7 +737,7 @@ void main() { expectExists('lib/main.dart'); expectExists('test/widget_test.dart'); - for (FileSystemEntity file in projectDir.listSync(recursive: true)) { + for (final FileSystemEntity file in projectDir.listSync(recursive: true)) { if (file is File && file.path.endsWith('.dart')) { final String original = file.readAsStringSync(); @@ -1227,10 +1227,10 @@ Future _createProject( } final List failures = [ - for (String path in expectedPaths) + for (final String path in expectedPaths) if (!pathExists(path)) 'Path "$path" does not exist.', - for (String path in unexpectedPaths) + for (final String path in unexpectedPaths) if (pathExists(path)) 'Path "$path" exists when it shouldn\'t.', ]; diff --git a/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart b/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart index 657b5808a1a..b48c9d57e3f 100644 --- a/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart +++ b/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart @@ -146,7 +146,7 @@ void main() { }; void expectDependenciesResolved(String projectPath) { - for (String output in pubOutput) { + for (final String output in pubOutput) { expectExists(projectPath, output); } } @@ -193,7 +193,7 @@ void main() { modulePluginRegistrants, pluginWitnesses, ].expand((List list) => list); - for (String path in allFiles) { + for (final String path in allFiles) { final File file = globals.fs.file(globals.fs.path.join(projectPath, path)); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart b/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart index 736531b80c9..b1cfd66585c 100644 --- a/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart +++ b/packages/flutter_tools/test/general.shard/android/android_sdk_test.dart @@ -201,7 +201,7 @@ void main() { }); }); - for (String os in ['linux', 'macos']) { + for (final String os in ['linux', 'macos']) { testUsingContext('detection on $os (no ndk available)', () { sdkDir = MockAndroidSdk.createSdkDirectory(withAndroidN: true); globals.config.setValue('android-sdk', sdkDir.path); diff --git a/packages/flutter_tools/test/general.shard/android/gradle_test.dart b/packages/flutter_tools/test/general.shard/android/gradle_test.dart index 17cb6512da0..83f69c70568 100644 --- a/packages/flutter_tools/test/general.shard/android/gradle_test.dart +++ b/packages/flutter_tools/test/general.shard/android/gradle_test.dart @@ -441,10 +441,10 @@ void main() { 'See https://goo.gl/CP92wY for more information on the problem and how to fix it.', 'This warning prints for all Android build failures. The real root cause of the error may be unrelated.', ]; - for (String m in nonMatchingLines) { + for (final String m in nonMatchingLines) { expect(androidXPluginWarningRegex.hasMatch(m), isFalse); } - for (String m in matchingLines) { + for (final String m in matchingLines) { expect(androidXPluginWarningRegex.hasMatch(m), isTrue); } }); diff --git a/packages/flutter_tools/test/general.shard/asset_bundle_package_fonts_test.dart b/packages/flutter_tools/test/general.shard/asset_bundle_package_fonts_test.dart index 222c96f2120..6ce082395bb 100644 --- a/packages/flutter_tools/test/general.shard/asset_bundle_package_fonts_test.dart +++ b/packages/flutter_tools/test/general.shard/asset_bundle_package_fonts_test.dart @@ -70,8 +70,8 @@ $fontsSection final AssetBundle bundle = AssetBundleFactory.instance.createBundle(); await bundle.build(manifestPath: 'pubspec.yaml'); - for (String packageName in packages) { - for (String packageFont in packageFonts) { + for (final String packageName in packages) { + for (final String packageFont in packageFonts) { final String entryKey = 'packages/$packageName/$packageFont'; expect(bundle.entries.containsKey(entryKey), true); expect( @@ -80,7 +80,7 @@ $fontsSection ); } - for (String localFont in localFonts) { + for (final String localFont in localFonts) { expect(bundle.entries.containsKey(localFont), true); expect( utf8.decode(await bundle.entries[localFont].contentsAsBytes()), diff --git a/packages/flutter_tools/test/general.shard/asset_bundle_package_test.dart b/packages/flutter_tools/test/general.shard/asset_bundle_package_test.dart index 25e208982fc..e75dde645e5 100644 --- a/packages/flutter_tools/test/general.shard/asset_bundle_package_test.dart +++ b/packages/flutter_tools/test/general.shard/asset_bundle_package_test.dart @@ -38,7 +38,7 @@ flutter: assets: '''); - for (String asset in assets) { + for (final String asset in assets) { buffer.write(''' - $asset '''); @@ -75,8 +75,8 @@ $assetsSection final AssetBundle bundle = AssetBundleFactory.instance.createBundle(); await bundle.build(manifestPath: 'pubspec.yaml'); - for (String packageName in packages) { - for (String asset in assets) { + for (final String packageName in packages) { + for (final String asset in assets) { final String entryKey = Uri.encodeFull('packages/$packageName/$asset'); expect(bundle.entries.containsKey(entryKey), true, reason: 'Cannot find key on bundle: $entryKey'); expect( @@ -93,7 +93,7 @@ $assetsSection } void writeAssets(String path, List assets) { - for (String asset in assets) { + for (final String asset in assets) { final String fullPath = fixPath(globals.fs.path.join(path, asset)); globals.fs.file(fullPath) diff --git a/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart b/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart index dcd7627c0cd..5fa9fda49f6 100644 --- a/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart +++ b/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart @@ -65,7 +65,7 @@ flutter: 'a/b/c/var2/foo', 'a/b/c/var3/foo', ]; - for (String asset in assets) { + for (final String asset in assets) { globals.fs.file(fixPath(asset)) ..createSync(recursive: true) ..writeAsStringSync(asset); @@ -75,7 +75,7 @@ flutter: await bundle.build(manifestPath: 'pubspec.yaml'); // The main asset file, /a/b/c/foo, and its variants exist. - for (String asset in assets) { + for (final String asset in assets) { expect(bundle.entries.containsKey(asset), true); expect(utf8.decode(await bundle.entries[asset].contentsAsBytes()), asset); } @@ -87,7 +87,7 @@ flutter: // Now the main asset file, /a/b/c/foo, does not exist. This is OK because // the /a/b/c/*/foo variants do exist. expect(bundle.entries.containsKey('a/b/c/foo'), false); - for (String asset in assets.skip(1)) { + for (final String asset in assets.skip(1)) { expect(bundle.entries.containsKey(asset), true); expect(utf8.decode(await bundle.entries[asset].contentsAsBytes()), asset); } diff --git a/packages/flutter_tools/test/general.shard/base/build_test.dart b/packages/flutter_tools/test/general.shard/base/build_test.dart index 62c4c18b739..450e818198d 100644 --- a/packages/flutter_tools/test/general.shard/base/build_test.dart +++ b/packages/flutter_tools/test/general.shard/base/build_test.dart @@ -248,7 +248,7 @@ void main() { when(mockXcode.sdkLocation(any)).thenAnswer((_) => Future.value(kSDKPath)); bufferLogger = BufferLogger(); - for (BuildMode mode in BuildMode.values) { + for (final BuildMode mode in BuildMode.values) { when(mockArtifacts.getArtifactPath(Artifact.snapshotDart, platform: anyNamed('platform'), mode: mode)).thenReturn(kSnapshotDart); } diff --git a/packages/flutter_tools/test/general.shard/base/logger_test.dart b/packages/flutter_tools/test/general.shard/base/logger_test.dart index b30772bcd60..189464caacd 100644 --- a/packages/flutter_tools/test/general.shard/base/logger_test.dart +++ b/packages/flutter_tools/test/general.shard/base/logger_test.dart @@ -103,7 +103,7 @@ void main() { } while (doThis()); } - for (String testOs in testPlatforms) { + for (final String testOs in testPlatforms) { testUsingContext('AnsiSpinner works for $testOs (1)', () async { bool done = false; mockStopwatch = FakeStopwatch(); @@ -255,7 +255,7 @@ void main() { expect(outputStdout().join('\n'), contains('This is taking an unexpectedly long time.')); // Test that the number of '\b' is correct. - for (String line in outputStdout()) { + for (final String line in outputStdout()) { int currLength = 0; for (int i = 0; i < line.length; i += 1) { currLength += line[i] == '\b' ? -1 : 1; diff --git a/packages/flutter_tools/test/general.shard/base/terminal_test.dart b/packages/flutter_tools/test/general.shard/base/terminal_test.dart index f6bc6755236..ff62a6f9056 100644 --- a/packages/flutter_tools/test/general.shard/base/terminal_test.dart +++ b/packages/flutter_tools/test/general.shard/base/terminal_test.dart @@ -40,7 +40,7 @@ void main() { }); testUsingContext('adding colors works', () { - for (TerminalColor color in TerminalColor.values) { + for (final TerminalColor color in TerminalColor.values) { expect( terminal.color('output', color), equals('${AnsiTerminal.colorCode(color)}output${AnsiTerminal.resetColor}'), diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/dart_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/dart_test.dart index b83b51b370f..9d83b2edc5a 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/dart_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/dart_test.dart @@ -96,7 +96,7 @@ flutter_tools:lib/'''); globals.fs.path.join('packages', 'flutter_tools', 'lib', 'src', 'build_system', 'targets', 'dart.dart'), globals.fs.path.join('packages', 'flutter_tools', 'lib', 'src', 'build_system', 'targets', 'ios.dart'), ]; - for (String path in paths) { + for (final String path in paths) { globals.fs.file(path).createSync(recursive: true); } }, overrides: { diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart index cd09381e25f..56f7b3d1fc8 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/macos_test.dart @@ -82,7 +82,7 @@ void main() { }); test('Copies files to correct cache directory', () => testbed.run(() async { - for (File input in inputs) { + for (final File input in inputs) { input.createSync(recursive: true); } // Create output directory so we can test that it is deleted. @@ -100,7 +100,7 @@ void main() { expect(target.existsSync(), false); target.createSync(recursive: true); - for (FileSystemEntity entity in source.listSync(recursive: true)) { + for (final FileSystemEntity entity in source.listSync(recursive: true)) { if (entity is File) { final String relative = globals.fs.path.relative(entity.path, from: source.path); final String destination = globals.fs.path.join(target.path, relative); @@ -115,7 +115,7 @@ void main() { await const DebugUnpackMacOS().build(environment); expect(globals.fs.directory('$_kOutputPrefix').existsSync(), true); - for (File file in inputs) { + for (final File file in inputs) { expect(globals.fs.file(file.path.replaceFirst(_kInputPrefix, _kOutputPrefix)).existsSync(), true); } })); diff --git a/packages/flutter_tools/test/general.shard/dart/sdk_validation_test.dart b/packages/flutter_tools/test/general.shard/dart/sdk_validation_test.dart index 9d864c142e9..e91b4cc6b10 100644 --- a/packages/flutter_tools/test/general.shard/dart/sdk_validation_test.dart +++ b/packages/flutter_tools/test/general.shard/dart/sdk_validation_test.dart @@ -64,7 +64,7 @@ Future analyze(AnalysisServer server) async { int errorCount = 0; final Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; server.onErrors.listen((FileAnalysisErrors result) { - for (AnalysisError error in result.errors) { + for (final AnalysisError error in result.errors) { print(error.toString().trim()); } errorCount += result.errors.length; diff --git a/packages/flutter_tools/test/general.shard/forbidden_imports_test.dart b/packages/flutter_tools/test/general.shard/forbidden_imports_test.dart index dce6b558fa4..eb771ab6034 100644 --- a/packages/flutter_tools/test/general.shard/forbidden_imports_test.dart +++ b/packages/flutter_tools/test/general.shard/forbidden_imports_test.dart @@ -22,8 +22,8 @@ void main() { .where(_isDartFile) .where(_isNotSkipped) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*package:'))) { continue; } @@ -47,8 +47,8 @@ void main() { .where(_isDartFile) .where(_isNotSkipped) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*globals.dart')) && !line.contains(r'as globals')) { final String relativePath = globals.fs.path.relative(file.path, from:flutterTools); @@ -65,14 +65,14 @@ void main() { ]; bool _isNotWhitelisted(FileSystemEntity entity) => whitelistedPaths.every((String path) => path != entity.path); - for (String dirName in ['lib', 'bin']) { + for (final String dirName in ['lib', 'bin']) { final Iterable files = globals.fs.directory(globals.fs.path.join(flutterTools, dirName)) .listSync(recursive: true) .where(_isDartFile) .where(_isNotWhitelisted) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*dart:io')) && !line.contains('ignore: dart_io_import')) { final String relativePath = globals.fs.path.relative(file.path, from:flutterTools); @@ -92,14 +92,14 @@ void main() { ]; bool _isNotWhitelisted(FileSystemEntity entity) => whitelistedPaths.every((String path) => path != entity.path); - for (String dirName in ['lib']) { + for (final String dirName in ['lib']) { final Iterable files = globals.fs.directory(globals.fs.path.join(flutterTools, dirName)) .listSync(recursive: true) .where(_isDartFile) .where(_isNotWhitelisted) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*package:test_api')) && !line.contains('ignore: test_api_import')) { final String relativePath = globals.fs.path.relative(file.path, from:flutterTools); @@ -112,14 +112,14 @@ void main() { test('no unauthorized imports of package:path', () { final String whitelistedPath = globals.fs.path.join(flutterTools, 'lib', 'src', 'build_runner', 'web_compilation_delegate.dart'); - for (String dirName in ['lib', 'bin', 'test']) { + for (final String dirName in ['lib', 'bin', 'test']) { final Iterable files = globals.fs.directory(globals.fs.path.join(flutterTools, dirName)) .listSync(recursive: true) .where(_isDartFile) .where((FileSystemEntity entity) => entity.path != whitelistedPath) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*package:path/path.dart')) && !line.contains('ignore: package_path_import')) { final String relativePath = globals.fs.path.relative(file.path, from:flutterTools); @@ -137,14 +137,14 @@ void main() { ]; bool _isNotWhitelisted(FileSystemEntity entity) => whitelistedPaths.every((String path) => path != entity.path); - for (String dirName in ['lib']) { + for (final String dirName in ['lib']) { final Iterable files = globals.fs.directory(globals.fs.path.join(flutterTools, dirName)) .listSync(recursive: true) .where(_isDartFile) .where(_isNotWhitelisted) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*dart:convert')) && !line.contains('ignore: dart_convert_import')) { final String relativePath = globals.fs.path.relative(file.path, from:flutterTools); @@ -163,14 +163,14 @@ void main() { ]; bool _isNotWhitelisted(FileSystemEntity entity) => whitelistedPaths.every((String path) => !entity.path.contains(path)); - for (String dirName in ['lib']) { + for (final String dirName in ['lib']) { final Iterable files = globals.fs.directory(globals.fs.path.join(flutterTools, dirName)) .listSync(recursive: true) .where(_isDartFile) .where(_isNotWhitelisted) .map(_asFile); - for (File file in files) { - for (String line in file.readAsLinesSync()) { + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { if (line.startsWith(RegExp(r'import.*package:build_runner_core/build_runner_core.dart')) || line.startsWith(RegExp(r'import.*package:build_runner/build_runner.dart')) || line.startsWith(RegExp(r'import.*package:build_config/build_config.dart')) || diff --git a/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_device_test.dart b/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_device_test.dart index d5b4e58f851..3bc889f352e 100644 --- a/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_device_test.dart +++ b/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_device_test.dart @@ -337,7 +337,7 @@ void main() { Future findUri(List views, String expectedIsolateName) async { when(vm.views).thenReturn(views); - for (MockFlutterView view in views) { + for (final MockFlutterView view in views) { when(view.owner).thenReturn(vm); } final MockFuchsiaDevice fuchsiaDevice = diff --git a/packages/flutter_tools/test/general.shard/ios/devices_test.dart b/packages/flutter_tools/test/general.shard/ios/devices_test.dart index 4820ae29689..fbf7ff002dc 100644 --- a/packages/flutter_tools/test/general.shard/ios/devices_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/devices_test.dart @@ -80,7 +80,7 @@ void main() { Platform: () => macPlatform, }); - for (Platform platform in unsupportedPlatforms) { + for (final Platform platform in unsupportedPlatforms) { testUsingContext('throws UnsupportedError exception if instantiated on ${platform.operatingSystem}', () { expect( () { IOSDevice('device-123'); }, @@ -781,7 +781,7 @@ void main() { }); final List unsupportedPlatforms = [linuxPlatform, windowsPlatform]; - for (Platform platform in unsupportedPlatforms) { + for (final Platform platform in unsupportedPlatforms) { testUsingContext('throws Unsupported Operation exception on ${platform.operatingSystem}', () async { when(iMobileDevice.isInstalled).thenReturn(false); when(iMobileDevice.getAvailableDeviceIDs()) diff --git a/packages/flutter_tools/test/general.shard/plugins_test.dart b/packages/flutter_tools/test/general.shard/plugins_test.dart index 7d2d8211149..30b44018738 100644 --- a/packages/flutter_tools/test/general.shard/plugins_test.dart +++ b/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -208,7 +208,7 @@ flutter: pluginClass: UseNewEmbedding dependencies: '''); - for (String dependency in dependencies) { + for (final String dependency in dependencies) { pluginDirectory .childFile('pubspec.yaml') .writeAsStringSync(' $dependency:\n', mode: FileMode.append); diff --git a/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart b/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart index 3d251a5580d..d46e562966c 100644 --- a/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart +++ b/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart @@ -14,7 +14,7 @@ import '../src/common.dart'; final DateTime inFuture = DateTime.now().add(const Duration(days: 100)); void main() { - for (bool asyncScanning in [true, false]) { + for (final bool asyncScanning in [true, false]) { testWithoutContext('No last compile, asyncScanning: $asyncScanning', () async { final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: MemoryFileSystem(), diff --git a/packages/flutter_tools/test/general.shard/project_test.dart b/packages/flutter_tools/test/general.shard/project_test.dart index d42a6172c3f..1fcdfe69d12 100644 --- a/packages/flutter_tools/test/general.shard/project_test.dart +++ b/packages/flutter_tools/test/general.shard/project_test.dart @@ -643,7 +643,7 @@ void testInMemory(String description, Future testMethod()) { void transfer(FileSystemEntity entity, FileSystem target) { if (entity is Directory) { target.directory(entity.absolute.path).createSync(recursive: true); - for (FileSystemEntity child in entity.listSync()) { + for (final FileSystemEntity child in entity.listSync()) { transfer(child, target); } } else if (entity is File) { diff --git a/packages/flutter_tools/test/general.shard/version_test.dart b/packages/flutter_tools/test/general.shard/version_test.dart index bf68b530cac..41d77c03165 100644 --- a/packages/flutter_tools/test/general.shard/version_test.dart +++ b/packages/flutter_tools/test/general.shard/version_test.dart @@ -30,7 +30,7 @@ void main() { mockCache = MockCache(); }); - for (String channel in FlutterVersion.officialChannels) { + for (final String channel in FlutterVersion.officialChannels) { DateTime getChannelUpToDateVersion() { return _testClock.ago(FlutterVersion.versionAgeConsideredUpToDate(channel) ~/ 2); } diff --git a/packages/flutter_tools/test/integration.shard/test_driver.dart b/packages/flutter_tools/test/integration.shard/test_driver.dart index 8dc062f0eed..7fa4c91b4ba 100644 --- a/packages/flutter_tools/test/integration.shard/test_driver.dart +++ b/packages/flutter_tools/test/integration.shard/test_driver.dart @@ -319,7 +319,7 @@ abstract class FlutterTestDriver { } SourcePosition _lookupTokenPos(List> table, int tokenPos) { - for (List row in table) { + for (final List row in table) { final int lineNumber = row[0]; int index = 1; diff --git a/packages/flutter_tools/test/src/fake_process_manager.dart b/packages/flutter_tools/test/src/fake_process_manager.dart index 0e822fd02b7..1a1830ae346 100644 --- a/packages/flutter_tools/test/src/fake_process_manager.dart +++ b/packages/flutter_tools/test/src/fake_process_manager.dart @@ -105,7 +105,7 @@ class FakeCommand { if (environment == null) { return false; } - for (String key in environment.keys) { + for (final String key in environment.keys) { if (environment[key] != this.environment[key]) { return false; } diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index 95fdd64d656..5929c1cc4f1 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart @@ -399,7 +399,7 @@ class MemoryIOSink implements IOSink { @override void writeAll(Iterable objects, [ String separator = '' ]) { bool addSeparator = false; - for (dynamic object in objects) { + for (final dynamic object in objects) { if (addSeparator) { write(separator); } diff --git a/packages/flutter_tools/test/src/testbed.dart b/packages/flutter_tools/test/src/testbed.dart index 2022ebf2423..ab68e92f4b4 100644 --- a/packages/flutter_tools/test/src/testbed.dart +++ b/packages/flutter_tools/test/src/testbed.dart @@ -139,7 +139,7 @@ class Testbed { } await test(); Cache.flutterRoot = originalFlutterRoot; - for (MapEntry entry in timers.entries) { + for (final MapEntry entry in timers.entries) { if (entry.key.isActive) { throw StateError('A Timer was active at the end of a test: ${entry.value}'); } diff --git a/packages/fuchsia_remote_debug_protocol/examples/list_vms_and_flutter_views.dart b/packages/fuchsia_remote_debug_protocol/examples/list_vms_and_flutter_views.dart index 13928727af1..9985da34385 100644 --- a/packages/fuchsia_remote_debug_protocol/examples/list_vms_and_flutter_views.dart +++ b/packages/fuchsia_remote_debug_protocol/examples/list_vms_and_flutter_views.dart @@ -36,13 +36,13 @@ Future main(List args) async { final FuchsiaRemoteConnection connection = await FuchsiaRemoteConnection.connect(address, interface, sshConfigPath); print('On $address, the following Dart VM ports are running:'); - for (int port in await connection.getDeviceServicePorts()) { + for (final int port in await connection.getDeviceServicePorts()) { print('\t$port'); } print(''); print('The following Flutter views are running:'); - for (FlutterView view in await connection.getFlutterViews()) { + for (final FlutterView view in await connection.getFlutterViews()) { print('\t${view.name ?? view.id}'); } await connection.stop(); diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart b/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart index 547dae96f3d..847fad9e93b 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart @@ -170,7 +170,7 @@ class DartVm { final Map jsonVmRef = await invokeRpc('getVM', timeout: timeout); final List result = []; - for (Map jsonIsolate in jsonVmRef['isolates']) { + for (final Map jsonIsolate in jsonVmRef['isolates']) { final String name = jsonIsolate['name'] as String; if (pattern.matchAsPrefix(name) != null) { _log.fine('Found Isolate matching "$pattern": "$name"'); @@ -213,7 +213,7 @@ class DartVm { final List views = []; final Map rpcResponse = await invokeRpc('_flutter.listViews', timeout: timeout); - for (Map jsonView in rpcResponse['views']) { + for (final Map jsonView in rpcResponse['views']) { final FlutterView flutterView = FlutterView._fromJson(jsonView); if (flutterView != null) { views.add(flutterView); diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart index 08f99064e6d..18d9f742388 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart @@ -221,7 +221,7 @@ class FuchsiaRemoteConnection { /// those objects) will subsequently have its connection closed as well, so /// behavior for them will be undefined. Future stop() async { - for (PortForwarder pf in _forwardedVmServicePorts) { + for (final PortForwarder pf in _forwardedVmServicePorts) { // Closes VM service first to ensure that the connection is closed cleanly // on the target before shutting down the forwarding itself. final DartVm vmService = _dartVmCache[pf.port]; @@ -229,7 +229,7 @@ class FuchsiaRemoteConnection { await vmService?.stop(); await pf.stop(); } - for (PortForwarder pf in _dartVmPortMap.values) { + for (final PortForwarder pf in _dartVmPortMap.values) { final DartVm vmService = _dartVmCache[pf.port]; _dartVmCache[pf.port] = null; await vmService?.stop(); @@ -305,7 +305,7 @@ class FuchsiaRemoteConnection { // simultaneously via Future.wait. final List>> isolates = >>[]; - for (PortForwarder fp in _dartVmPortMap.values) { + for (final PortForwarder fp in _dartVmPortMap.values) { final DartVm vmService = await _getDartVm(fp.port, timeout: vmConnectionTimeout); if (vmService == null) { @@ -390,7 +390,7 @@ class FuchsiaRemoteConnection { } } - for (PortForwarder pf in _dartVmPortMap.values) { + for (final PortForwarder pf in _dartVmPortMap.values) { final DartVm service = await _getDartVm(pf.port); if (service == null) { await shutDownPortForwarder(pf); @@ -448,7 +448,7 @@ class FuchsiaRemoteConnection { Future _pollVms() async { await _checkPorts(); final List servicePorts = await getDeviceServicePorts(); - for (int servicePort in servicePorts) { + for (final int servicePort in servicePorts) { if (!_stalePorts.contains(servicePort) && !_dartVmPortMap.containsKey(servicePort)) { _dartVmPortMap[servicePort] = await fuchsiaPortForwardingFunction( @@ -499,7 +499,7 @@ class FuchsiaRemoteConnection { _sshCommandRunner.sshConfigPath); })); - for (PortForwarder pf in forwardedVmServicePorts) { + for (final PortForwarder pf in forwardedVmServicePorts) { // TODO(awdavies): Handle duplicates. _dartVmPortMap[pf.remotePort] = pf; } @@ -521,13 +521,13 @@ class FuchsiaRemoteConnection { final List portPaths = await _sshCommandRunner .run('/bin/find /hub -name vmservice-port'); final List ports = []; - for (String path in portPaths) { + for (final String path in portPaths) { if (path == '') { continue; } final List lsOutput = await _sshCommandRunner.run('/bin/ls $path'); - for (String line in lsOutput) { + for (final String line in lsOutput) { if (line == '') { continue; }