enable lint prefer_final_in_for_each (#47724)

This commit is contained in:
Alexandre Ardhuin 2020-01-07 16:32:04 +01:00 committed by GitHub
parent fa337f5922
commit 4f9b6cf017
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
369 changed files with 1219 additions and 1220 deletions

View File

@ -141,7 +141,7 @@ linter:
- prefer_equal_for_default_values - 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_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_fields
# - prefer_final_in_for_each # not yet tested - prefer_final_in_for_each
- prefer_final_locals - prefer_final_locals
# - prefer_for_elements_to_map_fromIterable # not yet tested # - prefer_for_elements_to_map_fromIterable # not yet tested
- prefer_foreach - prefer_foreach

View File

@ -146,7 +146,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
path.moveTo(100.0, 97.0); 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); path.lineTo(p.x, p.y);
} }
@ -167,7 +167,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
bezier2Path.moveTo(0.0, 70.55); 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); bezier2Path.lineTo(p.x, p.y);
} }
@ -188,7 +188,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
bezier3Path.moveTo(0.0, 69.48); 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); bezier3Path.lineTo(p.x, p.y);
} }
@ -210,7 +210,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
bezier4Path.moveTo(0.0, 69.48); 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); bezier4Path.lineTo(p.x, p.y);
} }
@ -221,7 +221,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
} }
List<PathDetail> _playReversed() { List<PathDetail> _playReversed() {
for (List<Point> list in pointList) { for (final List<Point> list in pointList) {
if (list.isNotEmpty) { if (list.isNotEmpty) {
list.removeLast(); list.removeLast();
} }
@ -232,7 +232,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
path.moveTo(100.0, 97.0); path.moveTo(100.0, 97.0);
for (Point point in points) { for (final Point point in points) {
path.lineTo(point.x, point.y); path.lineTo(point.x, point.y);
} }
@ -240,14 +240,14 @@ class AnimatedBezierState extends State<AnimatedBezier>
bezier2Path.moveTo(0.0, 70.55); 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); bezier2Path.lineTo(p.x, p.y);
} }
final Path bezier3Path = Path(); final Path bezier3Path = Path();
bezier3Path.moveTo(0.0, 69.48); 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); bezier3Path.lineTo(p.x, p.y);
} }
@ -255,7 +255,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
bezier4Path.moveTo(0.0, 69.48); 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); bezier4Path.lineTo(p.x, p.y);
} }
@ -287,7 +287,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
void playAnimation() { void playAnimation() {
isPlaying = true; isPlaying = true;
isReversed = false; isReversed = false;
for (List<Point> list in pointList) { for (final List<Point> list in pointList) {
list.clear(); list.clear();
} }
controller.reset(); controller.reset();
@ -297,7 +297,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
void stopAnimation() { void stopAnimation() {
isPlaying = false; isPlaying = false;
controller.stop(); controller.stop();
for (List<Point> list in pointList) { for (final List<Point> list in pointList) {
list.clear(); list.clear();
} }
} }

View File

@ -51,7 +51,7 @@ class BenchmarkResultPrinter {
String _printJson() { String _printJson() {
final Map<String, double> results = <String, double>{}; final Map<String, double> results = <String, double>{};
for (_BenchmarkResult result in _results) { for (final _BenchmarkResult result in _results) {
results[result.name] = result.value; results[result.name] = result.value;
} }
return json.encode(results); return json.encode(results);
@ -59,7 +59,7 @@ class BenchmarkResultPrinter {
String _printPlainText() { String _printPlainText() {
final StringBuffer buf = StringBuffer(); 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}'); buf.writeln('${result.description}: ${result.value.toStringAsFixed(1)} ${result.unit}');
} }
return buf.toString(); return buf.toString();

View File

@ -16,7 +16,7 @@ void main() {
print('Velocity tracker benchmark...'); print('Velocity tracker benchmark...');
watch.start(); watch.start();
for (int i = 0; i < _kNumIters; i += 1) { 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) if (event is PointerDownEvent || event is PointerMoveEvent)
tracker.addPosition(event.timeStamp, event.position); tracker.addPosition(event.timeStamp, event.position);
if (event is PointerUpEvent) if (event is PointerUpEvent)

View File

@ -84,7 +84,7 @@ Iterable<int> generateIterableList() {
int sumIterable(Iterable<int> values) { int sumIterable(Iterable<int> values) {
int result = 0; int result = 0;
for (int value in values) { for (final int value in values) {
result += value; result += value;
} }
return result; return result;

View File

@ -71,7 +71,7 @@ void main() {
String consumeSpan(Iterable<InlineSpanSemanticsInformation> items) { String consumeSpan(Iterable<InlineSpanSemanticsInformation> items) {
String result = ''; String result = '';
for (InlineSpanSemanticsInformation span in items) { for (final InlineSpanSemanticsInformation span in items) {
result += span.text; result += span.text;
} }
return result; return result;
@ -81,7 +81,7 @@ String consumeSpan(Iterable<InlineSpanSemanticsInformation> items) {
Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoSyncStar(List<InlineSpanSemanticsInformation> inputs) sync* { Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoSyncStar(List<InlineSpanSemanticsInformation> inputs) sync* {
String workingText = ''; String workingText = '';
String workingLabel; String workingLabel;
for (InlineSpanSemanticsInformation info in inputs) { for (final InlineSpanSemanticsInformation info in inputs) {
if (info.requiresOwnNode) { if (info.requiresOwnNode) {
if (workingText != null) { if (workingText != null) {
yield InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText); yield InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText);
@ -110,7 +110,7 @@ Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoList(List<InlineSpa
String workingText = ''; String workingText = '';
String workingLabel; String workingLabel;
final List<InlineSpanSemanticsInformation> result = <InlineSpanSemanticsInformation>[]; final List<InlineSpanSemanticsInformation> result = <InlineSpanSemanticsInformation>[];
for (InlineSpanSemanticsInformation info in inputs) { for (final InlineSpanSemanticsInformation info in inputs) {
if (info.requiresOwnNode) { if (info.requiresOwnNode) {
if (workingText != null) { if (workingText != null) {
result.add(InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText)); result.add(InlineSpanSemanticsInformation(workingText, semanticsLabel: workingLabel ?? workingText));

View File

@ -193,7 +193,7 @@ class SampleChecker {
"import 'dart:typed_data';", "import 'dart:typed_data';",
"import 'dart:ui' as ui;", "import 'dart:ui' as ui;",
"import 'package:flutter_test/flutter_test.dart';", "import 'package:flutter_test/flutter_test.dart';",
for (File file in _listDartFiles(Directory(_defaultFlutterPackage))) ...<String>[ for (final File file in _listDartFiles(Directory(_defaultFlutterPackage))) ...<String>[
'', '',
'// ${file.path}', '// ${file.path}',
"import 'package:flutter/${path.basename(file.path)}';", "import 'package:flutter/${path.basename(file.path)}';",
@ -214,7 +214,7 @@ class SampleChecker {
errors = _analyze(_tempDirectory, sections, snippets); errors = _analyze(_tempDirectory, sections, snippets);
} finally { } finally {
if (errors.isNotEmpty) { if (errors.isNotEmpty) {
for (String filePath in errors.keys) { for (final String filePath in errors.keys) {
errors[filePath].forEach(stderr.writeln); errors[filePath].forEach(stderr.writeln);
} }
stderr.writeln('\nFound ${errors.length} sample code errors.'); stderr.writeln('\nFound ${errors.length} sample code errors.');
@ -310,7 +310,7 @@ class SampleChecker {
final List<Section> sections = <Section>[]; final List<Section> sections = <Section>[];
final List<Snippet> snippets = <Snippet>[]; final List<Snippet> snippets = <Snippet>[];
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 String relativeFilePath = path.relative(file.path, from: _flutterPackage.path);
final List<String> sampleLines = file.readAsLinesSync(); final List<String> sampleLines = file.readAsLinesSync();
final List<Section> preambleSections = <Section>[]; final List<Section> preambleSections = <Section>[];
@ -326,7 +326,7 @@ class SampleChecker {
final List<String> block = <String>[]; final List<String> block = <String>[];
List<String> snippetArgs = <String>[]; List<String> snippetArgs = <String>[];
Line startLine; Line startLine;
for (String line in sampleLines) { for (final String line in sampleLines) {
lineNumber += 1; lineNumber += 1;
final String trimmedLine = line.trim(); final String trimmedLine = line.trim();
if (inSnippet) { if (inSnippet) {
@ -434,10 +434,10 @@ class SampleChecker {
} }
} }
print('Found ${sections.length} sample code sections.'); print('Found ${sections.length} sample code sections.');
for (Section section in sections) { for (final Section section in sections) {
sectionMap[_writeSection(section).path] = section; sectionMap[_writeSection(section).path] = section;
} }
for (Snippet snippet in snippets) { for (final Snippet snippet in snippets) {
final File snippetFile = _writeSnippet(snippet); final File snippetFile = _writeSnippet(snippet);
snippet.contents = snippetFile.readAsLinesSync(); snippet.contents = snippetFile.readAsLinesSync();
snippetMap[snippetFile.absolute.path] = snippet; snippetMap[snippetFile.absolute.path] = snippet;
@ -576,7 +576,7 @@ linter:
); );
bool unknownAnalyzerErrors = false; bool unknownAnalyzerErrors = false;
final int headerLength = headers.length + 2; final int headerLength = headers.length + 2;
for (String error in errors) { for (final String error in errors) {
final Match parts = errorPattern.matchAsPrefix(error); final Match parts = errorPattern.matchAsPrefix(error);
if (parts != null) { if (parts != null) {
final String message = parts[2]; final String message = parts[2];
@ -860,7 +860,7 @@ class Snippet {
String toString() { String toString() {
final StringBuffer buf = StringBuffer('snippet ${args.join(' ')}\n'); final StringBuffer buf = StringBuffer('snippet ${args.join(' ')}\n');
int count = start.line; int count = start.line;
for (String line in input) { for (final String line in input) {
buf.writeln(' ${count.toString().padLeft(4, ' ')}: $line'); buf.writeln(' ${count.toString().padLeft(4, ' ')}: $line');
count++; count++;
} }

View File

@ -147,11 +147,11 @@ final RegExp _grandfatheredDeprecation = RegExp(r' // ignore: flutter_deprecatio
Future<void> verifyDeprecations(String workingDirectory, { int minimumMatches = 2000 }) async { Future<void> verifyDeprecations(String workingDirectory, { int minimumMatches = 2000 }) async {
final List<String> errors = <String>[]; final List<String> errors = <String>[];
for (File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) { for (final File file in _allFiles(workingDirectory, 'dart', minimumMatches: minimumMatches)) {
int lineNumber = 0; int lineNumber = 0;
final List<String> lines = file.readAsLinesSync(); final List<String> lines = file.readAsLinesSync();
final List<int> linesWithDeprecations = <int>[]; final List<int> linesWithDeprecations = <int>[];
for (String line in lines) { for (final String line in lines) {
if (line.contains(_findDeprecationPattern) && if (line.contains(_findDeprecationPattern) &&
!line.endsWith(_ignoreDeprecation) && !line.endsWith(_ignoreDeprecation) &&
!line.contains(_grandfatheredDeprecation)) { !line.contains(_grandfatheredDeprecation)) {
@ -239,7 +239,7 @@ Future<void> _verifyNoMissingLicenseForExtension(String workingDirectory, String
assert(!license.endsWith('\n')); assert(!license.endsWith('\n'));
final String licensePattern = license + '\n' + (trailingBlank ? '\n' : ''); final String licensePattern = license + '\n' + (trailingBlank ? '\n' : '');
final List<String> errors = <String>[]; final List<String> errors = <String>[];
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'); final String contents = file.readAsStringSync().replaceAll('\r\n', '\n');
if (contents.isEmpty) if (contents.isEmpty)
continue; // let's not go down the /bin/true rabbit hole continue; // let's not go down the /bin/true rabbit hole
@ -270,8 +270,8 @@ Future<void> verifyNoTestImports(String workingDirectory) async {
final List<String> errors = <String>[]; final List<String> errors = <String>[];
assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern)); assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern));
final List<File> dartFiles = _allFiles(path.join(workingDirectory, 'packages'), 'dart', minimumMatches: 1500).toList(); final List<File> dartFiles = _allFiles(path.join(workingDirectory, 'packages'), 'dart', minimumMatches: 1500).toList();
for (File file in dartFiles) { for (final File file in dartFiles) {
for (String line in file.readAsLinesSync()) { for (final String line in file.readAsLinesSync()) {
final Match match = _testImportPattern.firstMatch(line); final Match match = _testImportPattern.firstMatch(line);
if (match != null && !_exemptTestImports.contains(match.group(2))) if (match != null && !_exemptTestImports.contains(match.group(2)))
errors.add(file.path); errors.add(file.path);
@ -365,7 +365,7 @@ Future<void> verifyGeneratedPluginRegistrants(String flutterRoot) async {
final Map<String, List<File>> packageToRegistrants = <String, List<File>>{}; final Map<String, List<File>> packageToRegistrants = <String, List<File>>{};
for (File file in flutterRootDir.listSync(recursive: true).whereType<File>().where(_isGeneratedPluginRegistrant)) { for (final File file in flutterRootDir.listSync(recursive: true).whereType<File>().where(_isGeneratedPluginRegistrant)) {
final String package = _getPackageFor(file, flutterRootDir); final String package = _getPackageFor(file, flutterRootDir);
final List<File> registrants = packageToRegistrants.putIfAbsent(package, () => <File>[]); final List<File> registrants = packageToRegistrants.putIfAbsent(package, () => <File>[]);
registrants.add(file); registrants.add(file);
@ -373,16 +373,16 @@ Future<void> verifyGeneratedPluginRegistrants(String flutterRoot) async {
final Set<String> outOfDate = <String>{}; final Set<String> outOfDate = <String>{};
for (String package in packageToRegistrants.keys) { for (final String package in packageToRegistrants.keys) {
final Map<File, String> fileToContent = <File, String>{}; final Map<File, String> fileToContent = <File, String>{};
for (File f in packageToRegistrants[package]) { for (final File f in packageToRegistrants[package]) {
fileToContent[f] = f.readAsStringSync(); fileToContent[f] = f.readAsStringSync();
} }
await runCommand(flutter, <String>['inject-plugins'], await runCommand(flutter, <String>['inject-plugins'],
workingDirectory: package, workingDirectory: package,
outputMode: OutputMode.discard, outputMode: OutputMode.discard,
); );
for (File registrant in fileToContent.keys) { for (final File registrant in fileToContent.keys) {
if (registrant.readAsStringSync() != fileToContent[registrant]) { if (registrant.readAsStringSync() != fileToContent[registrant]) {
outOfDate.add(registrant.path); outOfDate.add(registrant.path);
} }
@ -422,20 +422,20 @@ Future<void> verifyNoBadImportsInFlutter(String workingDirectory) async {
} }
// Verify that the imports are well-ordered. // Verify that the imports are well-ordered.
final Map<String, Set<String>> dependencyMap = <String, Set<String>>{}; final Map<String, Set<String>> dependencyMap = <String, Set<String>>{};
for (String directory in directories) { for (final String directory in directories) {
dependencyMap[directory] = _findFlutterDependencies(path.join(srcPath, directory), errors, checkForMeta: directory != 'foundation'); dependencyMap[directory] = _findFlutterDependencies(path.join(srcPath, directory), errors, checkForMeta: directory != 'foundation');
} }
assert(dependencyMap['material'].contains('widgets') && assert(dependencyMap['material'].contains('widgets') &&
dependencyMap['widgets'].contains('rendering') && dependencyMap['widgets'].contains('rendering') &&
dependencyMap['rendering'].contains('painting')); // to make sure we're convinced _findFlutterDependencies is finding some 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)) { if (dependencyMap[package].contains(package)) {
errors.add( errors.add(
'One of the files in the $yellow$package$reset package imports that package recursively.' '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<String> loop = _deepSearch<String>(dependencyMap, package); final List<String> loop = _deepSearch<String>(dependencyMap, package);
if (loop != null) { if (loop != null) {
errors.add( errors.add(
@ -459,7 +459,7 @@ Future<void> verifyNoBadImportsInFlutter(String workingDirectory) async {
Future<void> verifyNoBadImportsInFlutterTools(String workingDirectory) async { Future<void> verifyNoBadImportsInFlutterTools(String workingDirectory) async {
final List<String> errors = <String>[]; final List<String> errors = <String>[];
final List<File> files = _allFiles(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'), 'dart', minimumMatches: 200).toList(); final List<File> 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/')) { if (file.readAsStringSync().contains('package:flutter_tools/')) {
errors.add('$yellow${file.path}$reset imports flutter_tools.'); errors.add('$yellow${file.path}$reset imports flutter_tools.');
} }
@ -535,7 +535,7 @@ Future<void> verifyNoTrailingSpaces(String workingDirectory, { int minimumMatche
.where((File file) => path.extension(file.path) != '.jar') .where((File file) => path.extension(file.path) != '.jar')
.toList(); .toList();
final List<String> problems = <String>[]; final List<String> problems = <String>[];
for (File file in files) { for (final File file in files) {
final List<String> lines = file.readAsLinesSync(); final List<String> lines = file.readAsLinesSync();
for (int index = 0; index < lines.length; index += 1) { for (int index = 0; index < lines.length; index += 1) {
if (lines[index].endsWith(' ')) { if (lines[index].endsWith(' ')) {
@ -1004,7 +1004,7 @@ Future<void> verifyNoBinaries(String workingDirectory, { Set<Hash256> grandfathe
.map<File>((String filename) => File(path.join(workingDirectory, filename))) .map<File>((String filename) => File(path.join(workingDirectory, filename)))
.toList(); .toList();
final List<String> problems = <String>[]; final List<String> problems = <String>[];
for (File file in files) { for (final File file in files) {
final Uint8List bytes = file.readAsBytesSync(); final Uint8List bytes = file.readAsBytesSync();
try { try {
utf8.decode(bytes); utf8.decode(bytes);
@ -1156,7 +1156,7 @@ Set<String> _findFlutterDependencies(String srcPath, List<String> errors, { bool
return _allFiles(srcPath, 'dart', minimumMatches: 1) return _allFiles(srcPath, 'dart', minimumMatches: 1)
.map<Set<String>>((File file) { .map<Set<String>>((File file) {
final Set<String> result = <String>{}; final Set<String> result = <String>{};
for (String line in file.readAsLinesSync()) { for (final String line in file.readAsLinesSync()) {
Match match = _importPattern.firstMatch(line); Match match = _importPattern.firstMatch(line);
if (match != null) if (match != null)
result.add(match.group(2)); result.add(match.group(2));
@ -1180,7 +1180,7 @@ Set<String> _findFlutterDependencies(String srcPath, List<String> errors, { bool
} }
List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) { List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) {
for (T key in map[start]) { for (final T key in map[start]) {
if (key == start) if (key == start)
continue; // we catch these separately continue; // we catch these separately
if (seen != null && seen.contains(key)) if (seen != null && seen.contains(key))

View File

@ -160,7 +160,7 @@ class FlutterCompactFormatter {
void finish() { void finish() {
final List<String> skipped = <String>[]; final List<String> skipped = <String>[];
final List<String> failed = <String>[]; final List<String> failed = <String>[];
for (TestResult result in _tests.values) { for (final TestResult result in _tests.values) {
switch (result.status) { switch (result.status) {
case TestStatus.started: case TestStatus.started:
failed.add('${_red}Unexpectedly failed to complete a test!'); failed.add('${_red}Unexpectedly failed to complete a test!');

View File

@ -354,7 +354,7 @@ class ArchiveCreator {
// Create each of the templates, since they will call 'pub get' on // Create each of the templates, since they will call 'pub get' on
// themselves when created, and this will warm the cache with their // themselves when created, and this will warm the cache with their
// dependencies too. // dependencies too.
for (String template in <String>['app', 'package', 'plugin']) { for (final String template in <String>['app', 'package', 'plugin']) {
final String createName = path.join(tempDir.path, 'create_$template'); final String createName = path.join(tempDir.path, 'create_$template');
await _runFlutter( await _runFlutter(
<String>['create', '--template=$template', createName], <String>['create', '--template=$template', createName],
@ -528,7 +528,7 @@ class ArchivePublisher {
// Search for any entries with the same hash and channel and remove them. // Search for any entries with the same hash and channel and remove them.
final List<dynamic> releases = jsonData['releases'] as List<dynamic>; final List<dynamic> releases = jsonData['releases'] as List<dynamic>;
jsonData['releases'] = <Map<String, dynamic>>[ jsonData['releases'] = <Map<String, dynamic>>[
for (Map<String, dynamic> entry in releases.cast<Map<String, dynamic>>()) for (final Map<String, dynamic> entry in releases.cast<Map<String, dynamic>>())
if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel']) if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel'])
entry, entry,
newEntry, newEntry,

View File

@ -37,7 +37,7 @@ Stream<String> runAndGetStdout(String executable, List<String> arguments, {
stderr.addStream(process.stderr); stderr.addStream(process.stderr);
final Stream<String> lines = process.stdout.transform(utf8.decoder).transform(const LineSplitter()); final Stream<String> lines = process.stdout.transform(utf8.decoder).transform(const LineSplitter());
await for (String line in lines) await for (final String line in lines)
yield line; yield line;
final int exitCode = await process.exitCode; final int exitCode = await process.exitCode;

View File

@ -295,7 +295,7 @@ const List<String> _excludedExampleApplications = <String>[
/// target app. /// target app.
Future<void> _runBuildTests() async { Future<void> _runBuildTests() async {
final Stream<FileSystemEntity> exampleDirectories = Directory(path.join(flutterRoot, 'examples')).list(); final Stream<FileSystemEntity> exampleDirectories = Directory(path.join(flutterRoot, 'examples')).list();
await for (FileSystemEntity fileEntity in exampleDirectories) { await for (final FileSystemEntity fileEntity in exampleDirectories) {
if (fileEntity is! Directory) { if (fileEntity is! Directory) {
continue; continue;
} }
@ -817,7 +817,7 @@ Future<void> _runHostOnlyDeviceLabTests() async {
last = '_last'; last = '_last';
} }
subshards['$subshard$last'] = () async { subshards['$subshard$last'] = () async {
for (ShardRunner test in sublist) for (final ShardRunner test in sublist)
await test(); await test();
}; };
} }
@ -1020,7 +1020,7 @@ Future<void> _runFromList(Map<String, ShardRunner> items, String key, String nam
item = parts[positionInTaskName]; item = parts[positionInTaskName];
} }
if (item == null) { if (item == null) {
for (String currentItem in items.keys) { for (final String currentItem in items.keys) {
print('$bold$key=$currentItem$reset'); print('$bold$key=$currentItem$reset');
await items[currentItem](); await items[currentItem]();
print(''); print('');

View File

@ -34,7 +34,7 @@ class FakeProcessManager extends Mock implements ProcessManager {
Map<String, List<ProcessResult>> get fakeResults => _fakeResults; Map<String, List<ProcessResult>> get fakeResults => _fakeResults;
set fakeResults(Map<String, List<ProcessResult>> value) { set fakeResults(Map<String, List<ProcessResult>> value) {
_fakeResults = <String, List<ProcessResult>>{}; _fakeResults = <String, List<ProcessResult>>{};
for (String key in value.keys) { for (final String key in value.keys) {
_fakeResults[key] = (value[key] ?? <ProcessResult>[ProcessResult(0, 0, '', '')]).toList(); _fakeResults[key] = (value[key] ?? <ProcessResult>[ProcessResult(0, 0, '', '')]).toList();
} }
} }
@ -46,7 +46,7 @@ class FakeProcessManager extends Mock implements ProcessManager {
/// parameters were in the same order. /// parameters were in the same order.
void verifyCalls(List<String> calls) { void verifyCalls(List<String> calls) {
int index = 0; int index = 0;
for (String call in calls) { for (final String call in calls) {
expect(call.split(' '), orderedEquals(invocations[index].positionalArguments[0] as Iterable<dynamic>)); expect(call.split(' '), orderedEquals(invocations[index].positionalArguments[0] as Iterable<dynamic>));
index++; index++;
} }
@ -178,7 +178,7 @@ class StringStreamConsumer implements StreamConsumer<List<int>> {
@override @override
Future<dynamic> close() async { Future<dynamic> close() async {
for (Completer<dynamic> completer in completers) { for (final Completer<dynamic> completer in completers) {
await completer.future; await completer.future;
} }
completers.clear(); completers.clear();

View File

@ -34,7 +34,7 @@ void main() {
], ],
}; };
processManager.fakeResults = calls; processManager.fakeResults = calls;
for (String key in calls.keys) { for (final String key in calls.keys) {
final Process process = await processManager.start(key.split(' ')); final Process process = await processManager.start(key.split(' '));
String output = ''; String output = '';
process.stdout.listen((List<int> item) { process.stdout.listen((List<int> item) {
@ -56,7 +56,7 @@ void main() {
], ],
}; };
processManager.fakeResults = calls; processManager.fakeResults = calls;
for (String key in calls.keys) { for (final String key in calls.keys) {
final ProcessResult result = await processManager.run(key.split(' ')); final ProcessResult result = await processManager.run(key.split(' '));
expect(result.stdout, equals(calls[key][0].stdout)); expect(result.stdout, equals(calls[key][0].stdout));
} }
@ -73,7 +73,7 @@ void main() {
], ],
}; };
processManager.fakeResults = calls; processManager.fakeResults = calls;
for (String key in calls.keys) { for (final String key in calls.keys) {
final ProcessResult result = processManager.runSync(key.split(' ')); final ProcessResult result = processManager.runSync(key.split(' '));
expect(result.stdout, equals(calls[key][0].stdout)); expect(result.stdout, equals(calls[key][0].stdout));
} }
@ -90,7 +90,7 @@ void main() {
], ],
}; };
processManager.fakeResults = calls; processManager.fakeResults = calls;
for (String key in calls.keys) { for (final String key in calls.keys) {
final Process process = await processManager.start(key.split(' ')); final Process process = await processManager.start(key.split(' '));
String output = ''; String output = '';
process.stdout.listen((List<int> item) { process.stdout.listen((List<int> item) {

View File

@ -35,7 +35,7 @@ void main() {
); );
} }
}); });
for (String platformName in <String>['macos', 'linux', 'windows']) { for (final String platformName in <String>['macos', 'linux', 'windows']) {
final FakePlatform platform = FakePlatform( final FakePlatform platform = FakePlatform(
operatingSystem: platformName, operatingSystem: platformName,
environment: <String, String>{ environment: <String, String>{

View File

@ -27,7 +27,7 @@ void main() {
'1.2.3+hotfix.1', '1.2.3+hotfix.1',
'1.2.3+hotfix.12-pre.12', '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<String>.value(version)); when(file.readAsString()).thenAnswer((Invocation invocation) => Future<String>.value(version));
expect( expect(
await verifyVersion(file), await verifyVersion(file),
@ -47,7 +47,7 @@ void main() {
' 1.2.3', ' 1.2.3',
'1.2.3-hotfix.1', '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<String>.value(version)); when(file.readAsString()).thenAnswer((Invocation invocation) => Future<String>.value(version));
expect( expect(
await verifyVersion(file), await verifyVersion(file),

View File

@ -254,7 +254,7 @@ class ArchiveUnpublisher {
return bDate.compareTo(aDate); return bDate.compareTo(aDate);
}); });
jsonData['releases'] = releases; jsonData['releases'] = releases;
for (Channel channel in channels) { for (final Channel channel in channels) {
if (!revisionsBeingRemoved.contains(jsonData['current_release'][getChannelName(channel)])) { 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. // Don't replace the current release if it's not one of the revisions we're removing.
continue; continue;
@ -276,7 +276,7 @@ class ArchiveUnpublisher {
Future<Map<Channel, Map<String, String>>> _getArchivePaths(List<Map<String, String>> releases) async { Future<Map<Channel, Map<String, String>>> _getArchivePaths(List<Map<String, String>> releases) async {
final Set<String> hashes = <String>{}; final Set<String> hashes = <String>{};
final Map<Channel, Map<String, String>> paths = <Channel, Map<String, String>>{}; final Map<Channel, Map<String, String>> paths = <Channel, Map<String, String>>{};
for (Map<String, String> revision in releases) { for (final Map<String, String> revision in releases) {
final String hash = revision['hash']; final String hash = revision['hash'];
final Channel channel = fromChannelName(revision['channel']); final Channel channel = fromChannelName(revision['channel']);
hashes.add(hash); hashes.add(hash);
@ -350,9 +350,9 @@ class ArchiveUnpublisher {
Future<void> _cloudRemoveArchive(Map<Channel, Map<String, String>> paths) async { Future<void> _cloudRemoveArchive(Map<Channel, Map<String, String>> paths) async {
final List<String> files = <String>[]; final List<String> files = <String>[];
print('${confirmed ? 'Removing' : 'Would remove'} the following release archives:'); print('${confirmed ? 'Removing' : 'Would remove'} the following release archives:');
for (Channel channel in paths.keys) { for (final Channel channel in paths.keys) {
final Map<String, String> hashes = paths[channel]; final Map<String, String> hashes = paths[channel];
for (String hash in hashes.keys) { for (final String hash in hashes.keys) {
final String file = '$gsReleaseFolder/${hashes[hash]}'; final String file = '$gsReleaseFolder/${hashes[hash]}';
files.add(file); files.add(file);
print(' $file'); print(' $file');
@ -464,7 +464,7 @@ Future<void> main(List<String> rawArguments) async {
if (revisions.isEmpty) { if (revisions.isEmpty) {
errorExit('Invalid argument: at least one --revision must be specified.'); 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) { if (revision.length != 40) {
errorExit('Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.'); errorExit('Invalid argument: --revision "$revision" must be the entire hash, not just a prefix.');
} }
@ -500,7 +500,7 @@ Future<void> main(List<String> rawArguments) async {
String message; String message;
String stack; String stack;
try { try {
for (PublishedPlatform platform in platforms) { for (final PublishedPlatform platform in platforms) {
final ArchiveUnpublisher publisher = ArchiveUnpublisher( final ArchiveUnpublisher publisher = ArchiveUnpublisher(
tempDir, tempDir,
revisions.toSet(), revisions.toSet(),

View File

@ -102,7 +102,7 @@ Future<bool> run(List<String> arguments) async {
print(''); print('');
} }
for (File file in files) { for (final File file in files) {
if (verbose) if (verbose)
print('Processing ${file.path}...'); print('Processing ${file.path}...');
TestFile instructions; TestFile instructions;
@ -127,7 +127,7 @@ Future<bool> run(List<String> arguments) async {
try { try {
bool success; bool success;
bool showContacts = false; 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); success = await shell(fetchCommand, checkout, verbose: verbose, silentFailure: skipOnFetchFailure);
if (!success) { if (!success) {
if (skipOnFetchFailure) { if (skipOnFetchFailure) {
@ -153,7 +153,7 @@ Future<bool> run(List<String> arguments) async {
for (int iteration = 0; iteration < repeat; iteration += 1) { for (int iteration = 0; iteration < repeat; iteration += 1) {
if (verbose && repeat > 1) if (verbose && repeat > 1)
print('Round ${iteration + 1} of $repeat.'); 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); success = await shell(testCommand, tests, verbose: verbose);
if (!success) { if (!success) {
print('ERROR: One or more tests from ${path.basenameWithoutExtension(file.path)} failed.'); print('ERROR: One or more tests from ${path.basenameWithoutExtension(file.path)} failed.');
@ -197,7 +197,7 @@ class TestFile {
final List<String> fetch = <String>[]; final List<String> fetch = <String>[];
final List<Directory> update = <Directory>[]; final List<Directory> update = <Directory>[];
final List<String> test = <String>[]; final List<String> test = <String>[];
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) { if (line.isEmpty) {
// blank line // blank line
} else if (line.startsWith('#')) { } else if (line.startsWith('#')) {
@ -228,7 +228,7 @@ class TestFile {
} }
if (contacts.isEmpty) if (contacts.isEmpty)
throw FormatException('${errorPrefix}No contacts specified. At least one contact e-mail address must be specified.'); 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')) 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'); throw FormatException('${errorPrefix}The following e-mail address appears to be an invalid e-mail address: $email');
} }

View File

@ -59,7 +59,7 @@ Future<void> main(List<String> rawArgs) async {
final String localEngine = args['local-engine'] as String; final String localEngine = args['local-engine'] as String;
final String localEngineSrcPath = args['local-engine-src-path'] 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"'); section('Running task "$taskName"');
final Map<String, dynamic> result = await runTask( final Map<String, dynamic> result = await runTask(
taskName, taskName,
@ -95,7 +95,7 @@ void addTasks({
} }
// Only start skipping if user specified a task to continue from // Only start skipping if user specified a task to continue from
final String stage = args['stage'] as String; 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 isQualifyingStage = stage == null || task.stage == stage;
final bool isQualifyingHost = !(args['match-host-platform'] as bool) || task.isSupportedByHost(); final bool isQualifyingHost = !(args['match-host-platform'] as bool) || task.isSupportedByHost();
if (isQualifyingHost && isQualifyingStage) { if (isQualifyingHost && isQualifyingStage) {
@ -116,7 +116,7 @@ final ArgParser _argParser = ArgParser()
'\n' '\n'
'This option may be repeated to specify multiple tasks.', 'This option may be repeated to specify multiple tasks.',
callback: (List<String> value) { callback: (List<String> value) {
for (String nameOrPath in value) { for (final String nameOrPath in value) {
final List<String> fragments = path.split(nameOrPath); final List<String> fragments = path.split(nameOrPath);
final bool isDartFile = fragments.last.endsWith('.dart'); final bool isDartFile = fragments.last.endsWith('.dart');

View File

@ -114,7 +114,7 @@ Future<void> main() async {
section('Check profile, release builds has Dart AOT dylib'); section('Check profile, release builds has Dart AOT dylib');
for (String mode in <String>['Profile', 'Release']) { for (final String mode in <String>['Profile', 'Release']) {
final String appFrameworkPath = path.join( final String appFrameworkPath = path.join(
outputPath, outputPath,
mode, mode,
@ -159,7 +159,7 @@ Future<void> main() async {
section("Check all modes' engine dylib"); section("Check all modes' engine dylib");
for (String mode in <String>['Debug', 'Profile', 'Release']) { for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String engineFrameworkPath = path.join( final String engineFrameworkPath = path.join(
outputPath, outputPath,
mode, mode,
@ -194,7 +194,7 @@ Future<void> main() async {
section("Check all modes' engine header"); section("Check all modes' engine header");
for (String mode in <String>['Debug', 'Profile', 'Release']) { for (final String mode in <String>['Debug', 'Profile', 'Release']) {
checkFileContains( checkFileContains(
<String>['#include "FlutterEngine.h"'], <String>['#include "FlutterEngine.h"'],
path.join(outputPath, mode, 'Flutter.framework', 'Headers', 'Flutter.h'), path.join(outputPath, mode, 'Flutter.framework', 'Headers', 'Flutter.h'),
@ -203,7 +203,7 @@ Future<void> main() async {
section("Check all modes' have plugin dylib"); section("Check all modes' have plugin dylib");
for (String mode in <String>['Debug', 'Profile', 'Release']) { for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String pluginFrameworkPath = path.join( final String pluginFrameworkPath = path.join(
outputPath, outputPath,
mode, mode,
@ -237,7 +237,7 @@ Future<void> main() async {
section("Check all modes' have generated plugin registrant"); section("Check all modes' have generated plugin registrant");
for (String mode in <String>['Debug', 'Profile', 'Release']) { for (final String mode in <String>['Debug', 'Profile', 'Release']) {
final String registrantFrameworkPath = path.join( final String registrantFrameworkPath = path.join(
outputPath, outputPath,
mode, mode,

View File

@ -40,7 +40,7 @@ Future<void> main() async {
print('^ not sure what to do with that line ^'); print('^ not sure what to do with that line ^');
} }
} }
await for (String entry in analysis.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) { await for (final String entry in analysis.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) {
print('analyzer stderr: $entry'); print('analyzer stderr: $entry');
if (entry.contains(' (ran in ') && !sawFinalLine) { if (entry.contains(' (ran in ') && !sawFinalLine) {
// ignore this line once // ignore this line once

View File

@ -16,7 +16,7 @@ Future<void> main() async {
final List<String> benchmarkScoreKeys = <String>[]; final List<String> benchmarkScoreKeys = <String>[];
final Map<String, dynamic> data = <String, dynamic>{}; final Map<String, dynamic> data = <String, dynamic>{};
for (String key in withSemantics.benchmarkScoreKeys) { for (final String key in withSemantics.benchmarkScoreKeys) {
final String deltaKey = 'delta_$key'; final String deltaKey = 'delta_$key';
data[deltaKey] = withSemantics.data[key] - withoutSemantics.data[key]; data[deltaKey] = withSemantics.data[key] - withoutSemantics.data[key];
data['semantics_$key'] = withSemantics.data[key]; data['semantics_$key'] = withSemantics.data[key];

View File

@ -49,7 +49,7 @@ Future<int> runTest({bool coverage = false}) async {
); );
int badLines = 0; int badLines = 0;
TestStep step = TestStep.starting; TestStep step = TestStep.starting;
await for (String entry in analysis.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) { await for (final String entry in analysis.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) {
print('test stdout ($step): $entry'); print('test stdout ($step): $entry');
if (step == TestStep.starting && entry == 'Building flutter tool...') { if (step == TestStep.starting && entry == 'Building flutter tool...') {
// ignore this line // ignore this line
@ -82,7 +82,7 @@ Future<int> runTest({bool coverage = false}) async {
} }
} }
} }
await for (String entry in analysis.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) { await for (final String entry in analysis.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) {
print('test stderr: $entry'); print('test stderr: $entry');
badLines += 1; badLines += 1;
} }

View File

@ -50,7 +50,7 @@ Future<void> main() async {
final String pubspecString = pubspecFile.readAsStringSync(); final String pubspecString = pubspecFile.readAsStringSync();
final StringBuffer iosOnlyPubspec = StringBuffer(); final StringBuffer iosOnlyPubspec = StringBuffer();
for (String line in pubspecString.split('\n')) { for (final String line in pubspecString.split('\n')) {
if (line.startsWith(' androidPackage:')) { if (line.startsWith(' androidPackage:')) {
continue; continue;
} }

View File

@ -37,7 +37,7 @@ Future<double> findCostsForFile(File file) async {
return 0.0; return 0.0;
final bool isTest = file.path.endsWith('_test.dart'); final bool isTest = file.path.endsWith('_test.dart');
double total = 0.0; double total = 0.0;
for (String line in await file.readAsLines()) { for (final String line in await file.readAsLines()) {
if (line.contains(todoPattern)) if (line.contains(todoPattern))
total += todoCost; total += todoCost;
if (line.contains(ignorePattern)) if (line.contains(ignorePattern))
@ -60,7 +60,7 @@ Future<int> findGlobalsForFile(File file) async {
if (path.extension(file.path) != '.dart') if (path.extension(file.path) != '.dart')
return 0; return 0;
int total = 0; int total = 0;
for (String line in await file.readAsLines()) { for (final String line in await file.readAsLines()) {
if (line.contains(globalsPattern)) if (line.contains(globalsPattern))
total += 1; total += 1;
} }
@ -74,7 +74,7 @@ Future<double> findCostsForRepo() async {
workingDirectory: flutterDirectory.path, workingDirectory: flutterDirectory.path,
); );
double total = 0.0; double total = 0.0;
await for (String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) await for (final String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()))
total += await findCostsForFile(File(path.join(flutterDirectory.path, entry))); total += await findCostsForFile(File(path.join(flutterDirectory.path, entry)));
final int gitExitCode = await git.exitCode; final int gitExitCode = await git.exitCode;
if (gitExitCode != 0) if (gitExitCode != 0)
@ -89,7 +89,7 @@ Future<int> findGlobalsForTool() async {
workingDirectory: flutterDirectory.path, workingDirectory: flutterDirectory.path,
); );
int total = 0; int total = 0;
await for (String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter())) await for (final String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()))
total += await findGlobalsForFile(File(path.join(flutterDirectory.path, entry))); total += await findGlobalsForFile(File(path.join(flutterDirectory.path, entry)));
final int gitExitCode = await git.exitCode; final int gitExitCode = await git.exitCode;
if (gitExitCode != 0) if (gitExitCode != 0)

View File

@ -37,7 +37,7 @@ Future<void> main() async {
.transform(utf8.decoder) .transform(utf8.decoder)
.transform(const LineSplitter()); .transform(const LineSplitter());
await for (String line in lines) { await for (final String line in lines) {
print(line); print(line);
if (line.contains('ERROR caught by framework')) { if (line.contains('ERROR caught by framework')) {
passed = true; passed = true;

View File

@ -144,7 +144,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
final List<String> output = (await eval(adbPath, <String>['devices', '-l'], canFail: false)) final List<String> output = (await eval(adbPath, <String>['devices', '-l'], canFail: false))
.trim().split('\n'); .trim().split('\n');
final List<String> results = <String>[]; final List<String> results = <String>[];
for (String line in output) { for (final String line in output) {
// Skip lines like: * daemon started successfully * // Skip lines like: * daemon started successfully *
if (line.startsWith('* daemon ')) if (line.startsWith('* daemon '))
continue; continue;
@ -172,7 +172,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
@override @override
Future<Map<String, HealthCheckResult>> checkDevices() async { Future<Map<String, HealthCheckResult>> checkDevices() async {
final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{};
for (String deviceId in await discoverDevices()) { for (final String deviceId in await discoverDevices()) {
try { try {
final AndroidDevice device = AndroidDevice(deviceId: deviceId); final AndroidDevice device = AndroidDevice(deviceId: deviceId);
// Just a smoke test that we can read wakefulness state // Just a smoke test that we can read wakefulness state
@ -432,7 +432,7 @@ class IosDeviceDiscovery implements DeviceDiscovery {
@override @override
Future<Map<String, HealthCheckResult>> checkDevices() async { Future<Map<String, HealthCheckResult>> checkDevices() async {
final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{}; final Map<String, HealthCheckResult> results = <String, HealthCheckResult>{};
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 // TODO(ianh): do a more meaningful connectivity check than just recording the ID
results['ios-device-$deviceId'] = HealthCheckResult.success(); results['ios-device-$deviceId'] = HealthCheckResult.success();
} }

View File

@ -191,7 +191,7 @@ Future<String> getAndroidManifest(String apk) async {
/// Checks that the classes are contained in the APK, throws otherwise. /// Checks that the classes are contained in the APK, throws otherwise.
Future<void> checkApkContainsClasses(File apk, List<String> classes) async { Future<void> checkApkContainsClasses(File apk, List<String> classes) async {
final ApkExtractor extractor = ApkExtractor(apk); final ApkExtractor extractor = ApkExtractor(apk);
for (String className in classes) { for (final String className in classes) {
if (!(await extractor.containsClass(className))) { if (!(await extractor.containsClass(className))) {
throw Exception('APK doesn\'t contain class `$className`.'); throw Exception('APK doesn\'t contain class `$className`.');
} }

View File

@ -179,7 +179,7 @@ class TaskResult {
message = 'success' { message = 'success' {
const JsonEncoder prettyJson = JsonEncoder.withIndent(' '); const JsonEncoder prettyJson = JsonEncoder.withIndent(' ');
if (benchmarkScoreKeys != null) { if (benchmarkScoreKeys != null) {
for (String key in benchmarkScoreKeys) { for (final String key in benchmarkScoreKeys) {
if (!data.containsKey(key)) { if (!data.containsKey(key)) {
throw 'Invalid Golem score key "$key". It does not exist in task ' throw 'Invalid Golem score key "$key". It does not exist in task '
'result data ${prettyJson.convert(data)}'; 'result data ${prettyJson.convert(data)}';

View File

@ -160,7 +160,7 @@ void _checkIsNotBlank(dynamic value, String variableName, String ownerName) {
} }
void _checkKeys(Map<dynamic, dynamic> map, String variableName, List<String> allowedKeys) { void _checkKeys(Map<dynamic, dynamic> map, String variableName, List<String> allowedKeys) {
for (String key in map.keys.cast<String>()) { for (final String key in map.keys.cast<String>()) {
if (!allowedKeys.contains(key)) { if (!allowedKeys.contains(key)) {
throw ManifestError( throw ManifestError(
'Unrecognized property "$key" in $variableName. ' 'Unrecognized property "$key" in $variableName. '

View File

@ -100,7 +100,7 @@ Stream<RunningProcessInfo> windowsRunningProcesses(String processName) async* {
print(result.stdout); print(result.stdout);
return; return;
} }
for (RunningProcessInfo info in processPowershellOutput(result.stdout as String)) { for (final RunningProcessInfo info in processPowershellOutput(result.stdout as String)) {
yield info; yield info;
} }
} }
@ -122,7 +122,7 @@ Iterable<RunningProcessInfo> processPowershellOutput(String output) sync* {
int creationDateHeaderEnd; int creationDateHeaderEnd;
int commandLineHeaderStart; int commandLineHeaderStart;
bool inTableBody = false; bool inTableBody = false;
for (String line in output.split('\n')) { for (final String line in output.split('\n')) {
if (line.startsWith('ProcessId')) { if (line.startsWith('ProcessId')) {
commandLineHeaderStart = line.indexOf('CommandLine'); commandLineHeaderStart = line.indexOf('CommandLine');
creationDateHeaderEnd = commandLineHeaderStart - 1; creationDateHeaderEnd = commandLineHeaderStart - 1;
@ -191,7 +191,7 @@ Stream<RunningProcessInfo> posixRunningProcesses(
print(result.stdout); print(result.stdout);
return; return;
} }
for (RunningProcessInfo info in processPsOutput(result.stdout as String, processName)) { for (final RunningProcessInfo info in processPsOutput(result.stdout as String, processName)) {
yield info; yield info;
} }
} }

View File

@ -63,7 +63,7 @@ class HealthCheckResult {
if (details != null && details.trim().isNotEmpty) { if (details != null && details.trim().isNotEmpty) {
buf.writeln(); buf.writeln();
// Indent details by 4 spaces // 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'); buf.writeln(' $line');
} }
} }
@ -119,7 +119,7 @@ void recursiveCopy(Directory source, Directory target) {
if (!target.existsSync()) if (!target.existsSync())
target.createSync(); 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); final String name = path.basename(entity.path);
if (entity is Directory && !entity.path.contains('.dart_tool')) if (entity is Directory && !entity.path.contains('.dart_tool'))
recursiveCopy(entity, Directory(path.join(target.path, name))); recursiveCopy(entity, Directory(path.join(target.path, name)));
@ -286,7 +286,7 @@ Future<void> forceQuitRunningProcesses() async {
await Future<void>.delayed(const Duration(seconds: 1)); await Future<void>.delayed(const Duration(seconds: 1));
// Whatever's left, kill it. // Whatever's left, kill it.
for (ProcessInfo p in _runningProcesses) { for (final ProcessInfo p in _runningProcesses) {
print('Force-quitting process:\n$p'); print('Force-quitting process:\n$p');
if (!p.process.kill()) { if (!p.process.kill()) {
print('Failed to force quit process'); print('Failed to force quit process');
@ -636,7 +636,7 @@ void checkFileNotExists(String file) {
/// Check that `collection` contains all entries in `values`. /// Check that `collection` contains all entries in `values`.
void checkCollectionContains<T>(Iterable<T> values, Iterable<T> collection) { void checkCollectionContains<T>(Iterable<T> values, Iterable<T> collection) {
for (T value in values) { for (final T value in values) {
if (!collection.contains(value)) { if (!collection.contains(value)) {
throw TaskResult.failure('Expected to find `$value` in `${collection.toString()}`.'); throw TaskResult.failure('Expected to find `$value` in `${collection.toString()}`.');
} }
@ -645,7 +645,7 @@ void checkCollectionContains<T>(Iterable<T> values, Iterable<T> collection) {
/// Check that `collection` does not contain any entries in `values` /// Check that `collection` does not contain any entries in `values`
void checkCollectionDoesNotContain<T>(Iterable<T> values, Iterable<T> collection) { void checkCollectionDoesNotContain<T>(Iterable<T> values, Iterable<T> collection) {
for (T value in values) { for (final T value in values) {
if (collection.contains(value)) { if (collection.contains(value)) {
throw TaskResult.failure('Did not expect to find `$value` in `$collection`.'); throw TaskResult.failure('Did not expect to find `$value` in `$collection`.');
} }
@ -656,7 +656,7 @@ void checkCollectionDoesNotContain<T>(Iterable<T> values, Iterable<T> collection
/// [Pattern]s, otherwise throws a [TaskResult]. /// [Pattern]s, otherwise throws a [TaskResult].
void checkFileContains(List<Pattern> patterns, String filePath) { void checkFileContains(List<Pattern> patterns, String filePath) {
final String fileContent = File(filePath).readAsStringSync(); final String fileContent = File(filePath).readAsStringSync();
for (Pattern pattern in patterns) { for (final Pattern pattern in patterns) {
if (!fileContent.contains(pattern)) { if (!fileContent.contains(pattern)) {
throw TaskResult.failure( throw TaskResult.failure(
'Expected to find `$pattern` in `$filePath` ' 'Expected to find `$pattern` in `$filePath` '

View File

@ -50,7 +50,7 @@ class GalleryTransitionTest {
file('${galleryDirectory.path}/build/transition_durations.timeline.json').readAsStringSync(), file('${galleryDirectory.path}/build/transition_durations.timeline.json').readAsStringSync(),
) as Map<String, dynamic>; ) as Map<String, dynamic>;
final Map<String, List<int>> transitions = <String, List<int>>{}; final Map<String, List<int>> transitions = <String, List<int>>{};
for (String key in original.keys) { for (final String key in original.keys) {
transitions[key.replaceAll('/', '')] = List<int>.from(original[key] as List<dynamic>); transitions[key.replaceAll('/', '')] = List<int>.from(original[key] as List<dynamic>);
} }

View File

@ -386,7 +386,7 @@ class CompileTest {
final RegExp metricExpression = RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)'); final RegExp metricExpression = RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)');
final Map<String, dynamic> metrics = <String, dynamic>{}; final Map<String, dynamic> metrics = <String, dynamic>{};
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)); metrics[_sdkNameToMetricName(m.group(1))] = int.parse(m.group(2));
} }
if (metrics.length != _kSdkNameToMetricNameMapping.length) { if (metrics.length != _kSdkNameToMetricNameMapping.length) {

View File

@ -12,7 +12,7 @@ import 'package:flutter_devicelab/framework/utils.dart';
/// Combines several TaskFunctions with trivial success value into one. /// Combines several TaskFunctions with trivial success value into one.
TaskFunction combine(List<TaskFunction> tasks) { TaskFunction combine(List<TaskFunction> tasks) {
return () async { return () async {
for (TaskFunction task in tasks) { for (final TaskFunction task in tasks) {
final TaskResult result = await task(); final TaskResult result = await task();
if (result.failed) { if (result.failed) {
return result; return result;

View File

@ -120,14 +120,14 @@ Future<void> saveCatalogScreenshots({
String prefix, // Prefix for all file names. String prefix, // Prefix for all file names.
}) async { }) async {
final List<String> screenshots = <String>[ final List<String> screenshots = <String>[
for (FileSystemEntity entity in directory.listSync()) for (final FileSystemEntity entity in directory.listSync())
if (entity is File && entity.path.endsWith('.png')) if (entity is File && entity.path.endsWith('.png'))
entity.path, entity.path,
]; ];
final List<String> largeNames = <String>[]; // Cloud storage names for the full res screenshots. final List<String> largeNames = <String>[]; // Cloud storage names for the full res screenshots.
final List<String> smallNames = <String>[]; // Likewise for the scaled down screenshots. final List<String> smallNames = <String>[]; // Likewise for the scaled down screenshots.
for (String path in screenshots) { for (final String path in screenshots) {
final String name = screenshotName(path); final String name = screenshotName(path);
largeNames.add('$commit/$prefix$name.png'); largeNames.add('$commit/$prefix$name.png');
smallNames.add('$commit/$prefix${name}_small.png'); smallNames.add('$commit/$prefix${name}_small.png');

View File

@ -19,7 +19,7 @@ void main() {
expect(task.stage, 'devicelab'); expect(task.stage, 'devicelab');
expect(task.requiredAgentCapabilities, <String>['linux/android']); expect(task.requiredAgentCapabilities, <String>['linux/android']);
for (ManifestTask task in manifest.tasks) { for (final ManifestTask task in manifest.tasks) {
final File taskFile = File('bin/tasks/${task.name}.dart'); final File taskFile = File('bin/tasks/${task.name}.dart');
expect(taskFile.existsSync(), true, expect(taskFile.existsSync(), true,
reason: 'File ${taskFile.path} corresponding to manifest task "${task.name}" not found'); reason: 'File ${taskFile.path} corresponding to manifest task "${task.name}" not found');

View File

@ -19,7 +19,7 @@ void main() {
final ProcessResult scriptProcess = processManager.runSync(<String>[ final ProcessResult scriptProcess = processManager.runSync(<String>[
dart, dart,
'bin/run.dart', 'bin/run.dart',
for (String testName in testNames) ...<String>['-t', testName], for (final String testName in testNames) ...<String>['-t', testName],
]); ]);
return scriptProcess; return scriptProcess;
} }

View File

@ -149,7 +149,7 @@ class AndroidSemanticsNode {
/// Gets a list of [AndroidSemanticsActions] which are defined for the node. /// Gets a list of [AndroidSemanticsActions] which are defined for the node.
List<AndroidSemanticsAction> getActions() => <AndroidSemanticsAction>[ List<AndroidSemanticsAction> getActions() => <AndroidSemanticsAction>[
for (int id in (_values['actions'] as List<dynamic>).cast<int>()) AndroidSemanticsAction.deserialize(id), for (final int id in (_values['actions'] as List<dynamic>).cast<int>()) AndroidSemanticsAction.deserialize(id),
]; ];
@override @override

View File

@ -399,7 +399,7 @@ void main() {
// catch up. // catch up.
await Future<void>.delayed(const Duration(milliseconds: 1500)); await Future<void>.delayed(const Duration(milliseconds: 1500));
for (String item in popupItems) { for (final String item in popupItems) {
expect( expect(
await getSemantics(find.byValueKey('$popupKeyValue.$item')), await getSemantics(find.byValueKey('$popupKeyValue.$item')),
hasAndroidSemantics( hasAndroidSemantics(
@ -423,7 +423,7 @@ void main() {
await driver.tap(find.byValueKey(popupButtonKeyValue)); await driver.tap(find.byValueKey(popupButtonKeyValue));
await Future<void>.delayed(const Duration(milliseconds: 1500)); await Future<void>.delayed(const Duration(milliseconds: 1500));
for (String item in popupItems) { for (final String item in popupItems) {
expect( expect(
await getSemantics(find.byValueKey('$popupKeyValue.$item')), await getSemantics(find.byValueKey('$popupKeyValue.$item')),
hasAndroidSemantics( hasAndroidSemantics(
@ -467,7 +467,7 @@ void main() {
try { try {
await Future<void>.delayed(const Duration(milliseconds: 1500)); await Future<void>.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 // 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. // that is in the overlay, not the one in the dropdown.
expect( expect(
@ -503,7 +503,7 @@ void main() {
await driver.tap(find.byValueKey(dropdownButtonKeyValue)); await driver.tap(find.byValueKey(dropdownButtonKeyValue));
await Future<void>.delayed(const Duration(milliseconds: 1500)); await Future<void>.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 // 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. // that is in the overlay, not the one in the dropdown.
expect( expect(
@ -572,7 +572,7 @@ void main() {
), ),
reason: "Alert OK button doesn't have the right semantics"); reason: "Alert OK button doesn't have the right semantics");
for (String item in <String>['Title', 'Body1', 'Body2']) { for (final String item in <String>['Title', 'Body1', 'Body2']) {
expect( expect(
await getSemantics(find.byValueKey('$alertKeyValue.$item')), await getSemantics(find.byValueKey('$alertKeyValue.$item')),
hasAndroidSemantics( hasAndroidSemantics(
@ -611,7 +611,7 @@ void main() {
), ),
reason: "Alert OK button doesn't have the right semantics"); reason: "Alert OK button doesn't have the right semantics");
for (String item in <String>['Title', 'Body1', 'Body2']) { for (final String item in <String>['Title', 'Body1', 'Body2']) {
expect( expect(
await getSemantics(find.byValueKey('$alertKeyValue.$item')), await getSemantics(find.byValueKey('$alertKeyValue.$item')),
hasAndroidSemantics( hasAndroidSemantics(

View File

@ -122,7 +122,7 @@ void diffMaps(
'${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} '); '${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} ');
return; return;
} }
for (String key in expected.keys) { for (final String key in expected.keys) {
if (excludeKeys.contains(key)) if (excludeKeys.contains(key))
continue; continue;
if (doublesApproximatelyMatch(expected[key], actual[key])) if (doublesApproximatelyMatch(expected[key], actual[key]))

View File

@ -123,7 +123,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
await channel.invokeMethod<void>('pipeFlutterViewEvents'); await channel.invokeMethod<void>('pipeFlutterViewEvents');
await viewChannel.invokeMethod<void>('pipeTouchEvents'); await viewChannel.invokeMethod<void>('pipeTouchEvents');
print('replaying ${recordedEvents.length} motion events'); print('replaying ${recordedEvents.length} motion events');
for (Map<String, dynamic> event in recordedEvents.reversed) { for (final Map<String, dynamic> event in recordedEvents.reversed) {
await channel.invokeMethod<void>('synthesizeEvent', event); await channel.invokeMethod<void>('synthesizeEvent', event);
} }

View File

@ -174,7 +174,7 @@ bool _deepEqualsList(List<dynamic> a, List<dynamic> b) {
bool _deepEqualsMap(Map<dynamic, dynamic> a, Map<dynamic, dynamic> b) { bool _deepEqualsMap(Map<dynamic, dynamic> a, Map<dynamic, dynamic> b) {
if (a.length != b.length) if (a.length != b.length)
return false; return false;
for (dynamic key in a.keys) { for (final dynamic key in a.keys) {
if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) if (!b.containsKey(key) || !_deepEquals(a[key], b[key]))
return false; return false;
} }

View File

@ -77,7 +77,7 @@ class UndoableActionDispatcher extends ActionDispatcher implements Listenable {
/// May only be called by subclasses. /// May only be called by subclasses.
@protected @protected
void notifyListeners() { void notifyListeners() {
for (VoidCallback callback in _listeners) { for (final VoidCallback callback in _listeners) {
callback(); callback();
} }
} }

View File

@ -159,7 +159,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
setState(() { setState(() {
final double dy = markersScrollOffset - notification.metrics.extentBefore; final double dy = markersScrollOffset - notification.metrics.extentBefore;
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]; final Offset oldPosition = markers[type];
markers[type] = oldPosition.translate(0.0, dy); markers[type] = oldPosition.translate(0.0, dy);
} }
@ -199,7 +199,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
), ),
), ),
), ),
for (MarkerType type in markers.keys) for (final MarkerType type in markers.keys)
Marker(type: type, position: markers[type]), Marker(type: type, position: markers[type]),
], ],
); );

View File

@ -127,8 +127,8 @@ class _HardwareKeyDemoState extends State<RawKeyboardDemo> {
if (_event.character != null) { if (_event.character != null) {
dataText.add(Text('character: ${_event.character}')); dataText.add(Text('character: ${_event.character}'));
} }
for (ModifierKey modifier in data.modifiersPressed.keys) { for (final ModifierKey modifier in data.modifiersPressed.keys) {
for (KeyboardSide side in KeyboardSide.values) { for (final KeyboardSide side in KeyboardSide.values) {
if (data.isModifierPressed(modifier, side: side)) { if (data.isModifierPressed(modifier, side: side)) {
dataText.add( dataText.add(
Text('${_getEnumName(side)} ${_getEnumName(modifier).replaceAll('Modifier', '')} pressed'), Text('${_getEnumName(side)} ${_getEnumName(modifier).replaceAll('Modifier', '')} pressed'),

View File

@ -343,7 +343,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
if (node.children == null || node.children.isEmpty) if (node.children == null || node.children.isEmpty)
return 0; return 0;
int result = 0; int result = 0;
for (TextSpan child in node.children.cast<TextSpan>()) for (final TextSpan child in node.children.cast<TextSpan>())
result = math.max(result, depthOf(child)); result = math.max(result, depthOf(child));
return result; return result;
} }
@ -582,7 +582,7 @@ class _UnderlinesState extends State<Underlines> {
child: ListBody( child: ListBody(
children: <Widget>[ children: <Widget>[
_wrap(null), _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<Fallback> {
child: IntrinsicWidth( child: IntrinsicWidth(
child: ListBody( child: ListBody(
children: <Widget>[ children: <Widget>[
for (String font in androidFonts) for (final String font in androidFonts)
Text( Text(
multiScript, multiScript,
style: style.copyWith( style: style.copyWith(

View File

@ -104,7 +104,7 @@ class SnippetGenerator {
final List<String> result = <String>[]; final List<String> result = <String>[];
const HtmlEscape htmlEscape = HtmlEscape(); const HtmlEscape htmlEscape = HtmlEscape();
String language; String language;
for (_ComponentTuple injection in injections) { for (final _ComponentTuple injection in injections) {
if (!injection.name.startsWith('code')) { if (!injection.name.startsWith('code')) {
continue; continue;
} }
@ -152,7 +152,7 @@ class SnippetGenerator {
final List<_ComponentTuple> components = <_ComponentTuple>[]; final List<_ComponentTuple> components = <_ComponentTuple>[];
String language; String language;
final RegExp codeStartEnd = RegExp(r'^\s*```([-\w]+|[-\w]+ ([-\w]+))?\s*$'); 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); final Match match = codeStartEnd.firstMatch(line);
if (match != null) { // If we saw the start or end of a code block if (match != null) { // If we saw the start or end of a code block
inCodeBlock = !inCodeBlock; inCodeBlock = !inCodeBlock;
@ -188,7 +188,7 @@ class SnippetGenerator {
String _addLineNumbers(String app) { String _addLineNumbers(String app) {
final StringBuffer buffer = StringBuffer(); final StringBuffer buffer = StringBuffer();
int count = 0; int count = 0;
for (String line in app.split('\n')) { for (final String line in app.split('\n')) {
count++; count++;
buffer.writeln('${count.toString().padLeft(5, ' ')}: $line'); buffer.writeln('${count.toString().padLeft(5, ' ')}: $line');
} }

View File

@ -57,7 +57,7 @@ Future<void> main(List<String> arguments) async {
// https://github.com/dart-lang/dartdoc/issues/1982 // https://github.com/dart-lang/dartdoc/issues/1982
buf.writeln('version: 0.0.0'); buf.writeln('version: 0.0.0');
buf.writeln('dependencies:'); buf.writeln('dependencies:');
for (String package in findPackageNames()) { for (final String package in findPackageNames()) {
buf.writeln(' $package:'); buf.writeln(' $package:');
buf.writeln(' sdk: flutter'); buf.writeln(' sdk: flutter');
} }
@ -72,7 +72,7 @@ Future<void> main(List<String> arguments) async {
libDir.createSync(); libDir.createSync();
final StringBuffer contents = StringBuffer('library temp_doc;\n\n'); 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\';'); contents.writeln('import \'package:$libraryRef\';');
} }
File('$kDocsRoot/lib/temp_doc.dart').writeAsStringSync(contents.toString()); 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()) if (!destDir.existsSync())
destDir.createSync(recursive: true); 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)); final String newPath = path.join(destDir.path, path.basename(entity.path));
if (entity is File) { if (entity is File) {
final File newFile = File(newPath); final File newFile = File(newPath);
@ -361,7 +361,7 @@ void sanityCheckDocs() {
'$kPublishRoot/api/material/Tooltip-class.html', '$kPublishRoot/api/material/Tooltip-class.html',
'$kPublishRoot/api/widgets/Widget-class.html', '$kPublishRoot/api/widgets/Widget-class.html',
]; ];
for (String canary in canaries) { for (final String canary in canaries) {
if (!File(canary).existsSync()) if (!File(canary).existsSync())
throw Exception('Missing "$canary", which probably means the documentation failed to build correctly.'); throw Exception('Missing "$canary", which probably means the documentation failed to build correctly.');
} }
@ -470,9 +470,9 @@ List<Directory> findPackages() {
/// Returns import or on-disk paths for all libraries in the Flutter SDK. /// Returns import or on-disk paths for all libraries in the Flutter SDK.
Iterable<String> libraryRefs() sync* { Iterable<String> libraryRefs() sync* {
for (Directory dir in findPackages()) { for (final Directory dir in findPackages()) {
final String dirName = path.basename(dir.path); 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')) { if (file is File && file.path.endsWith('.dart')) {
yield '$dirName/${path.basename(file.path)}'; yield '$dirName/${path.basename(file.path)}';
} }

View File

@ -20,7 +20,7 @@ class CodeGenerator {
final StringBuffer result = StringBuffer(); final StringBuffer result = StringBuffer();
final List<String> words = input.split(RegExp(r'\s+')); final List<String> words = input.split(RegExp(r'\s+'));
String currentLine = words.removeAt(0); String currentLine = words.removeAt(0);
for (String word in words) { for (final String word in words) {
if ((currentLine.length + word.length) < wrapWidth) { if ((currentLine.length + word.length) < wrapWidth) {
currentLine += ' $word'; currentLine += ' $word';
} else { } else {
@ -37,7 +37,7 @@ class CodeGenerator {
/// Gets the generated definitions of PhysicalKeyboardKeys. /// Gets the generated definitions of PhysicalKeyboardKeys.
String get physicalDefinitions { String get physicalDefinitions {
final StringBuffer definitions = StringBuffer(); 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 ' final String firstComment = wrapString('Represents the location of the '
'"${entry.commentName}" key on a generalized keyboard.'); '"${entry.commentName}" key on a generalized keyboard.');
final String otherComments = wrapString('See the function ' 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( printKey(
entry.flutterId, entry.flutterId,
entry.keyLabel, entry.keyLabel,
@ -81,7 +81,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
entry.commentName, 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. // 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 // It won't end up being the same value because it'll be in the pseudo-key
// plane. // plane.
@ -99,8 +99,8 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
String get logicalSynonyms { String get logicalSynonyms {
final StringBuffer synonyms = StringBuffer(); final StringBuffer synonyms = StringBuffer();
for (String name in Key.synonyms.keys) { for (final String name in Key.synonyms.keys) {
for (String synonym in Key.synonyms[name].cast<String>()) { for (final String synonym in Key.synonyms[name].cast<String>()) {
final String keyName = upperCamelToLowerCamel(synonym); final String keyName = upperCamelToLowerCamel(synonym);
synonyms.writeln(' $keyName: $name,'); 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. /// This generates the map of USB HID codes to physical keys.
String get predefinedHidCodeMap { String get predefinedHidCodeMap {
final StringBuffer scanCodeMap = StringBuffer(); final StringBuffer scanCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
scanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: ${entry.constantName},'); scanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: ${entry.constantName},');
} }
return scanCodeMap.toString().trimRight(); 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. /// THis generates the map of Flutter key codes to logical keys.
String get predefinedKeyCodeMap { String get predefinedKeyCodeMap {
final StringBuffer keyCodeMap = StringBuffer(); 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},'); 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. // 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 // It won't end up being the same value because it'll be in the pseudo-key
// plane. // plane.
@ -152,9 +152,9 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
/// This generates the map of GLFW number pad key codes to logical keys. /// This generates the map of GLFW number pad key codes to logical keys.
String get glfwNumpadMap { String get glfwNumpadMap {
final StringBuffer glfwNumpadMap = StringBuffer(); final StringBuffer glfwNumpadMap = StringBuffer();
for (Key entry in numpadKeyData) { for (final Key entry in numpadKeyData) {
if (entry.glfwKeyCodes != null) { if (entry.glfwKeyCodes != null) {
for (int code in entry.glfwKeyCodes.cast<int>()) { for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwNumpadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of GLFW key codes to logical keys.
String get glfwKeyCodeMap { String get glfwKeyCodeMap {
final StringBuffer glfwKeyCodeMap = StringBuffer(); final StringBuffer glfwKeyCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.glfwKeyCodes != null) { if (entry.glfwKeyCodes != null) {
for (int code in entry.glfwKeyCodes.cast<int>()) { for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of XKB USB HID codes to physical keys.
String get xkbScanCodeMap { String get xkbScanCodeMap {
final StringBuffer xkbScanCodeMap = StringBuffer(); final StringBuffer xkbScanCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.xKbScanCode != null) { if (entry.xKbScanCode != null) {
xkbScanCodeMap.writeln(' ${toHex(entry.xKbScanCode)}: PhysicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Android key codes to logical keys.
String get androidKeyCodeMap { String get androidKeyCodeMap {
final StringBuffer androidKeyCodeMap = StringBuffer(); final StringBuffer androidKeyCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.androidKeyCodes != null) { if (entry.androidKeyCodes != null) {
for (int code in entry.androidKeyCodes.cast<int>()) { for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Android number pad key codes to logical keys.
String get androidNumpadMap { String get androidNumpadMap {
final StringBuffer androidKeyCodeMap = StringBuffer(); final StringBuffer androidKeyCodeMap = StringBuffer();
for (Key entry in numpadKeyData) { for (final Key entry in numpadKeyData) {
if (entry.androidKeyCodes != null) { if (entry.androidKeyCodes != null) {
for (int code in entry.androidKeyCodes.cast<int>()) { for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Android scan codes to physical keys.
String get androidScanCodeMap { String get androidScanCodeMap {
final StringBuffer androidScanCodeMap = StringBuffer(); final StringBuffer androidScanCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.androidScanCodes != null) { if (entry.androidScanCodes != null) {
for (int code in entry.androidScanCodes.cast<int>()) { for (final int code in entry.androidScanCodes.cast<int>()) {
androidScanCodeMap.writeln(' $code: PhysicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of macOS key codes to physical keys.
String get macOsScanCodeMap { String get macOsScanCodeMap {
final StringBuffer macOsScanCodeMap = StringBuffer(); final StringBuffer macOsScanCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.macOsScanCode != null) { if (entry.macOsScanCode != null) {
macOsScanCodeMap.writeln(' ${toHex(entry.macOsScanCode)}: PhysicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of macOS number pad key codes to logical keys.
String get macOsNumpadMap { String get macOsNumpadMap {
final StringBuffer macOsNumPadMap = StringBuffer(); final StringBuffer macOsNumPadMap = StringBuffer();
for (Key entry in numpadKeyData) { for (final Key entry in numpadKeyData) {
if (entry.macOsScanCode != null) { if (entry.macOsScanCode != null) {
macOsNumPadMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},'); macOsNumPadMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},');
} }
@ -249,7 +249,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
String get macOsFunctionKeyMap { String get macOsFunctionKeyMap {
final StringBuffer macOsFunctionKeyMap = StringBuffer(); final StringBuffer macOsFunctionKeyMap = StringBuffer();
for (Key entry in functionKeyData) { for (final Key entry in functionKeyData) {
if (entry.macOsScanCode != null) { if (entry.macOsScanCode != null) {
macOsFunctionKeyMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Fuchsia key codes to logical keys.
String get fuchsiaKeyCodeMap { String get fuchsiaKeyCodeMap {
final StringBuffer fuchsiaKeyCodeMap = StringBuffer(); final StringBuffer fuchsiaKeyCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.usbHidCode != null) { if (entry.usbHidCode != null) {
fuchsiaKeyCodeMap.writeln(' ${toHex(entry.flutterId)}: LogicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Fuchsia USB HID codes to physical keys.
String get fuchsiaHidCodeMap { String get fuchsiaHidCodeMap {
final StringBuffer fuchsiaScanCodeMap = StringBuffer(); final StringBuffer fuchsiaScanCodeMap = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.usbHidCode != null) { if (entry.usbHidCode != null) {
fuchsiaScanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: PhysicalKeyboardKey.${entry.constantName},'); 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. /// This generates the map of Web KeyboardEvent codes to logical keys.
String get webLogicalKeyMap { String get webLogicalKeyMap {
final StringBuffer result = StringBuffer(); final StringBuffer result = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.name != null) { if (entry.name != null) {
result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},"); 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. /// This generates the map of Web KeyboardEvent codes to physical keys.
String get webPhysicalKeyMap { String get webPhysicalKeyMap {
final StringBuffer result = StringBuffer(); final StringBuffer result = StringBuffer();
for (Key entry in keyData.data) { for (final Key entry in keyData.data) {
if (entry.name != null) { if (entry.name != null) {
result.writeln(" '${entry.name}': PhysicalKeyboardKey.${entry.constantName},"); 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. /// This generates the map of Web number pad codes to logical keys.
String get webNumpadMap { String get webNumpadMap {
final StringBuffer result = StringBuffer(); final StringBuffer result = StringBuffer();
for (Key entry in numpadKeyData) { for (final Key entry in numpadKeyData) {
if (entry.name != null) { if (entry.name != null) {
result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},"); result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},");
} }
@ -359,7 +359,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
static String _injectDictionary(String template, Map<String, String> dictionary) { static String _injectDictionary(String template, Map<String, String> dictionary) {
String result = template; String result = template;
for (String key in dictionary.keys) { for (final String key in dictionary.keys) {
result = result.replaceAll('@@@$key@@@', dictionary[key]); result = result.replaceAll('@@@$key@@@', dictionary[key]);
} }
return result; return result;

View File

@ -53,18 +53,18 @@ class KeyData {
/// Parses the given JSON data and populates the data structure from it. /// Parses the given JSON data and populates the data structure from it.
KeyData.fromJson(Map<String, dynamic> contentMap) { KeyData.fromJson(Map<String, dynamic> contentMap) {
data = <Key>[ data = <Key>[
for (String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map<String, List<dynamic>>), for (final String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map<String, List<dynamic>>),
]; ];
} }
/// Converts the data structure into a JSON structure that can be parsed by /// Converts the data structure into a JSON structure that can be parsed by
/// [KeyData.fromJson]. /// [KeyData.fromJson].
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
for (Key entry in data) { for (final Key entry in data) {
// Android Key names // Android Key names
entry.androidKeyNames = _nameToAndroidName[entry.constantName]?.cast<String>(); entry.androidKeyNames = _nameToAndroidName[entry.constantName]?.cast<String>();
if (entry.androidKeyNames != null && entry.androidKeyNames.isNotEmpty) { if (entry.androidKeyNames != null && entry.androidKeyNames.isNotEmpty) {
for (String androidKeyName in entry.androidKeyNames) { for (final String androidKeyName in entry.androidKeyNames) {
if (_nameToAndroidKeyCode[androidKeyName] != null) { if (_nameToAndroidKeyCode[androidKeyName] != null) {
entry.androidKeyCodes ??= <int>[]; entry.androidKeyCodes ??= <int>[];
entry.androidKeyCodes.add(_nameToAndroidKeyCode[androidKeyName]); entry.androidKeyCodes.add(_nameToAndroidKeyCode[androidKeyName]);
@ -79,7 +79,7 @@ class KeyData {
// GLFW key names // GLFW key names
entry.glfwKeyNames = _nameToGlfwName[entry.constantName]?.cast<String>(); entry.glfwKeyNames = _nameToGlfwName[entry.constantName]?.cast<String>();
if (entry.glfwKeyNames != null && entry.glfwKeyNames.isNotEmpty) { if (entry.glfwKeyNames != null && entry.glfwKeyNames.isNotEmpty) {
for (String glfwKeyName in entry.glfwKeyNames) { for (final String glfwKeyName in entry.glfwKeyNames) {
if (_nameToGlfwKeyCode[glfwKeyName] != null) { if (_nameToGlfwKeyCode[glfwKeyName] != null) {
entry.glfwKeyCodes ??= <int>[]; entry.glfwKeyCodes ??= <int>[];
entry.glfwKeyCodes.add(_nameToGlfwKeyCode[glfwKeyName]); entry.glfwKeyCodes.add(_nameToGlfwKeyCode[glfwKeyName]);
@ -89,7 +89,7 @@ class KeyData {
} }
final Map<String, dynamic> outputMap = <String, dynamic>{}; final Map<String, dynamic> outputMap = <String, dynamic>{};
for (Key entry in data) { for (final Key entry in data) {
outputMap[entry.constantName] = entry.toJson(); outputMap[entry.constantName] = entry.toJson();
} }
return outputMap; return outputMap;
@ -178,7 +178,7 @@ class KeyData {
headerFile = headerFile.replaceAllMapped(enumBlock, (Match match) => match.group(1)); headerFile = headerFile.replaceAllMapped(enumBlock, (Match match) => match.group(1));
final RegExp enumEntry = RegExp(r'''AKEYCODE_([A-Z0-9_]+)\s*=\s*([0-9]+),?'''); final RegExp enumEntry = RegExp(r'''AKEYCODE_([A-Z0-9_]+)\s*=\s*([0-9]+),?''');
final Map<String, int> result = <String, int>{}; final Map<String, int> result = <String, int>{};
for (Match match in enumEntry.allMatches(headerFile)) { for (final Match match in enumEntry.allMatches(headerFile)) {
result[match.group(1)] = int.parse(match.group(2)); result[match.group(1)] = int.parse(match.group(2));
} }
return result; return result;
@ -193,7 +193,7 @@ class KeyData {
// Only get the KEY definitions, ignore the rest (mouse, joystick, etc). // 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 RegExp enumEntry = RegExp(r'''define GLFW_KEY_([A-Z0-9_]+)\s*([A-Z0-9_]+),?''');
final Map<String, dynamic> replaced = <String, dynamic>{}; final Map<String, dynamic> replaced = <String, dynamic>{};
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_', ''); replaced[match.group(1)] = int.tryParse(match.group(2)) ?? match.group(2).replaceAll('GLFW_KEY_', '');
} }
final Map<String, int> result = <String, int>{}; final Map<String, int> result = <String, int>{};

View File

@ -56,7 +56,7 @@ Future<void> generateDocs(String url, String docName, String checkFile) async {
print('Extracting $docName to ${output.path}'); print('Extracting $docName to ${output.path}');
output.createSync(recursive: true); output.createSync(recursive: true);
for (ArchiveFile af in archive) { for (final ArchiveFile af in archive) {
if (!af.name.endsWith('/')) { if (!af.name.endsWith('/')) {
final File file = File('${output.path}/${af.name}'); final File file = File('${output.path}/${af.name}');
file.createSync(recursive: true); file.createSync(recursive: true);

View File

@ -36,7 +36,7 @@ Map<String, dynamic> loadBundle(File file) {
} }
void encodeBundleTranslations(Map<String, dynamic> bundle) { void encodeBundleTranslations(Map<String, dynamic> 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 // The ARB file resource "attributes" for foo are called @foo. Don't need
// to encode them. // to encode them.
if (key.startsWith('@')) if (key.startsWith('@'))
@ -54,7 +54,7 @@ void encodeBundleTranslations(Map<String, dynamic> bundle) {
void checkEncodedTranslations(Map<String, dynamic> encodedBundle, Map<String, dynamic> bundle) { void checkEncodedTranslations(Map<String, dynamic> encodedBundle, Map<String, dynamic> bundle) {
bool errorFound = false; bool errorFound = false;
const JsonDecoder decoder = JsonDecoder(); const JsonDecoder decoder = JsonDecoder();
for (String key in bundle.keys) { for (final String key in bundle.keys) {
if (decoder.convert('"${encodedBundle[key]}"') != bundle[key]) { if (decoder.convert('"${encodedBundle[key]}"') != bundle[key]) {
stderr.writeln(' encodedTranslation for $key does not match original value "${bundle[key]}"'); stderr.writeln(' encodedTranslation for $key does not match original value "${bundle[key]}"');
errorFound = true; errorFound = true;
@ -67,7 +67,7 @@ void checkEncodedTranslations(Map<String, dynamic> encodedBundle, Map<String, dy
void rewriteBundle(File file, Map<String, dynamic> bundle) { void rewriteBundle(File file, Map<String, dynamic> bundle) {
final StringBuffer contents = StringBuffer(); final StringBuffer contents = StringBuffer();
contents.writeln('{'); 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(' "$key": "${bundle[key]}"${key == bundle.keys.last ? '' : ','}');
} }
contents.writeln('}'); contents.writeln('}');

View File

@ -167,7 +167,7 @@ Set<String> _supportedLocales() {
final Set<String> supportedLocales = <String>{}; final Set<String> supportedLocales = <String>{};
final RegExp filenameRE = RegExp(r'(?:material|cupertino)_(\w+)\.arb$'); final RegExp filenameRE = RegExp(r'(?:material|cupertino)_(\w+)\.arb$');
final Directory supportedLocalesDirectory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n')); 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; final String filePath = entity.path;
if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath)) if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath))
supportedLocales.add(filenameRE.firstMatch(filePath)[1]); supportedLocales.add(filenameRE.firstMatch(filePath)[1]);
@ -181,7 +181,7 @@ Map<String, File> _listIntlData(Directory directory) {
.listSync() .listSync()
.whereType<File>() .whereType<File>()
.where((File file) => file.path.endsWith('.json')); .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); final String locale = path.basenameWithoutExtension(file.path);
localeFiles[locale] = file; localeFiles[locale] = file;
} }

View File

@ -87,7 +87,7 @@ String generateArbBasedLocalizationSubclasses({
// Used to calculate if there are any corresponding countries for a given language and script. // Used to calculate if there are any corresponding countries for a given language and script.
final Map<LocaleInfo, Set<String>> languageAndScriptToCountryCodes = <LocaleInfo, Set<String>>{}; final Map<LocaleInfo, Set<String>> languageAndScriptToCountryCodes = <LocaleInfo, Set<String>>{};
final Set<String> allResourceIdentifiers = <String>{}; final Set<String> allResourceIdentifiers = <String>{};
for (LocaleInfo locale in localeToResources.keys.toList()..sort()) { for (final LocaleInfo locale in localeToResources.keys.toList()..sort()) {
if (locale.scriptCode != null) { if (locale.scriptCode != null) {
languageToScriptCodes[locale.languageCode] ??= <String>{}; languageToScriptCodes[locale.languageCode] ??= <String>{};
languageToScriptCodes[locale.languageCode].add(locale.scriptCode); languageToScriptCodes[locale.languageCode].add(locale.scriptCode);
@ -129,13 +129,13 @@ String generateArbBasedLocalizationSubclasses({
final List<String> allKeys = allResourceIdentifiers.toList()..sort(); final List<String> allKeys = allResourceIdentifiers.toList()..sort();
final List<String> languageCodes = languageToLocales.keys.toList()..sort(); final List<String> languageCodes = languageToLocales.keys.toList()..sort();
final LocaleInfo canonicalLocale = LocaleInfo.fromString('en'); final LocaleInfo canonicalLocale = LocaleInfo.fromString('en');
for (String languageName in languageCodes) { for (final String languageName in languageCodes) {
final LocaleInfo languageLocale = LocaleInfo.fromString(languageName); final LocaleInfo languageLocale = LocaleInfo.fromString(languageName);
output.writeln(generateClassDeclaration(languageLocale, generatedClassPrefix, baseClass)); output.writeln(generateClassDeclaration(languageLocale, generatedClassPrefix, baseClass));
output.writeln(generateConstructor(languageLocale)); output.writeln(generateConstructor(languageLocale));
final Map<String, String> languageResources = localeToResources[languageLocale]; final Map<String, String> languageResources = localeToResources[languageLocale];
for (String key in allKeys) { for (final String key in allKeys) {
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale)); output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale));
} }
@ -146,7 +146,7 @@ String generateArbBasedLocalizationSubclasses({
scriptCodeCount = languageToScriptCodes[languageName].length; scriptCodeCount = languageToScriptCodes[languageName].length;
// Language has scriptCodes, so we need to properly fallback countries to corresponding // Language has scriptCodes, so we need to properly fallback countries to corresponding
// script default values before language default values. // 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); final LocaleInfo scriptBaseLocale = LocaleInfo.fromString(languageName + '_' + scriptCode);
output.writeln(generateClassDeclaration( output.writeln(generateClassDeclaration(
scriptBaseLocale, scriptBaseLocale,
@ -155,7 +155,7 @@ String generateArbBasedLocalizationSubclasses({
)); ));
output.writeln(generateConstructor(scriptBaseLocale)); output.writeln(generateConstructor(scriptBaseLocale));
final Map<String, String> scriptResources = localeToResources[scriptBaseLocale]; final Map<String, String> 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]) if (languageResources[key] == scriptResources[key])
continue; continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
@ -164,7 +164,7 @@ String generateArbBasedLocalizationSubclasses({
output.writeln('}'); output.writeln('}');
final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort(); final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
for (LocaleInfo locale in localeCodes) { for (final LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName) if (locale.originalString == languageName)
continue; continue;
if (locale.originalString == languageName + '_' + scriptCode) if (locale.originalString == languageName + '_' + scriptCode)
@ -179,7 +179,7 @@ String generateArbBasedLocalizationSubclasses({
)); ));
output.writeln(generateConstructor(locale)); output.writeln(generateConstructor(locale));
final Map<String, String> localeResources = localeToResources[locale]; final Map<String, String> 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. // When script fallback contains the key, we compare to it instead of language fallback.
if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key]) if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key])
continue; continue;
@ -193,7 +193,7 @@ String generateArbBasedLocalizationSubclasses({
// No scriptCode. Here, we do not compare against script default (because it // No scriptCode. Here, we do not compare against script default (because it
// doesn't exist). // doesn't exist).
final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort(); final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
for (LocaleInfo locale in localeCodes) { for (final LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName) if (locale.originalString == languageName)
continue; continue;
countryCodeCount += 1; countryCodeCount += 1;
@ -204,7 +204,7 @@ String generateArbBasedLocalizationSubclasses({
'$generatedClassPrefix${camelCase(languageLocale)}', '$generatedClassPrefix${camelCase(languageLocale)}',
)); ));
output.writeln(generateConstructor(locale)); output.writeln(generateConstructor(locale));
for (String key in localeResources.keys) { for (final String key in localeResources.keys) {
if (languageResources[key] == localeResources[key]) if (languageResources[key] == localeResources[key])
continue; continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
@ -262,7 +262,7 @@ $supportedLocales/// {@endtemplate}
/// [$baseClass.delegate]. /// [$baseClass.delegate].
$factoryDeclaration $factoryDeclaration
switch (locale.languageCode) {'''); switch (locale.languageCode) {''');
for (String language in languageToLocales.keys) { for (final String language in languageToLocales.keys) {
// Only one instance of the language. // Only one instance of the language.
if (languageToLocales[language].length == 1) { if (languageToLocales[language].length == 1) {
output.writeln(''' output.writeln('''
@ -272,7 +272,7 @@ $factoryDeclaration
output.writeln(''' output.writeln('''
case '$language': { case '$language': {
switch (locale.countryCode) {'''); switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) { for (final LocaleInfo locale in languageToLocales[language]) {
if (locale.originalString == language) if (locale.originalString == language)
continue; continue;
assert(locale.length > 1); assert(locale.length > 1);
@ -290,14 +290,14 @@ $factoryDeclaration
output.writeln(''' output.writeln('''
case '$language': { case '$language': {
switch (locale.scriptCode) {'''); switch (locale.scriptCode) {''');
for (String scriptCode in languageToScriptCodes[language]) { for (final String scriptCode in languageToScriptCodes[language]) {
final LocaleInfo scriptLocale = LocaleInfo.fromString(language + '_' + scriptCode); final LocaleInfo scriptLocale = LocaleInfo.fromString(language + '_' + scriptCode);
output.writeln(''' output.writeln('''
case '$scriptCode': {'''); case '$scriptCode': {''');
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) { if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln(''' output.writeln('''
switch (locale.countryCode) {'''); switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) { for (final LocaleInfo locale in languageToLocales[language]) {
if (locale.countryCode == null) if (locale.countryCode == null)
continue; continue;
else else
@ -326,7 +326,7 @@ $factoryDeclaration
} else { } else {
// Not Explicitly defined, fallback to first locale with the same language and // Not Explicitly defined, fallback to first locale with the same language and
// script: // script:
for (LocaleInfo locale in languageToLocales[language]) { for (final LocaleInfo locale in languageToLocales[language]) {
if (locale.scriptCode != scriptCode) if (locale.scriptCode != scriptCode)
continue; continue;
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) { if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
@ -345,7 +345,7 @@ $factoryDeclaration
if (hasCountryCode) { if (hasCountryCode) {
output.writeln(''' output.writeln('''
switch (locale.countryCode) {'''); switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) { for (final LocaleInfo locale in languageToLocales[language]) {
if (locale.originalString == language) if (locale.originalString == language)
continue; continue;
assert(locale.length > 1); assert(locale.length > 1);

View File

@ -270,7 +270,7 @@ String generateDateFormattingLogic(Map<String, dynamic> bundle, String key) {
final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap != null && attributesMap.containsKey('placeholders')) { if (attributesMap != null && attributesMap.containsKey('placeholders')) {
final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
for (String placeholder in placeholders.keys) { for (final String placeholder in placeholders.keys) {
final dynamic value = placeholders[placeholder]; final dynamic value = placeholders[placeholder];
if ( if (
value is Map<String, dynamic> && value is Map<String, dynamic> &&
@ -302,7 +302,7 @@ List<String> genIntlMethodArgs(Map<String, dynamic> bundle, String key) {
final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
if (placeholders.isNotEmpty) { if (placeholders.isNotEmpty) {
final List<String> argumentList = <String>[]; final List<String> argumentList = <String>[];
for (String placeholder in placeholders.keys) { for (final String placeholder in placeholders.keys) {
final dynamic value = placeholders[placeholder]; final dynamic value = placeholders[placeholder];
if ( if (
value is Map<String, dynamic> && value is Map<String, dynamic> &&
@ -328,7 +328,7 @@ String genSimpleMethod(Map<String, dynamic> bundle, String key) {
String message = bundle[key] as String; String message = bundle[key] as String;
final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
for (String placeholder in placeholders.keys) { for (final String placeholder in placeholders.keys) {
final dynamic value = placeholders[placeholder]; final dynamic value = placeholders[placeholder];
if (value is Map<String, dynamic> && _isDateParameter(value)) { if (value is Map<String, dynamic> && _isDateParameter(value)) {
message = message.replaceAll('{$placeholder}', '\$${placeholder}String'); message = message.replaceAll('{$placeholder}', '\$${placeholder}String');
@ -388,7 +388,7 @@ String genPluralMethod(Map<String, dynamic> arbBundle, String resourceId) {
// To make it easier to parse the plurals message, temporarily replace each // To make it easier to parse the plurals message, temporarily replace each
// "{placeholder}" parameter with "#placeholder#". // "{placeholder}" parameter with "#placeholder#".
String message = arbBundle[resourceId] as String; String message = arbBundle[resourceId] as String;
for (String placeholder in placeholders) for (final String placeholder in placeholders)
message = message.replaceAll('{$placeholder}', '#$placeholder#'); message = message.replaceAll('{$placeholder}', '#$placeholder#');
final Map<String, String> pluralIds = <String, String>{ final Map<String, String> pluralIds = <String, String>{
@ -406,12 +406,12 @@ String genPluralMethod(Map<String, dynamic> arbBundle, String resourceId) {
...genIntlMethodArgs(arbBundle, resourceId), ...genIntlMethodArgs(arbBundle, resourceId),
]; ];
for (String pluralKey in pluralIds.keys) { for (final String pluralKey in pluralIds.keys) {
final RegExp expRE = RegExp('($pluralKey){([^}]+)}'); final RegExp expRE = RegExp('($pluralKey){([^}]+)}');
final RegExpMatch match = expRE.firstMatch(message); final RegExpMatch match = expRE.firstMatch(message);
if (match != null && match.groupCount == 2) { if (match != null && match.groupCount == 2) {
String argValue = match.group(2); String argValue = match.group(2);
for (String placeholder in placeholders) { for (final String placeholder in placeholders) {
final dynamic value = placeholdersMap[placeholder]; final dynamic value = placeholdersMap[placeholder];
if (value is Map<String, dynamic> && _isDateParameter(value)) { if (value is Map<String, dynamic> && _isDateParameter(value)) {
argValue = argValue.replaceAll('#$placeholder#', '\$${placeholder}String'); argValue = argValue.replaceAll('#$placeholder#', '\$${placeholder}String');
@ -435,7 +435,7 @@ String genSupportedLocaleProperty(Set<LocaleInfo> supportedLocales) {
const String suffix = '),\n ];'; const String suffix = '),\n ];';
String resultingProperty = prefix; String resultingProperty = prefix;
for (LocaleInfo locale in supportedLocales) { for (final LocaleInfo locale in supportedLocales) {
final String languageCode = locale.languageCode; final String languageCode = locale.languageCode;
final String countryCode = locale.countryCode; final String countryCode = locale.countryCode;
@ -668,7 +668,7 @@ class LocalizationsGenerator {
.toList(); .toList();
final List<LocaleInfo> localeInfoList = <LocaleInfo>[]; final List<LocaleInfo> localeInfoList = <LocaleInfo>[];
for (File file in fileSystemEntityList) { for (final File file in fileSystemEntityList) {
final String filePath = file.path; final String filePath = file.path;
if (arbFilenameRE.hasMatch(filePath)) { if (arbFilenameRE.hasMatch(filePath)) {
final Map<String, dynamic> arbContents = json.decode(file.readAsStringSync()) as Map<String, dynamic>; final Map<String, dynamic> arbContents = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
@ -705,7 +705,7 @@ class LocalizationsGenerator {
})); }));
if (preferredSupportedLocales != null) { if (preferredSupportedLocales != null) {
for (LocaleInfo preferredLocale in preferredSupportedLocales) { for (final LocaleInfo preferredLocale in preferredSupportedLocales) {
if (!localeInfoList.contains(preferredLocale)) { if (!localeInfoList.contains(preferredLocale)) {
throw L10nException( throw L10nException(
'The preferred supported locale, \'$preferredLocale\', cannot be ' 'The preferred supported locale, \'$preferredLocale\', cannot be '
@ -750,7 +750,7 @@ class LocalizationsGenerator {
} }
final List<String> sortedArbKeys = bundle.keys.toList()..sort(); final List<String> sortedArbKeys = bundle.keys.toList()..sort();
for (String key in sortedArbKeys) { for (final String key in sortedArbKeys) {
if (key.startsWith('@')) if (key.startsWith('@'))
continue; continue;
if (!_isValidGetterAndMethodName(key)) if (!_isValidGetterAndMethodName(key))

View File

@ -155,7 +155,7 @@ void loadMatchingArbsIntoBundleMaps({
/// overwrite the existing assumed data. /// overwrite the existing assumed data.
final Set<LocaleInfo> assumedLocales = <LocaleInfo>{}; final Set<LocaleInfo> assumedLocales = <LocaleInfo>{};
for (FileSystemEntity entity in directory.listSync().toList()..sort(sortFilesByPath)) { for (final FileSystemEntity entity in directory.listSync().toList()..sort(sortFilesByPath)) {
final String entityPath = entity.path; final String entityPath = entity.path;
if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) { if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) {
final String localeString = filenamePattern.firstMatch(entityPath)[1]; final String localeString = filenamePattern.firstMatch(entityPath)[1];
@ -166,7 +166,7 @@ void loadMatchingArbsIntoBundleMaps({
final Map<String, String> resources = localeToResources[locale]; final Map<String, String> resources = localeToResources[locale];
final Map<String, dynamic> attributes = localeToResourceAttributes[locale]; final Map<String, dynamic> attributes = localeToResourceAttributes[locale];
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>; final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (String key in bundle.keys) { for (final String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo. // The ARB file resource "attributes" for foo are called @foo.
if (key.startsWith('@')) if (key.startsWith('@'))
attributes[key.substring(1)] = bundle[key]; attributes[key.substring(1)] = bundle[key];
@ -270,7 +270,7 @@ const String registry = 'https://www.iana.org/assignments/language-subtag-regist
Map<String, List<String>> _parseSection(String section) { Map<String, List<String>> _parseSection(String section) {
final Map<String, List<String>> result = <String, List<String>>{}; final Map<String, List<String>> result = <String, List<String>>{};
List<String> lastHeading; List<String> lastHeading;
for (String line in section.split('\n')) { for (final String line in section.split('\n')) {
if (line == '') if (line == '')
continue; continue;
if (line.startsWith(' ')) { if (line.startsWith(' ')) {
@ -304,7 +304,7 @@ Future<void> precacheLanguageAndRegionTags() async {
final String body = (await response.cast<List<int>>().transform<String>(utf8.decoder).toList()).join(''); final String body = (await response.cast<List<int>>().transform<String>(utf8.decoder).toList()).join('');
client.close(force: true); client.close(force: true);
final List<Map<String, List<String>>> sections = body.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList(); final List<Map<String, List<String>>> sections = body.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList();
for (Map<String, List<String>> section in sections) { for (final Map<String, List<String>> section in sections) {
assert(section.containsKey('Type'), section.toString()); assert(section.containsKey('Type'), section.toString());
final String type = section['Type'].single; final String type = section['Type'].single;
if (type == 'language' || type == 'region' || type == 'script') { if (type == 'language' || type == 'region' || type == 'script') {

View File

@ -38,7 +38,7 @@ void validateEnglishLocalizations(File file) {
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>; final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (String resourceId in bundle.keys) { for (final String resourceId in bundle.keys) {
if (resourceId.startsWith('@')) if (resourceId.startsWith('@'))
continue; continue;
@ -55,7 +55,7 @@ void validateEnglishLocalizations(File file) {
errorMessages.writeln('A value was not specified for @$resourceId'); 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('@')) if (!atResourceId.startsWith('@'))
continue; continue;

View File

@ -134,7 +134,7 @@ void _copy(Directory source, Directory target) {
if (!target.existsSync()) if (!target.existsSync())
target.createSync(recursive: true); 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); final String name = path.basename(entity.path);
if (entity is Directory) { if (entity is Directory) {
@ -165,7 +165,7 @@ class SourceStats {
SourceStats getStatsFor(Directory dir, [SourceStats stats]) { SourceStats getStatsFor(Directory dir, [SourceStats stats]) {
stats ??= SourceStats(); 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); final String name = path.basename(entity.path);
if (entity is File && name.endsWith('.dart')) { if (entity is File && name.endsWith('.dart')) {
stats.files += 1; stats.files += 1;

View File

@ -182,7 +182,7 @@ void main(List<String> args) {
String regenerateIconsFile(String iconData, String codepointData) { String regenerateIconsFile(String iconData, String codepointData) {
final StringBuffer buf = StringBuffer(); final StringBuffer buf = StringBuffer();
bool generating = false; bool generating = false;
for (String line in LineSplitter.split(iconData)) { for (final String line in LineSplitter.split(iconData)) {
if (!generating) if (!generating)
buf.writeln(line); buf.writeln(line);
if (line.contains(kBeginGeneratedMark)) { if (line.contains(kBeginGeneratedMark)) {

View File

@ -65,7 +65,7 @@ void main(List<String> args) {
} }
final List<FrameData> frames = <FrameData>[ final List<FrameData> frames = <FrameData>[
for (String filePath in argResults.rest) interpretSvg(filePath), for (final String filePath in argResults.rest) interpretSvg(filePath),
]; ];
final StringBuffer generatedSb = StringBuffer(); final StringBuffer generatedSb = StringBuffer();

View File

@ -59,7 +59,7 @@ class Animation {
sb.write('const $className $varName = const $className(\n'); sb.write('const $className $varName = const $className(\n');
sb.write('${kIndent}const Size(${size.x}, ${size.y}),\n'); sb.write('${kIndent}const Size(${size.x}, ${size.y}),\n');
sb.write('${kIndent}const <_PathFrames>[\n'); sb.write('${kIndent}const <_PathFrames>[\n');
for (PathAnimation path in paths) for (final PathAnimation path in paths)
sb.write(path.toDart()); sb.write(path.toDart());
sb.write('$kIndent],\n'); sb.write('$kIndent],\n');
sb.write(');'); sb.write(');');
@ -117,11 +117,11 @@ class PathAnimation {
final StringBuffer sb = StringBuffer(); final StringBuffer sb = StringBuffer();
sb.write('${kIndent * 2}const _PathFrames(\n'); sb.write('${kIndent * 2}const _PathFrames(\n');
sb.write('${kIndent * 3}opacities: const <double>[\n'); sb.write('${kIndent * 3}opacities: const <double>[\n');
for (double opacity in opacities) for (final double opacity in opacities)
sb.write('${kIndent * 4}$opacity,\n'); sb.write('${kIndent * 4}$opacity,\n');
sb.write('${kIndent * 3}],\n'); sb.write('${kIndent * 3}],\n');
sb.write('${kIndent * 3}commands: const <_PathCommand>[\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(command.toDart());
sb.write('${kIndent * 3}],\n'); sb.write('${kIndent * 3}],\n');
sb.write('${kIndent * 2}),\n'); sb.write('${kIndent * 2}),\n');
@ -166,9 +166,9 @@ class PathCommandAnimation {
} }
final StringBuffer sb = StringBuffer(); final StringBuffer sb = StringBuffer();
sb.write('${kIndent * 4}const $dartCommandClass(\n'); sb.write('${kIndent * 4}const $dartCommandClass(\n');
for (List<Point<double>> pointFrames in points) { for (final List<Point<double>> pointFrames in points) {
sb.write('${kIndent * 5}const <Offset>[\n'); sb.write('${kIndent * 5}const <Offset>[\n');
for (Point<double> point in pointFrames) for (final Point<double> point in pointFrames)
sb.write('${kIndent * 6}const Offset(${point.x}, ${point.y}),\n'); sb.write('${kIndent * 6}const Offset(${point.x}, ${point.y}),\n');
sb.write('${kIndent * 5}],\n'); sb.write('${kIndent * 5}],\n');
} }
@ -201,7 +201,7 @@ FrameData interpretSvg(String svgFilePath) {
List<SvgPath> _interpretSvgGroup(List<XmlNode> children, _Transform transform) { List<SvgPath> _interpretSvgGroup(List<XmlNode> children, _Transform transform) {
final List<SvgPath> paths = <SvgPath>[]; final List<SvgPath> paths = <SvgPath>[];
for (XmlNode node in children) { for (final XmlNode node in children) {
if (node.nodeType != XmlNodeType.ELEMENT) if (node.nodeType != XmlNodeType.ELEMENT)
continue; continue;
final XmlElement element = node as XmlElement; final XmlElement element = node as XmlElement;
@ -304,7 +304,7 @@ class SvgPath {
final SvgPathCommandBuilder commandsBuilder = SvgPathCommandBuilder(); final SvgPathCommandBuilder commandsBuilder = SvgPathCommandBuilder();
if (!_pathCommandValidator.hasMatch(dAttr)) if (!_pathCommandValidator.hasMatch(dAttr))
throw Exception('illegal or unsupported path d expression: $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 commandType = match.group(1);
final String pointStr = match.group(2); final String pointStr = match.group(2);
commands.add(commandsBuilder.build(commandType, parsePoints(pointStr))); commands.add(commandsBuilder.build(commandType, parsePoints(pointStr)));
@ -469,7 +469,7 @@ Matrix3 _parseSvgTransform(String transform) {
throw Exception('illegal or unsupported transform: $transform'); throw Exception('illegal or unsupported transform: $transform');
final Iterable<Match> matches =_transformCommand.allMatches(transform).toList().reversed; final Iterable<Match> matches =_transformCommand.allMatches(transform).toList().reversed;
Matrix3 result = Matrix3.identity(); Matrix3 result = Matrix3.identity();
for (Match m in matches) { for (final Match m in matches) {
final String command = m.group(1); final String command = m.group(1);
final String params = m.group(2); final String params = m.group(2);
if (command == 'translate') { if (command == 'translate') {

View File

@ -146,7 +146,7 @@ void generate(String commit) {
initialize(); initialize();
final List<SampleInfo> samples = <SampleInfo>[]; final List<SampleInfo> samples = <SampleInfo>[];
for (FileSystemEntity entity in sampleDirectory.listSync()) { for (final FileSystemEntity entity in sampleDirectory.listSync()) {
if (entity is File && entity.path.endsWith('.dart')) { if (entity is File && entity.path.endsWith('.dart')) {
final SampleInfo sample = SampleInfo(entity, commit); final SampleInfo sample = SampleInfo(entity, commit);
if (sample.initialize()) // skip files that lack the Sample Catalog comment 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 // Write the sample app files, like animated_list.md
for (SampleInfo sample in samples) { for (final SampleInfo sample in samples) {
writeExpandedTemplate( writeExpandedTemplate(
outputFile(sample.sourceName + '.md'), outputFile(sample.sourceName + '.md'),
inputFile('bin', 'sample_page.md.template').readAsStringSync(), 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 // that feature one class. For example AnimatedList_index.md would only
// include samples that had AnimatedList in their "Classes:" list. // include samples that had AnimatedList in their "Classes:" list.
final Map<String, List<SampleInfo>> classToSamples = <String, List<SampleInfo>>{}; final Map<String, List<SampleInfo>> classToSamples = <String, List<SampleInfo>>{};
for (SampleInfo sample in samples) { for (final SampleInfo sample in samples) {
for (String className in sample.highlightedClasses) { for (final String className in sample.highlightedClasses) {
classToSamples[className] ??= <SampleInfo>[]; classToSamples[className] ??= <SampleInfo>[];
classToSamples[className].add(sample); classToSamples[className].add(sample);
} }
} }
for (String className in classToSamples.keys) { for (final String className in classToSamples.keys) {
final Iterable<String> entries = classToSamples[className].map<String>((SampleInfo sample) { final Iterable<String> entries = classToSamples[className].map<String>((SampleInfo sample) {
return expandTemplate(entryTemplate, sample.commentValues); 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. // For now, the website's index.json file must be updated by hand.
logMessage('The following entries must appear in _data/catalog/widgets.json'); 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"'); logMessage('"sample": "${className}_index"');
} }

View File

@ -13,11 +13,11 @@ void main() {
await tester.pump(); await tester.pump();
// Initially only the top level EntryItems (the "chapters") are present. // 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); 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); 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); expect(find.text(item.title), findsNothing);
} }
} }
@ -34,15 +34,15 @@ void main() {
// Expand the chapters. Now the chapter and sections, but not the // Expand the chapters. Now the chapter and sections, but not the
// items, should be present. // 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); 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); 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); expect(find.text(section.title), findsOneWidget);
await scrollUpOneEntry(); await scrollUpOneEntry();
for (Entry item in section.children) for (final Entry item in section.children)
expect(find.text(item.title), findsNothing); expect(find.text(item.title), findsNothing);
} }
await scrollUpOneEntry(); await scrollUpOneEntry();
@ -53,8 +53,8 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
// Expand the sections. Now Widgets for all three levels should be present. // Expand the sections. Now Widgets for all three levels should be present.
for (Entry chapter in expansion_tile_sample.data) { for (final Entry chapter in expansion_tile_sample.data) {
for (Entry section in chapter.children) { for (final Entry section in chapter.children) {
await tapEntry(section.title); await tapEntry(section.title);
await scrollUpOneEntry(); await scrollUpOneEntry();
} }
@ -65,11 +65,11 @@ void main() {
// Working in reverse order, so we don't need to do anymore scrolling, // Working in reverse order, so we don't need to do anymore scrolling,
// check that everything is visible and close the sections and // check that everything is visible and close the sections and
// chapters as we go up. // 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); 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); 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); expect(find.text(item.title), findsOneWidget);
await tapEntry(section.title); // close the section await tapEntry(section.title); // close the section
} }
@ -77,11 +77,11 @@ void main() {
} }
// Finally only the top level EntryItems (the "chapters") are present. // 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); 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); 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); expect(find.text(item.title), findsNothing);
} }
} }

View File

@ -158,14 +158,14 @@ class _BottomNavigationDemoState extends State<BottomNavigationDemo>
@override @override
void dispose() { void dispose() {
for (NavigationIconView view in _navigationViews) for (final NavigationIconView view in _navigationViews)
view.controller.dispose(); view.controller.dispose();
super.dispose(); super.dispose();
} }
Widget _buildTransitionsStack() { Widget _buildTransitionsStack() {
final List<FadeTransition> transitions = <FadeTransition>[ final List<FadeTransition> transitions = <FadeTransition>[
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. // We want to have the newly animating (fading in) views on top.

View File

@ -260,7 +260,7 @@ class _ChipDemoState extends State<ChipDemo> {
Set<String> allowedActions = <String>{}; Set<String> allowedActions = <String>{};
if (_selectedMaterial != null && _selectedMaterial.isNotEmpty) { if (_selectedMaterial != null && _selectedMaterial.isNotEmpty) {
for (String tool in _selectedTools) { for (final String tool in _selectedTools) {
allowedActions.addAll(_toolActions[tool]); allowedActions.addAll(_toolActions[tool]);
} }
allowedActions = allowedActions.intersection(_materialActions[_selectedMaterial]); allowedActions = allowedActions.intersection(_materialActions[_selectedMaterial]);

View File

@ -135,7 +135,7 @@ class DessertDataSource extends DataTableSource {
int get selectedRowCount => _selectedCount; int get selectedRowCount => _selectedCount;
void _selectAll(bool checked) { void _selectAll(bool checked) {
for (Dessert dessert in _desserts) for (final Dessert dessert in _desserts)
dessert.selected = checked; dessert.selected = checked;
_selectedCount = checked ? _desserts.length : 0; _selectedCount = checked ? _desserts.length : 0;
notifyListeners(); notifyListeners();

View File

@ -476,7 +476,7 @@ class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
return; return;
} }
for (int product in difference) { for (final int product in difference) {
if (_internalList.length < _list.length) { if (_internalList.length < _list.length) {
_list.remove(product); _list.remove(product);
} else if (_internalList.length > _list.length) { } else if (_internalList.length > _list.length) {

View File

@ -294,8 +294,7 @@ class _ConnectivityOverlayState extends State<ConnectivityOverlay> {
final Connectivity connectivity = Connectivity(); final Connectivity connectivity = Connectivity();
ConnectivityResult previousResult = await connectivity.checkConnectivity(); ConnectivityResult previousResult = await connectivity.checkConnectivity();
yield previousResult; yield previousResult;
await for (ConnectivityResult result await for (final ConnectivityResult result in connectivity.onConnectivityChanged) {
in connectivity.onConnectivityChanged) {
if (result != previousResult) { if (result != previousResult) {
yield result; yield result;
previousResult = result; previousResult = result;

View File

@ -27,7 +27,7 @@ Future<void> _parseExampleCode(AssetBundle bundle) async {
List<String> codeBlock; List<String> codeBlock;
String codeTag; String codeTag;
for (String line in lines) { for (final String line in lines) {
if (codeBlock == null) { if (codeBlock == null) {
// Outside a block. // Outside a block.
if (line.startsWith(_kStartTag)) { if (line.startsWith(_kStartTag)) {

View File

@ -94,7 +94,7 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
final List<TextSpan> formattedText = <TextSpan>[]; final List<TextSpan> formattedText = <TextSpan>[];
int currentPosition = 0; int currentPosition = 0;
for (_HighlightSpan span in _spans) { for (final _HighlightSpan span in _spans) {
if (currentPosition != span.start) if (currentPosition != span.start)
formattedText.add(TextSpan(text: _src.substring(currentPosition, span.start))); formattedText.add(TextSpan(text: _src.substring(currentPosition, span.start)));

View File

@ -61,10 +61,10 @@ Future<void> main() async {
print('Starting app...'); print('Starting app...');
runApp(const GalleryApp(testMode: true)); runApp(const GalleryApp(testMode: true));
final _LiveWidgetController controller = _LiveWidgetController(WidgetsBinding.instance); final _LiveWidgetController controller = _LiveWidgetController(WidgetsBinding.instance);
for (GalleryDemoCategory category in kAllGalleryDemoCategories) { for (final GalleryDemoCategory category in kAllGalleryDemoCategories) {
print('Tapping "${category.name}" section...'); print('Tapping "${category.name}" section...');
await controller.tap(find.text(category.name)); 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); final Finder demoItem = find.text(demo.title);
print('Scrolling to "${demo.title}"...'); print('Scrolling to "${demo.title}"...');
await controller.scrollIntoView(demoItem, alignment: 0.5); await controller.scrollIntoView(demoItem, alignment: 0.5);

View File

@ -42,7 +42,7 @@ void verifyToStringOutput(String name, String route, String testString) {
final List<String> lines = testString.split('\n'); final List<String> lines = testString.split('\n');
if (!testString.endsWith('\n')) if (!testString.endsWith('\n'))
reportToStringError(name, route, lines.length, lines, 'does not end with a line feed'); 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; lineNumber += 1;
if (line == '' && lineNumber != lines.length) { if (line == '' && lineNumber != lines.length) {
reportToStringError(name, route, lineNumber, lines, 'found empty line'); reportToStringError(name, route, lineNumber, lines, 'found empty line');
@ -157,11 +157,11 @@ Future<void> smokeGallery(WidgetTester tester) async {
expect(find.text(kGalleryTitle), findsOneWidget); 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 Scrollable.ensureVisible(tester.element(find.text(category.name)), alignment: 0.5);
await tester.tap(find.text(category.name)); await tester.tap(find.text(category.name));
await tester.pumpAndSettle(); 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 Scrollable.ensureVisible(tester.element(find.text(demo.title)), alignment: 0.0);
await smokeDemo(tester, demo); await smokeDemo(tester, demo);
tester.binding.debugAssertNoTransientCallbacks('A transient callback was still active after running $demo'); tester.binding.debugAssertNoTransientCallbacks('A transient callback was still active after running $demo');

View File

@ -69,7 +69,7 @@ Future<void> saveDurationsHistogram(List<Map<String, dynamic>> events, String ou
int frameStart; int frameStart;
// Save the duration of the first frame after each 'Start Transition' event. // Save the duration of the first frame after each 'Start Transition' event.
for (Map<String, dynamic> event in events) { for (final Map<String, dynamic> event in events) {
final String eventName = event['name'] as String; final String eventName = event['name'] as String;
if (eventName == 'Start Transition') { if (eventName == 'Start Transition') {
assert(startEvent == null); assert(startEvent == null);
@ -143,7 +143,7 @@ Future<void> runDemos(List<String> demos, FlutterDriver driver) async {
final SerializableFinder demoList = find.byValueKey('GalleryDemoList'); final SerializableFinder demoList = find.byValueKey('GalleryDemoList');
String currentDemoCategory; String currentDemoCategory;
for (String demo in demos) { for (final String demo in demos) {
if (kSkippedDemos.contains(demo)) if (kSkippedDemos.contains(demo))
continue; continue;

View File

@ -79,7 +79,7 @@ void beginFrame(Duration timeStamp) {
void handlePointerDataPacket(ui.PointerDataPacket packet) { void handlePointerDataPacket(ui.PointerDataPacket packet) {
// The pointer packet contains a number of pointer movements, which we iterate // The pointer packet contains a number of pointer movements, which we iterate
// through and process. // 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 (datum.change == ui.PointerChange.down) {
// If the pointer went down, we change the color of the circle to blue. // If the pointer went down, we change the color of the circle to blue.
color = const ui.Color(0xFF0000FF); color = const ui.Color(0xFF0000FF);

View File

@ -94,7 +94,7 @@ class RenderDots extends RenderBox {
canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFFFFFF)); canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFFFFFF));
// We iterate through our model and paint each dot. // 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); dot.paint(canvas, offset);
} }
} }

View File

@ -31,7 +31,7 @@ class RenderDots extends RenderConstrainedBox {
canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF)); canvas.drawRect(offset & size, Paint()..color = const Color(0xFF0000FF));
final Paint paint = Paint()..color = const Color(0xFF00FF00); 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); canvas.drawCircle(point, 50.0, paint);
super.paint(context, offset); super.paint(context, offset);

View File

@ -56,7 +56,7 @@ class StockData extends ChangeNotifier {
bool get loading => _httpClient != null; bool get loading => _httpClient != null;
void add(List<dynamic> data) { void add(List<dynamic> data) {
for (List<dynamic> fields in data.cast<List<dynamic>>()) { for (final List<dynamic> fields in data.cast<List<dynamic>>()) {
final Stock stock = Stock.fromFields(fields.cast<String>()); final Stock stock = Stock.fromFields(fields.cast<String>());
_symbols.add(stock.symbol); _symbols.add(stock.symbol);
_stocks[stock.symbol] = stock; _stocks[stock.symbol] = stock;

View File

@ -118,7 +118,7 @@ mixin AnimationLocalListenersMixin {
/// will not change which listeners are called during this iteration. /// will not change which listeners are called during this iteration.
void notifyListeners() { void notifyListeners() {
final List<VoidCallback> localListeners = List<VoidCallback>.from(_listeners); final List<VoidCallback> localListeners = List<VoidCallback>.from(_listeners);
for (VoidCallback listener in localListeners) { for (final VoidCallback listener in localListeners) {
try { try {
if (_listeners.contains(listener)) if (_listeners.contains(listener))
listener(); listener();
@ -187,7 +187,7 @@ mixin AnimationLocalStatusListenersMixin {
/// will not change which listeners are called during this iteration. /// will not change which listeners are called during this iteration.
void notifyStatusListeners(AnimationStatus status) { void notifyStatusListeners(AnimationStatus status) {
final List<AnimationStatusListener> localListeners = List<AnimationStatusListener>.from(_statusListeners); final List<AnimationStatusListener> localListeners = List<AnimationStatusListener>.from(_statusListeners);
for (AnimationStatusListener listener in localListeners) { for (final AnimationStatusListener listener in localListeners) {
try { try {
if (_statusListeners.contains(listener)) if (_statusListeners.contains(listener))
listener(status); listener(status);

View File

@ -57,7 +57,7 @@ class TweenSequence<T> extends Animatable<T> {
_items.addAll(items); _items.addAll(items);
double totalWeight = 0.0; double totalWeight = 0.0;
for (TweenSequenceItem<T> item in _items) for (final TweenSequenceItem<T> item in _items)
totalWeight += item.weight; totalWeight += item.weight;
assert(totalWeight > 0.0); assert(totalWeight > 0.0);

View File

@ -1572,7 +1572,7 @@ class _CupertinoTimerPickerState extends State<CupertinoTimerPicker> {
// that has the biggest width. // that has the biggest width.
// - If two different 1-digit numbers are of the same width, their corresponding // - If two different 1-digit numbers are of the same width, their corresponding
// 2 digit numbers are of the same width. // 2 digit numbers are of the same width.
for (String input in numbers) { for (final String input in numbers) {
textPainter.text = TextSpan( textPainter.text = TextSpan(
text: input, text: input,
style: textStyle, style: textStyle,

View File

@ -257,13 +257,13 @@ class _SegmentedControlState<T> extends State<CupertinoSegmentedControl<T>>
void _updateAnimationControllers() { void _updateAnimationControllers() {
assert(mounted, 'This should only be called after didUpdateDependencies'); assert(mounted, 'This should only be called after didUpdateDependencies');
for (AnimationController controller in _selectionControllers) { for (final AnimationController controller in _selectionControllers) {
controller.dispose(); controller.dispose();
} }
_selectionControllers.clear(); _selectionControllers.clear();
_childTweens.clear(); _childTweens.clear();
for (T key in widget.children.keys) { for (final T key in widget.children.keys) {
final AnimationController animationController = createAnimationController(); final AnimationController animationController = createAnimationController();
if (widget.groupValue == key) { if (widget.groupValue == key) {
_childTweens.add(_reverseBackgroundColorTween); _childTweens.add(_reverseBackgroundColorTween);
@ -294,7 +294,7 @@ class _SegmentedControlState<T> extends State<CupertinoSegmentedControl<T>>
if (oldWidget.groupValue != widget.groupValue) { if (oldWidget.groupValue != widget.groupValue) {
int index = 0; int index = 0;
for (T key in widget.children.keys) { for (final T key in widget.children.keys) {
if (widget.groupValue == key) { if (widget.groupValue == key) {
_childTweens[index] = _forwardBackgroundColorTween; _childTweens[index] = _forwardBackgroundColorTween;
_selectionControllers[index].forward(); _selectionControllers[index].forward();
@ -309,7 +309,7 @@ class _SegmentedControlState<T> extends State<CupertinoSegmentedControl<T>>
@override @override
void dispose() { void dispose() {
for (AnimationController animationController in _selectionControllers) { for (final AnimationController animationController in _selectionControllers) {
animationController.dispose(); animationController.dispose();
} }
super.dispose(); super.dispose();
@ -364,7 +364,7 @@ class _SegmentedControlState<T> extends State<CupertinoSegmentedControl<T>>
int index = 0; int index = 0;
int selectedIndex; int selectedIndex;
int pressedIndex; int pressedIndex;
for (T currentKey in widget.children.keys) { for (final T currentKey in widget.children.keys) {
selectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex; selectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex;
pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex; pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex;
@ -629,7 +629,7 @@ class _RenderSegmentedControl<T> extends RenderBox
double maxHeight = _kMinSegmentedControlHeight; double maxHeight = _kMinSegmentedControlHeight;
double childWidth = constraints.minWidth / childCount; 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.max(childWidth, child.getMaxIntrinsicWidth(double.infinity));
} }
childWidth = math.min(childWidth, constraints.maxWidth / childCount); childWidth = math.min(childWidth, constraints.maxWidth / childCount);

View File

@ -301,7 +301,7 @@ class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T
vsync: this, vsync: this,
); );
for (T currentKey in widget.children.keys) { for (final T currentKey in widget.children.keys) {
_highlightControllers[currentKey] = _createHighlightAnimationController( _highlightControllers[currentKey] = _createHighlightAnimationController(
isCompleted: currentKey == widget.groupValue, // Highlight the current selection. isCompleted: currentKey == widget.groupValue, // Highlight the current selection.
); );
@ -314,7 +314,7 @@ class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
// Update animation controllers. // Update animation controllers.
for (T oldKey in oldWidget.children.keys) { for (final T oldKey in oldWidget.children.keys) {
if (!widget.children.containsKey(oldKey)) { if (!widget.children.containsKey(oldKey)) {
_highlightControllers[oldKey].dispose(); _highlightControllers[oldKey].dispose();
_pressControllers[oldKey].dispose(); _pressControllers[oldKey].dispose();
@ -324,7 +324,7 @@ class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T
} }
} }
for (T newKey in widget.children.keys) { for (final T newKey in widget.children.keys) {
if (!_highlightControllers.keys.contains(newKey)) { if (!_highlightControllers.keys.contains(newKey)) {
_highlightControllers[newKey] = _createHighlightAnimationController(); _highlightControllers[newKey] = _createHighlightAnimationController();
_pressControllers[newKey] = _createFadeoutAnimationController(); _pressControllers[newKey] = _createFadeoutAnimationController();
@ -336,11 +336,11 @@ class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T
@override @override
void dispose() { void dispose() {
for (AnimationController animationController in _highlightControllers.values) { for (final AnimationController animationController in _highlightControllers.values) {
animationController.dispose(); animationController.dispose();
} }
for (AnimationController animationController in _pressControllers.values) { for (final AnimationController animationController in _pressControllers.values) {
animationController.dispose(); animationController.dispose();
} }
@ -413,7 +413,7 @@ class _SegmentedControlState<T> extends State<CupertinoSlidingSegmentedControl<T
]), ]),
builder: (BuildContext context, Widget child) { builder: (BuildContext context, Widget child) {
final List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];
for (T currentKey in keys) { for (final T currentKey in keys) {
final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith( final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith(
fontWeight: _highlightTween.evaluate(_highlightControllers[currentKey]), fontWeight: _highlightTween.evaluate(_highlightControllers[currentKey]),
); );
@ -829,7 +829,7 @@ class _RenderSegmentedControl<T> extends RenderBox
double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount; double childWidth = (constraints.minWidth - totalSeparatorWidth) / childCount;
double maxHeight = _kMinSegmentedControlHeight; double maxHeight = _kMinSegmentedControlHeight;
for (RenderBox child in getChildrenAsList()) { for (final RenderBox child in getChildrenAsList()) {
childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding); childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding);
} }
@ -999,7 +999,7 @@ class _RenderSegmentedControl<T> extends RenderBox
final RRect thumbRRect = RRect.fromRectAndRadius(thumbRect.shift(offset), _kThumbRadius); 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()); context.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint());
} }

View File

@ -523,10 +523,10 @@ class _TabSwitchingViewState extends State<_TabSwitchingView> {
@override @override
void dispose() { void dispose() {
for (FocusScopeNode focusScopeNode in tabFocusNodes) { for (final FocusScopeNode focusScopeNode in tabFocusNodes) {
focusScopeNode.dispose(); focusScopeNode.dispose();
} }
for (FocusScopeNode focusScopeNode in discardedNodes) { for (final FocusScopeNode focusScopeNode in discardedNodes) {
focusScopeNode.dispose(); focusScopeNode.dispose();
} }
super.dispose(); super.dispose();

View File

@ -79,7 +79,7 @@ class CupertinoThumbPainter {
Radius.circular(rect.shortestSide / 2.0), 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(rrect.shift(shadow.offset), shadow.toPaint());
canvas.drawRRect( canvas.drawRRect(

View File

@ -556,7 +556,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti
ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'), ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'),
]; ];
int i = 1; int i = 1;
for (DiagnosticsNode summary in summaries) { for (final DiagnosticsNode summary in summaries) {
message.add(DiagnosticsProperty<DiagnosticsNode>('Summary $i', summary, expandableValue : true)); message.add(DiagnosticsProperty<DiagnosticsNode>('Summary $i', summary, expandableValue : true));
i += 1; i += 1;
} }
@ -683,7 +683,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti
final RegExp packageParser = RegExp(r'^([^:]+):(.+)$'); final RegExp packageParser = RegExp(r'^([^:]+):(.+)$');
final List<String> result = <String>[]; final List<String> result = <String>[];
final List<String> skipped = <String>[]; final List<String> skipped = <String>[];
for (String line in frames) { for (final String line in frames) {
final Match match = stackParser.firstMatch(line); final Match match = stackParser.firstMatch(line);
if (match != null) { if (match != null) {
assert(match.groupCount == 2); assert(match.groupCount == 2);
@ -834,7 +834,7 @@ class _FlutterErrorDetailsNode extends DiagnosticableNode<FlutterErrorDetails> {
return null; return null;
} }
Iterable<DiagnosticsNode> properties = builder.properties; Iterable<DiagnosticsNode> properties = builder.properties;
for (DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) { for (final DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) {
properties = transformer(properties); properties = transformer(properties);
} }
return DiagnosticPropertiesBuilder.fromProperties(properties.toList()); return DiagnosticPropertiesBuilder.fromProperties(properties.toList());

View File

@ -200,7 +200,7 @@ class ChangeNotifier implements Listenable {
assert(_debugAssertNotDisposed()); assert(_debugAssertNotDisposed());
if (_listeners != null) { if (_listeners != null) {
final List<VoidCallback> localListeners = List<VoidCallback>.from(_listeners); final List<VoidCallback> localListeners = List<VoidCallback>.from(_listeners);
for (VoidCallback listener in localListeners) { for (final VoidCallback listener in localListeners) {
try { try {
if (_listeners.contains(listener)) if (_listeners.contains(listener))
listener(); listener();

View File

@ -26,7 +26,7 @@ bool setEquals<T>(Set<T> a, Set<T> b) {
return false; return false;
if (identical(a, b)) if (identical(a, b))
return true; return true;
for (T value in a) { for (final T value in a) {
if (!b.contains(value)) if (!b.contains(value))
return false; return false;
} }
@ -84,7 +84,7 @@ bool mapEquals<T, U>(Map<T, U> a, Map<T, U> b) {
return false; return false;
if (identical(a, b)) if (identical(a, b))
return true; return true;
for (T key in a.keys) { for (final T key in a.keys) {
if (!b.containsKey(key) || b[key] != a[key]) { if (!b.containsKey(key) || b[key] != a[key]) {
return false; return false;
} }

View File

@ -115,7 +115,7 @@ class _OutputBuffer extends ByteConversionSinkBase {
} }
_bytes = Uint8List(_contentLength); _bytes = Uint8List(_contentLength);
int offset = 0; int offset = 0;
for (List<int> chunk in _chunks) { for (final List<int> chunk in _chunks) {
_bytes.setRange(offset, offset + chunk.length, chunk); _bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length; offset += chunk.length;
} }

View File

@ -843,7 +843,7 @@ class _PrefixedStringBuilder {
); );
int i = 0; int i = 0;
final int length = lines.length; final int length = lines.length;
for (String line in lines) { for (final String line in lines) {
i++; i++;
_writeLine( _writeLine(
line, line,
@ -1132,7 +1132,7 @@ class TextTreeRenderer {
const int maxLines = 25; const int maxLines = 25;
int lines = 0; int lines = 0;
void visitor(DiagnosticsNode node) { void visitor(DiagnosticsNode node) {
for (DiagnosticsNode child in node.getChildren()) { for (final DiagnosticsNode child in node.getChildren()) {
if (lines < maxLines) { if (lines < maxLines) {
depth += 1; depth += 1;
descendants.add('$prefixOtherLines${" " * depth}$child'); descendants.add('$prefixOtherLines${" " * depth}$child');
@ -2508,7 +2508,7 @@ class FlagsSummary<T> extends DiagnosticsProperty<Map<String, T>> {
// For a null value, it is omitted unless `includeEmtpy` is true and // For a null value, it is omitted unless `includeEmtpy` is true and
// [ifEntryNull] contains a corresponding description. // [ifEntryNull] contains a corresponding description.
Iterable<String> _formattedValues() sync* { Iterable<String> _formattedValues() sync* {
for (MapEntry<String, T> entry in value.entries) { for (final MapEntry<String, T> entry in value.entries) {
if (entry.value != null) { if (entry.value != null) {
yield entry.key; yield entry.key;
} }

View File

@ -310,7 +310,7 @@ class LicenseRegistry {
static Stream<LicenseEntry> get licenses async* { static Stream<LicenseEntry> get licenses async* {
if (_collectors == null) if (_collectors == null)
return; return;
for (LicenseEntryCollector collector in _collectors) for (final LicenseEntryCollector collector in _collectors)
yield* collector(); yield* collector();
} }

View File

@ -256,7 +256,7 @@ class GestureArenaManager {
assert(state.eagerWinner == null || state.eagerWinner == member); assert(state.eagerWinner == null || state.eagerWinner == member);
assert(!state.isOpen); assert(!state.isOpen);
_arenas.remove(pointer); _arenas.remove(pointer);
for (GestureArenaMember rejectedMember in state.members) { for (final GestureArenaMember rejectedMember in state.members) {
if (rejectedMember != member) if (rejectedMember != member)
rejectedMember.rejectGesture(pointer); rejectedMember.rejectGesture(pointer);
} }

View File

@ -193,7 +193,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
} }
return; return;
} }
for (HitTestEntry entry in hitTestResult.path) { for (final HitTestEntry entry in hitTestResult.path) {
try { try {
entry.target.handleEvent(event.transformed(entry.transform), entry); entry.target.handleEvent(event.transformed(entry.transform), entry);
} catch (exception, stack) { } catch (exception, stack) {

View File

@ -42,7 +42,7 @@ class PointerEventConverter {
/// from physical coordinates to logical pixels. See the discussion at /// from physical coordinates to logical pixels. See the discussion at
/// [PointerEvent] for more details on the [PointerEvent] coordinate space. /// [PointerEvent] for more details on the [PointerEvent] coordinate space.
static Iterable<PointerEvent> expand(Iterable<ui.PointerData> data, double devicePixelRatio) sync* { static Iterable<PointerEvent> expand(Iterable<ui.PointerData> 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 position = Offset(datum.physicalX, datum.physicalY) / devicePixelRatio;
final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio; final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio;
final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio); final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio);

View File

@ -410,7 +410,7 @@ class MouseTracker extends ChangeNotifier {
// We can safely use `_mouseStates` here without worrying about the removed // We can safely use `_mouseStates` here without worrying about the removed
// state, because `targetEvent` should be null when `_mouseStates` is used. // state, because `targetEvent` should be null when `_mouseStates` is used.
final Iterable<_MouseState> dirtyStates = targetEvent == null ? _mouseStates.values : <_MouseState>[targetState]; final Iterable<_MouseState> dirtyStates = targetEvent == null ? _mouseStates.values : <_MouseState>[targetState];
for (_MouseState dirtyState in dirtyStates) { for (final _MouseState dirtyState in dirtyStates) {
final LinkedHashSet<MouseTrackerAnnotation> nextAnnotations = _findAnnotations(dirtyState); final LinkedHashSet<MouseTrackerAnnotation> nextAnnotations = _findAnnotations(dirtyState);
final LinkedHashSet<MouseTrackerAnnotation> lastAnnotations = dirtyState.replaceAnnotations(nextAnnotations); final LinkedHashSet<MouseTrackerAnnotation> lastAnnotations = dirtyState.replaceAnnotations(nextAnnotations);
handleUpdatedDevice(dirtyState, lastAnnotations); handleUpdatedDevice(dirtyState, lastAnnotations);

View File

@ -505,7 +505,7 @@ class MultiTapGestureRecognizer extends GestureRecognizer {
@override @override
void dispose() { void dispose() {
final List<_TapGesture> localGestures = List<_TapGesture>.from(_gestureMap.values); final List<_TapGesture> localGestures = List<_TapGesture>.from(_gestureMap.values);
for (_TapGesture gesture in localGestures) for (final _TapGesture gesture in localGestures)
gesture.cancel(); gesture.cancel();
// Rejection of each gesture should cause it to be removed from our map // Rejection of each gesture should cause it to be removed from our map
assert(_gestureMap.isEmpty); assert(_gestureMap.isEmpty);

View File

@ -251,7 +251,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
void resolve(GestureDisposition disposition) { void resolve(GestureDisposition disposition) {
final List<GestureArenaEntry> localEntries = List<GestureArenaEntry>.from(_entries.values); final List<GestureArenaEntry> localEntries = List<GestureArenaEntry>.from(_entries.values);
_entries.clear(); _entries.clear();
for (GestureArenaEntry entry in localEntries) for (final GestureArenaEntry entry in localEntries)
entry.resolve(disposition); entry.resolve(disposition);
} }
@ -270,7 +270,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
@override @override
void dispose() { void dispose() {
resolve(GestureDisposition.rejected); resolve(GestureDisposition.rejected);
for (int pointer in _trackedPointers) for (final int pointer in _trackedPointers)
GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent); GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent);
_trackedPointers.clear(); _trackedPointers.clear();
assert(_entries.isEmpty); assert(_entries.isEmpty);

View File

@ -338,7 +338,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
// Compute the focal point // Compute the focal point
Offset focalPoint = Offset.zero; Offset focalPoint = Offset.zero;
for (int pointer in _pointerLocations.keys) for (final int pointer in _pointerLocations.keys)
focalPoint += _pointerLocations[pointer]; focalPoint += _pointerLocations[pointer];
_currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero; _currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero;
@ -348,7 +348,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
double totalDeviation = 0.0; double totalDeviation = 0.0;
double totalHorizontalDeviation = 0.0; double totalHorizontalDeviation = 0.0;
double totalVerticalDeviation = 0.0; double totalVerticalDeviation = 0.0;
for (int pointer in _pointerLocations.keys) { for (final int pointer in _pointerLocations.keys) {
totalDeviation += (_currentFocalPoint - _pointerLocations[pointer]).distance; totalDeviation += (_currentFocalPoint - _pointerLocations[pointer]).distance;
totalHorizontalDeviation += (_currentFocalPoint.dx - _pointerLocations[pointer].dx).abs(); totalHorizontalDeviation += (_currentFocalPoint.dx - _pointerLocations[pointer].dx).abs();
totalVerticalDeviation += (_currentFocalPoint.dy - _pointerLocations[pointer].dy).abs(); totalVerticalDeviation += (_currentFocalPoint.dy - _pointerLocations[pointer].dy).abs();

View File

@ -34,7 +34,7 @@ class _CombiningGestureArenaMember extends GestureArenaMember {
assert(_winner != null || _members.isNotEmpty); assert(_winner != null || _members.isNotEmpty);
_close(); _close();
_winner ??= _owner.captain ?? _members[0]; _winner ??= _owner.captain ?? _members[0];
for (GestureArenaMember member in _members) { for (final GestureArenaMember member in _members) {
if (member != _winner) if (member != _winner)
member.rejectGesture(pointer); member.rejectGesture(pointer);
} }
@ -45,7 +45,7 @@ class _CombiningGestureArenaMember extends GestureArenaMember {
void rejectGesture(int pointer) { void rejectGesture(int pointer) {
assert(_pointer == pointer); assert(_pointer == pointer);
_close(); _close();
for (GestureArenaMember member in _members) for (final GestureArenaMember member in _members)
member.rejectGesture(pointer); member.rejectGesture(pointer);
} }

View File

@ -488,7 +488,7 @@ class _LicensePageState extends State<LicensePage> {
debugFlowId = flow.id; debugFlowId = flow.id;
return true; return true;
}()); }());
await for (LicenseEntry license in LicenseRegistry.licenses) { await for (final LicenseEntry license in LicenseRegistry.licenses) {
if (!mounted) { if (!mounted) {
return; return;
} }
@ -523,7 +523,7 @@ class _LicensePageState extends State<LicensePage> {
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
)); ));
for (LicenseParagraph paragraph in paragraphs) { for (final LicenseParagraph paragraph in paragraphs) {
if (paragraph.indent == LicenseParagraph.centeredIndent) { if (paragraph.indent == LicenseParagraph.centeredIndent) {
_licenses.add(Padding( _licenses.add(Padding(
padding: const EdgeInsets.only(top: 16.0), padding: const EdgeInsets.only(top: 16.0),

Some files were not shown because too many files have changed in this diff Show More