From 758009ba7010feda282f26fd6537b5aa79394271 Mon Sep 17 00:00:00 2001 From: Alexandre Ardhuin Date: Tue, 2 Jul 2019 21:11:56 +0200 Subject: [PATCH] more ui-as-code (#35393) * more ui-as-code * address review comments --- dev/bots/analyze-sample-code.dart | 17 ++-- dev/bots/analyze.dart | 24 +++-- dev/bots/prepare_package.dart | 16 +-- dev/bots/test.dart | 20 ++-- dev/bots/test/prepare_package_test.dart | 69 +++++-------- dev/bots/unpublish_package.dart | 13 ++- dev/devicelab/lib/framework/apk_utils.dart | 8 +- dev/devicelab/lib/tasks/analysis.dart | 11 ++- dev/devicelab/lib/tasks/gallery.dart | 2 +- .../lib/tasks/integration_tests.dart | 2 +- dev/devicelab/lib/tasks/microbenchmarks.dart | 15 +-- dev/devicelab/lib/tasks/perf_tests.dart | 18 ++-- dev/devicelab/test/run_test.dart | 12 +-- dev/manual_tests/lib/text.dart | 3 +- dev/snippets/lib/snippets.dart | 19 ++-- .../flutter_gallery/lib/demo/colors_demo.dart | 32 +++--- .../demo/material/bottom_app_bar_demo.dart | 76 +++++++------- .../flutter_gallery/lib/gallery/demo.dart | 25 ++--- .../lib/src/foundation/assertions.dart | 10 +- .../lib/src/foundation/diagnostics.dart | 89 +++++++---------- packages/flutter/lib/src/material/about.dart | 85 ++++++++-------- .../flutter/lib/src/material/date_picker.dart | 5 +- .../flutter/lib/src/material/scaffold.dart | 10 +- .../flutter/lib/src/painting/borders.dart | 18 ++-- packages/flutter/lib/src/rendering/box.dart | 24 +++-- .../lib/src/rendering/custom_paint.dart | 11 +-- .../flutter/lib/src/rendering/object.dart | 28 +++--- .../flutter/lib/src/rendering/sliver.dart | 29 +++--- .../flutter/lib/src/semantics/semantics.dart | 18 ++-- .../lib/src/widgets/nested_scroll_view.dart | 16 +-- .../lib/src/widgets/widget_inspector.dart | 21 ++-- .../foundation/diagnostics_json_test.dart | 6 +- .../test/rendering/paragraph_test.dart | 10 +- packages/flutter_test/lib/src/binding.dart | 8 +- packages/flutter_test/pubspec.yaml | 2 +- .../flutter_tools/bin/fuchsia_attach.dart | 10 +- .../lib/src/android/android_device.dart | 66 ++++++------- .../src/android/android_studio_validator.dart | 14 ++- packages/flutter_tools/lib/src/asset.dart | 34 +++---- .../flutter_tools/lib/src/base/build.dart | 25 ++--- .../lib/src/base/fingerprint.dart | 10 +- packages/flutter_tools/lib/src/cache.dart | 98 +++++++++---------- .../lib/src/commands/daemon.dart | 8 +- .../lib/src/commands/format.dart | 25 ++--- .../flutter_tools/lib/src/commands/test.dart | 16 ++- .../lib/src/commands/update_packages.dart | 20 ++-- packages/flutter_tools/lib/src/dart/pub.dart | 32 +++--- packages/flutter_tools/lib/src/device.dart | 9 +- packages/flutter_tools/lib/src/doctor.dart | 68 ++++++------- .../flutter_tools/lib/src/ios/simulators.dart | 12 ++- .../lib/src/runner/flutter_command.dart | 19 ++-- .../flutter_tools/lib/src/test/runner.dart | 47 ++++----- packages/flutter_tools/lib/src/version.dart | 15 +-- .../test/base/fingerprint_test.dart | 6 +- .../test/commands/build_bundle_test.dart | 12 +-- .../test/commands/create_test.dart | 9 +- .../test/commands/ide_config_test.dart | 44 ++++++--- .../test/commands/packages_test.dart | 13 ++- packages/flutter_tools/test/src/testbed.dart | 16 ++- .../lib/src/fuchsia_remote_connection.dart | 26 +++-- .../lib/src/runners/ssh_command_runner.dart | 22 ++--- .../pubspec.yaml | 2 +- 62 files changed, 676 insertions(+), 774 deletions(-) diff --git a/dev/bots/analyze-sample-code.dart b/dev/bots/analyze-sample-code.dart index d949bb2aa5..a04d220d4d 100644 --- a/dev/bots/analyze-sample-code.dart +++ b/dev/bots/analyze-sample-code.dart @@ -531,10 +531,12 @@ linter: File _writeSection(Section section) { final String sectionId = _createNameFromSource('sample', section.start.filename, section.start.line); final File outputFile = File(path.join(_tempDirectory.path, '$sectionId.dart'))..createSync(recursive: true); - final List mainContents = headers.toList(); - mainContents.add(const Line('')); - mainContents.add(Line('// From: ${section.start.filename}:${section.start.line}')); - mainContents.addAll(section.code); + final List mainContents = [ + ...headers, + const Line(''), + Line('// From: ${section.start.filename}:${section.start.line}'), + ...section.code, + ]; outputFile.writeAsStringSync(mainContents.map((Line line) => line.code).join('\n')); return outputFile; } @@ -820,10 +822,9 @@ class Line { class Section { const Section(this.code); factory Section.combine(List
sections) { - final List code = []; - for (Section section in sections) { - code.addAll(section.code); - } + final List code = sections + .expand((Section section) => section.code) + .toList(); return Section(code); } factory Section.fromStrings(Line firstLine, List code) { diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index 4397e65e47..138da9b05e 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -40,9 +40,10 @@ Future main(List args) async { { // Analyze all the Dart code in the repo. - final List options = ['--flutter-repo']; - options.addAll(args); - await _runFlutterAnalyze(flutterRoot, options: options); + await _runFlutterAnalyze(flutterRoot, options: [ + '--flutter-repo', + ...args, + ]); } // Ensure that all package dependencies are in sync. @@ -59,9 +60,12 @@ Future main(List args) async { // Try with the --watch analyzer, to make sure it returns success also. // The --benchmark argument exits after one run. { - final List options = ['--flutter-repo', '--watch', '--benchmark']; - options.addAll(args); - await _runFlutterAnalyze(flutterRoot, options: options); + await _runFlutterAnalyze(flutterRoot, options: [ + '--flutter-repo', + '--watch', + '--benchmark', + ...args, + ]); } await _checkForTrailingSpaces(); @@ -79,9 +83,11 @@ Future main(List args) async { workingDirectory: flutterRoot, ); { - final List options = ['--watch', '--benchmark']; - options.addAll(args); - await _runFlutterAnalyze(outDir.path, options: options); + await _runFlutterAnalyze(outDir.path, options: [ + '--watch', + '--benchmark', + ...args, + ]); } } finally { outDir.deleteSync(recursive: true); diff --git a/dev/bots/prepare_package.dart b/dev/bots/prepare_package.dart index d36eaf2e71..843966de7d 100644 --- a/dev/bots/prepare_package.dart +++ b/dev/bots/prepare_package.dart @@ -601,14 +601,14 @@ class ArchivePublisher { if (dest.endsWith('.json')) { mimeType = 'application/json'; } - final List args = []; - // Use our preferred MIME type for the files we care about - // and let gsutil figure it out for anything else. - if (mimeType != null) { - args.addAll(['-h', 'Content-Type:$mimeType']); - } - args.addAll(['cp', src, dest]); - return await _runGsUtil(args); + return await _runGsUtil([ + // Use our preferred MIME type for the files we care about + // and let gsutil figure it out for anything else. + if (mimeType != null) ...['-h', 'Content-Type:$mimeType'], + 'cp', + src, + dest, + ]); } } diff --git a/dev/bots/test.dart b/dev/bots/test.dart index e16480059b..7cb5d2df9b 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -754,11 +754,13 @@ Future _runFlutterWebTest(String workingDirectory, { Duration timeout = _kLongTimeout, List tests, }) async { - final List args = ['test', '-v', '--platform=chrome']; - if (flutterTestArgs != null && flutterTestArgs.isNotEmpty) - args.addAll(flutterTestArgs); - - args.addAll(tests); + final List args = [ + 'test', + '-v', + '--platform=chrome', + ...?flutterTestArgs, + ...tests, + ]; // TODO(jonahwilliams): fix relative path issues to make this unecessary. final Directory oldCurrent = Directory.current; @@ -791,9 +793,11 @@ Future _runFlutterTest(String workingDirectory, { Map environment, List tests = const [], }) async { - final List args = ['test', ...options]; - if (flutterTestArgs != null && flutterTestArgs.isNotEmpty) - args.addAll(flutterTestArgs); + final List args = [ + 'test', + ...options, + ...?flutterTestArgs, + ]; final bool shouldProcessOutput = useFlutterTestFormatter && !expectFailure && !options.contains('--coverage'); if (shouldProcessOutput) { diff --git a/dev/bots/test/prepare_package_test.dart b/dev/bots/test/prepare_package_test.dart index 4fcf50c7ac..78c958b31c 100644 --- a/dev/bots/test/prepare_package_test.dart +++ b/dev/bots/test/prepare_package_test.dart @@ -106,16 +106,14 @@ void main() { test('sets PUB_CACHE properly', () async { final String createBase = path.join(tempDir.absolute.path, 'create_'); - final Map> calls = >{ + final String archiveName = path.join(tempDir.absolute.path, + 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); + processManager.fakeResults = >{ 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git reset --hard $testRef': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git describe --tags --exact-match $testRef': [ProcessResult(0, 0, 'v1.2.3', '')], - }; - if (platform.isWindows) { - calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null; - } - calls.addAll(>{ + if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null, '$flutter doctor': null, '$flutter update-packages': null, '$flutter precache': null, @@ -124,17 +122,10 @@ void main() { '$flutter create --template=package ${createBase}package': null, '$flutter create --template=plugin ${createBase}plugin': null, 'git clean -f -X **/.packages': null, - }); - final String archiveName = path.join(tempDir.absolute.path, - 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); - if (platform.isWindows) { - calls['7za a -tzip -mx=9 $archiveName flutter'] = null; - } else if (platform.isMacOS) { - calls['zip -r -9 $archiveName flutter'] = null; - } else if (platform.isLinux) { - calls['tar cJf $archiveName flutter'] = null; - } - processManager.fakeResults = calls; + if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null + else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null + else if (platform.isLinux) 'tar cJf $archiveName flutter': null, + }; await creator.initializeRepo(); await creator.createArchive(); expect( @@ -149,16 +140,14 @@ void main() { test('calls the right commands for archive output', () async { final String createBase = path.join(tempDir.absolute.path, 'create_'); + final String archiveName = path.join(tempDir.absolute.path, + 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); final Map> calls = >{ 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git reset --hard $testRef': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git describe --tags --exact-match $testRef': [ProcessResult(0, 0, 'v1.2.3', '')], - }; - if (platform.isWindows) { - calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null; - } - calls.addAll(>{ + if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null, '$flutter doctor': null, '$flutter update-packages': null, '$flutter precache': null, @@ -167,16 +156,10 @@ void main() { '$flutter create --template=package ${createBase}package': null, '$flutter create --template=plugin ${createBase}plugin': null, 'git clean -f -X **/.packages': null, - }); - final String archiveName = path.join(tempDir.absolute.path, - 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); - if (platform.isWindows) { - calls['7za a -tzip -mx=9 $archiveName flutter'] = null; - } else if (platform.isMacOS) { - calls['zip -r -9 $archiveName flutter'] = null; - } else if (platform.isLinux) { - calls['tar cJf $archiveName flutter'] = null; - } + if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null + else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null + else if (platform.isLinux) 'tar cJf $archiveName flutter': null, + }; processManager.fakeResults = calls; creator = ArchiveCreator( tempDir, @@ -206,16 +189,14 @@ void main() { test('non-strict mode calls the right commands', () async { final String createBase = path.join(tempDir.absolute.path, 'create_'); + final String archiveName = path.join(tempDir.absolute.path, + 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); final Map> calls = >{ 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git reset --hard $testRef': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git describe --tags --abbrev=0 $testRef': [ProcessResult(0, 0, 'v1.2.3', '')], - }; - if (platform.isWindows) { - calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null; - } - calls.addAll(>{ + if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null, '$flutter doctor': null, '$flutter update-packages': null, '$flutter precache': null, @@ -224,16 +205,10 @@ void main() { '$flutter create --template=package ${createBase}package': null, '$flutter create --template=plugin ${createBase}plugin': null, 'git clean -f -X **/.packages': null, - }); - final String archiveName = path.join(tempDir.absolute.path, - 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); - if (platform.isWindows) { - calls['7za a -tzip -mx=9 $archiveName flutter'] = null; - } else if (platform.isMacOS) { - calls['zip -r -9 $archiveName flutter'] = null; - } else if (platform.isLinux) { - calls['tar cJf $archiveName flutter'] = null; - } + if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null + else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null + else if (platform.isLinux) 'tar cJf $archiveName flutter': null, + }; processManager.fakeResults = calls; creator = ArchiveCreator( tempDir, diff --git a/dev/bots/unpublish_package.dart b/dev/bots/unpublish_package.dart index a91ce398d6..518919fcab 100644 --- a/dev/bots/unpublish_package.dart +++ b/dev/bots/unpublish_package.dart @@ -377,13 +377,12 @@ class ArchiveUnpublisher { if (dest.endsWith('.json')) { mimeType = 'application/json'; } - final List args = []; - // Use our preferred MIME type for the files we care about - // and let gsutil figure it out for anything else. - if (mimeType != null) { - args.addAll(['-h', 'Content-Type:$mimeType']); - } - args.addAll(['cp', src, dest]); + final List args = [ + // Use our preferred MIME type for the files we care about + // and let gsutil figure it out for anything else. + if (mimeType != null) ...['-h', 'Content-Type:$mimeType'], + ...['cp', src, dest], + ]; return await _runGsUtil(args, confirm: confirmed); } } diff --git a/dev/devicelab/lib/framework/apk_utils.dart b/dev/devicelab/lib/framework/apk_utils.dart index bbbfa08fb3..62bee93d3d 100644 --- a/dev/devicelab/lib/framework/apk_utils.dart +++ b/dev/devicelab/lib/framework/apk_utils.dart @@ -252,10 +252,10 @@ Future _resultOfGradleTask({String workingDirectory, String task, print('\nUsing JAVA_HOME=$javaHome'); - final List args = ['app:$task']; - if (options != null) { - args.addAll(options); - } + final List args = [ + 'app:$task', + ...?options, + ]; final String gradle = Platform.isWindows ? 'gradlew.bat' : './gradlew'; print('Running Gradle: ${path.join(workingDirectory, gradle)} ${args.join(' ')}'); print(File(path.join(workingDirectory, gradle)).readAsStringSync()); diff --git a/dev/devicelab/lib/tasks/analysis.dart b/dev/devicelab/lib/tasks/analysis.dart index cbf4366d56..a938d49179 100644 --- a/dev/devicelab/lib/tasks/analysis.dart +++ b/dev/devicelab/lib/tasks/analysis.dart @@ -28,11 +28,12 @@ Future analyzerBenchmarkTask() async { await dart(['dev/tools/mega_gallery.dart', '--out=${_megaGalleryDirectory.path}']); }); - final Map data = {}; - data.addAll((await _run(_FlutterRepoBenchmark())).asMap('flutter_repo', 'batch')); - data.addAll((await _run(_FlutterRepoBenchmark(watch: true))).asMap('flutter_repo', 'watch')); - data.addAll((await _run(_MegaGalleryBenchmark())).asMap('mega_gallery', 'batch')); - data.addAll((await _run(_MegaGalleryBenchmark(watch: true))).asMap('mega_gallery', 'watch')); + final Map data = { + ...(await _run(_FlutterRepoBenchmark())).asMap('flutter_repo', 'batch'), + ...(await _run(_FlutterRepoBenchmark(watch: true))).asMap('flutter_repo', 'watch'), + ...(await _run(_MegaGalleryBenchmark())).asMap('mega_gallery', 'batch'), + ...(await _run(_MegaGalleryBenchmark(watch: true))).asMap('mega_gallery', 'watch'), + }; return TaskResult.success(data, benchmarkScoreKeys: data.keys.toList()); } diff --git a/dev/devicelab/lib/tasks/gallery.dart b/dev/devicelab/lib/tasks/gallery.dart index 7fdc271466..31a0c4555e 100644 --- a/dev/devicelab/lib/tasks/gallery.dart +++ b/dev/devicelab/lib/tasks/gallery.dart @@ -64,8 +64,8 @@ class GalleryTransitionTest { final Map data = { 'transitions': transitions, 'missed_transition_count': _countMissedTransitions(transitions), + ...summary, }; - data.addAll(summary); return TaskResult.success(data, benchmarkScoreKeys: [ 'missed_transition_count', diff --git a/dev/devicelab/lib/tasks/integration_tests.dart b/dev/devicelab/lib/tasks/integration_tests.dart index f6c7eb739a..116403eb94 100644 --- a/dev/devicelab/lib/tasks/integration_tests.dart +++ b/dev/devicelab/lib/tasks/integration_tests.dart @@ -124,8 +124,8 @@ class DriverTest { testTarget, '-d', deviceId, + ...extraOptions, ]; - options.addAll(extraOptions); await flutter('drive', options: options, environment: Map.from(environment)); return TaskResult.success(null); diff --git a/dev/devicelab/lib/tasks/microbenchmarks.dart b/dev/devicelab/lib/tasks/microbenchmarks.dart index e3c3f35aab..5cd4b7f839 100644 --- a/dev/devicelab/lib/tasks/microbenchmarks.dart +++ b/dev/devicelab/lib/tasks/microbenchmarks.dart @@ -48,13 +48,14 @@ TaskFunction createMicrobenchmarkTask() { return _run(); } - final Map allResults = {}; - allResults.addAll(await _runMicrobench('lib/stocks/layout_bench.dart')); - allResults.addAll(await _runMicrobench('lib/stocks/build_bench.dart')); - allResults.addAll(await _runMicrobench('lib/geometry/rrect_contains_bench.dart')); - allResults.addAll(await _runMicrobench('lib/gestures/velocity_tracker_bench.dart')); - allResults.addAll(await _runMicrobench('lib/gestures/gesture_detector_bench.dart')); - allResults.addAll(await _runMicrobench('lib/stocks/animation_bench.dart')); + final Map allResults = { + ...await _runMicrobench('lib/stocks/layout_bench.dart'), + ...await _runMicrobench('lib/stocks/build_bench.dart'), + ...await _runMicrobench('lib/geometry/rrect_contains_bench.dart'), + ...await _runMicrobench('lib/gestures/velocity_tracker_bench.dart'), + ...await _runMicrobench('lib/gestures/gesture_detector_bench.dart'), + ...await _runMicrobench('lib/stocks/animation_bench.dart'), + }; return TaskResult.success(allResults, benchmarkScoreKeys: allResults.keys.toList()); }; diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index b2eca5ac79..7c67fed774 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -289,10 +289,11 @@ class CompileTest { await device.unlock(); await flutter('packages', options: ['get']); - final Map metrics = {} - ..addAll(await _compileAot()) - ..addAll(await _compileApp(reportPackageContentSizes: reportPackageContentSizes)) - ..addAll(await _compileDebug()); + final Map metrics = { + ...await _compileAot(), + ...await _compileApp(reportPackageContentSizes: reportPackageContentSizes), + ...await _compileDebug(), + }; return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList()); }); @@ -533,10 +534,11 @@ class MemoryTest { final ListStatistics endMemoryStatistics = ListStatistics(_endMemory); final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory); - final Map memoryUsage = {}; - memoryUsage.addAll(startMemoryStatistics.asMap('start')); - memoryUsage.addAll(endMemoryStatistics.asMap('end')); - memoryUsage.addAll(diffMemoryStatistics.asMap('diff')); + final Map memoryUsage = { + ...startMemoryStatistics.asMap('start'), + ...endMemoryStatistics.asMap('end'), + ...diffMemoryStatistics.asMap('diff'), + }; _device = null; _startMemory.clear(); diff --git a/dev/devicelab/test/run_test.dart b/dev/devicelab/test/run_test.dart index c877e98858..a9f0d48a82 100644 --- a/dev/devicelab/test/run_test.dart +++ b/dev/devicelab/test/run_test.dart @@ -15,14 +15,12 @@ void main() { group('run.dart script', () { Future runScript(List testNames) async { - final List options = ['bin/run.dart']; - for (String testName in testNames) { - options..addAll(['-t', testName]); - } final String dart = path.absolute(path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', 'dart')); - final ProcessResult scriptProcess = processManager.runSync( - [dart, ...options] - ); + final ProcessResult scriptProcess = processManager.runSync([ + dart, + 'bin/run.dart', + for (String testName in testNames) ...['-t', testName], + ]); return scriptProcess; } diff --git a/dev/manual_tests/lib/text.dart b/dev/manual_tests/lib/text.dart index 3d5f482bd5..cfb8461ccf 100644 --- a/dev/manual_tests/lib/text.dart +++ b/dev/manual_tests/lib/text.dart @@ -1401,8 +1401,7 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin } } base ??= String.fromCharCode(randomCharacter(random)); - final List characters = []; - characters.addAll(these); + final List characters = these.toList(); return base + String.fromCharCodes(characters); } diff --git a/dev/snippets/lib/snippets.dart b/dev/snippets/lib/snippets.dart index 20f5da7c7c..9f69daec2a 100644 --- a/dev/snippets/lib/snippets.dart +++ b/dev/snippets/lib/snippets.dart @@ -127,15 +127,16 @@ class SnippetGenerator { 'description': description, 'code': htmlEscape.convert(result.join('\n')), 'language': language ?? 'dart', - }..addAll(type == SnippetType.application - ? { - 'serial': metadata['serial'].toString() ?? '0', - 'id': - injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'id').mergedContent, - 'app': - htmlEscape.convert(injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'app').mergedContent), - } - : {'serial': '', 'id': '', 'app': ''}); + 'serial': '', + 'id': '', + 'app': '', + }; + if (type == SnippetType.application) { + substitutions + ..['serial'] = metadata['serial'].toString() ?? '0' + ..['id'] = injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'id').mergedContent + ..['app'] = htmlEscape.convert(injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'app').mergedContent); + } return skeleton.replaceAllMapped(RegExp('{{(${substitutions.keys.join('|')})}}'), (Match match) { return substitutions[match[1]]; }); diff --git a/examples/flutter_gallery/lib/demo/colors_demo.dart b/examples/flutter_gallery/lib/demo/colors_demo.dart index 4b201710e7..d27e704905 100644 --- a/examples/flutter_gallery/lib/demo/colors_demo.dart +++ b/examples/flutter_gallery/lib/demo/colors_demo.dart @@ -99,26 +99,24 @@ class PaletteTabView extends StatelessWidget { final TextTheme textTheme = Theme.of(context).textTheme; final TextStyle whiteTextStyle = textTheme.body1.copyWith(color: Colors.white); final TextStyle blackTextStyle = textTheme.body1.copyWith(color: Colors.black); - final List colorItems = primaryKeys.map((int index) { - return DefaultTextStyle( - style: index > colors.threshold ? whiteTextStyle : blackTextStyle, - child: ColorItem(index: index, color: colors.primary[index]), - ); - }).toList(); - - if (colors.accent != null) { - colorItems.addAll(accentKeys.map((int index) { - return DefaultTextStyle( - style: index > colors.threshold ? whiteTextStyle : blackTextStyle, - child: ColorItem(index: index, color: colors.accent[index], prefix: 'A'), - ); - }).toList()); - } - return Scrollbar( child: ListView( itemExtent: kColorItemHeight, - children: colorItems, + children: [ + ...primaryKeys.map((int index) { + return DefaultTextStyle( + style: index > colors.threshold ? whiteTextStyle : blackTextStyle, + child: ColorItem(index: index, color: colors.primary[index]), + ); + }), + if (colors.accent != null) + ...accentKeys.map((int index) { + return DefaultTextStyle( + style: index > colors.threshold ? whiteTextStyle : blackTextStyle, + child: ColorItem(index: index, color: colors.accent[index], prefix: 'A'), + ); + }), + ], ) ); } diff --git a/examples/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart b/examples/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart index ac0c0d8125..d3da0fb87e 100644 --- a/examples/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/bottom_app_bar_demo.dart @@ -349,52 +349,42 @@ class _DemoBottomAppBar extends StatelessWidget { @override Widget build(BuildContext context) { - final List rowContents = [ - IconButton( - icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'), - onPressed: () { - showModalBottomSheet( - context: context, - builder: (BuildContext context) => const _DemoDrawer(), - ); - }, - ), - ]; - - if (kCenterLocations.contains(fabLocation)) { - rowContents.add( - const Expanded(child: SizedBox()), - ); - } - - rowContents.addAll( [ - IconButton( - icon: const Icon(Icons.search, semanticLabel: 'show search action',), - onPressed: () { - Scaffold.of(context).showSnackBar( - const SnackBar(content: Text('This is a dummy search action.')), - ); - }, - ), - IconButton( - icon: Icon( - Theme.of(context).platform == TargetPlatform.iOS - ? Icons.more_horiz - : Icons.more_vert, - semanticLabel: 'Show menu actions', - ), - onPressed: () { - Scaffold.of(context).showSnackBar( - const SnackBar(content: Text('This is a dummy menu action.')), - ); - }, - ), - ]); - return BottomAppBar( color: color, - child: Row(children: rowContents), shape: shape, + child: Row(children: [ + IconButton( + icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'), + onPressed: () { + showModalBottomSheet( + context: context, + builder: (BuildContext context) => const _DemoDrawer(), + ); + }, + ), + if (kCenterLocations.contains(fabLocation)) const Expanded(child: SizedBox()), + IconButton( + icon: const Icon(Icons.search, semanticLabel: 'show search action',), + onPressed: () { + Scaffold.of(context).showSnackBar( + const SnackBar(content: Text('This is a dummy search action.')), + ); + }, + ), + IconButton( + icon: Icon( + Theme.of(context).platform == TargetPlatform.iOS + ? Icons.more_horiz + : Icons.more_vert, + semanticLabel: 'Show menu actions', + ), + onPressed: () { + Scaffold.of(context).showSnackBar( + const SnackBar(content: Text('This is a dummy menu action.')), + ); + }, + ), + ]), ); } } diff --git a/examples/flutter_gallery/lib/gallery/demo.dart b/examples/flutter_gallery/lib/gallery/demo.dart index a7ee712e21..178d8dea76 100644 --- a/examples/flutter_gallery/lib/gallery/demo.dart +++ b/examples/flutter_gallery/lib/gallery/demo.dart @@ -97,7 +97,8 @@ class TabbedComponentDemoScaffold extends StatelessWidget { child: Scaffold( appBar: AppBar( title: Text(title), - actions: (actions ?? [])..add( + actions: [ + ...?actions, Builder( builder: (BuildContext context) { return IconButton( @@ -106,17 +107,17 @@ class TabbedComponentDemoScaffold extends StatelessWidget { ); }, ), - )..addAll(showExampleCodeAction ? [ - Builder( - builder: (BuildContext context) { - return IconButton( - icon: const Icon(Icons.code), - tooltip: 'Show example code', - onPressed: () => _showExampleCode(context), - ); - }, - ), - ] : []), + if (showExampleCodeAction) + Builder( + builder: (BuildContext context) { + return IconButton( + icon: const Icon(Icons.code), + tooltip: 'Show example code', + onPressed: () => _showExampleCode(context), + ); + }, + ), + ], bottom: TabBar( isScrollable: isScrollable, tabs: demos.map((ComponentDemoTabData data) => Tab(text: data.tabName)).toList(), diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index 9d2ea25d11..abcb076eff 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -477,12 +477,10 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti /// using [ErrorHint]s or other [DiagnosticsNode]s. factory FlutterError(String message) { final List lines = message.split('\n'); - final List parts = []; - parts.add(ErrorSummary(lines.first)); - if (lines.length > 1) { - parts.addAll(lines.skip(1).map((String line) => ErrorDescription(line))); - } - return FlutterError.fromParts(parts); + return FlutterError.fromParts([ + ErrorSummary(lines.first), + ...lines.skip(1).map((String line) => ErrorDescription(line)), + ]); } /// Create an error message from a list of [DiagnosticsNode]s. diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index 111d8ca17a..ed5d2da71f 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -1541,61 +1541,46 @@ abstract class DiagnosticsNode { if (kReleaseMode) { return {}; } - final Map data = { + final bool hasChildren = getChildren().isNotEmpty; + return { 'description': toDescription(), 'type': runtimeType.toString(), + if (name != null) + 'name': name, + if (!showSeparator) + 'showSeparator': showSeparator, + if (level != DiagnosticLevel.info) + 'level': describeEnum(level), + if (showName == false) + 'showName': showName, + if (emptyBodyDescription != null) + 'emptyBodyDescription': emptyBodyDescription, + if (style != DiagnosticsTreeStyle.sparse) + 'style': describeEnum(style), + if (allowTruncate) + 'allowTruncate': allowTruncate, + if (hasChildren) + 'hasChildren': hasChildren, + if (linePrefix?.isNotEmpty == true) + 'linePrefix': linePrefix, + if (!allowWrap) + 'allowWrap': allowWrap, + if (allowNameWrap) + 'allowNameWrap': allowNameWrap, + ...delegate.additionalNodeProperties(this), + if (delegate.includeProperties) + 'properties': toJsonList( + delegate.filterProperties(getProperties(), this), + this, + delegate, + ), + if (delegate.subtreeDepth > 0) + 'children': toJsonList( + delegate.filterChildren(getChildren(), this), + this, + delegate, + ), }; - if (name != null) - data['name'] = name; - - if (!showSeparator) - data['showSeparator'] = showSeparator; - if (level != DiagnosticLevel.info) - data['level'] = describeEnum(level); - if (showName == false) - data['showName'] = showName; - if (emptyBodyDescription != null) - data['emptyBodyDescription'] = emptyBodyDescription; - if (style != DiagnosticsTreeStyle.sparse) - data['style'] = describeEnum(style); - - if (allowTruncate) - data['allowTruncate'] = allowTruncate; - - final bool hasChildren = getChildren().isNotEmpty; - if (hasChildren) - data['hasChildren'] = hasChildren; - - if (linePrefix?.isNotEmpty == true) - data['linePrefix'] = linePrefix; - - if (!allowWrap) - data['allowWrap'] = allowWrap; - - if (allowNameWrap) - data['allowNameWrap'] = allowNameWrap; - - data.addAll(delegate.additionalNodeProperties(this)); - - if (delegate.includeProperties) { - final List properties = getProperties(); - data['properties'] = toJsonList( - delegate.filterProperties(properties, this), - this, - delegate, - ); - } - - if (delegate.subtreeDepth > 0) { - final List children = getChildren(); - data['children'] = toJsonList( - delegate.filterChildren(children, this), - this, - delegate, - ); - } - - return data; } /// Serializes a [List] of [DiagnosticsNode]s to a JSON list according to diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index c0b76c7100..40f53fa94b 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -268,33 +268,32 @@ class AboutDialog extends StatelessWidget { final String name = applicationName ?? _defaultApplicationName(context); final String version = applicationVersion ?? _defaultApplicationVersion(context); final Widget icon = applicationIcon ?? _defaultApplicationIcon(context); - List body = []; - if (icon != null) - body.add(IconTheme(data: const IconThemeData(size: 48.0), child: icon)); - body.add(Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24.0), - child: ListBody( - children: [ - Text(name, style: Theme.of(context).textTheme.headline), - Text(version, style: Theme.of(context).textTheme.body1), - Container(height: 18.0), - Text(applicationLegalese ?? '', style: Theme.of(context).textTheme.caption), - ], - ), - ), - )); - body = [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: body, - ), - ]; - if (children != null) - body.addAll(children); return AlertDialog( content: SingleChildScrollView( - child: ListBody(children: body), + child: ListBody( + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (icon != null) IconTheme(data: const IconThemeData(size: 48.0), child: icon), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: ListBody( + children: [ + Text(name, style: Theme.of(context).textTheme.headline), + Text(version, style: Theme.of(context).textTheme.body1), + Container(height: 18.0), + Text(applicationLegalese ?? '', style: Theme.of(context).textTheme.caption), + ], + ), + ), + ), + ], + ), + ...?children, + ], + ), ), actions: [ FlatButton( @@ -457,24 +456,6 @@ class _LicensePageState extends State { final String name = widget.applicationName ?? _defaultApplicationName(context); final String version = widget.applicationVersion ?? _defaultApplicationVersion(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final List contents = [ - Text(name, style: Theme.of(context).textTheme.headline, textAlign: TextAlign.center), - Text(version, style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center), - Container(height: 18.0), - Text(widget.applicationLegalese ?? '', style: Theme.of(context).textTheme.caption, textAlign: TextAlign.center), - Container(height: 18.0), - Text('Powered by Flutter', style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center), - Container(height: 24.0), - ]; - contents.addAll(_licenses); - if (!_loaded) { - contents.add(const Padding( - padding: EdgeInsets.symmetric(vertical: 24.0), - child: Center( - child: CircularProgressIndicator(), - ), - )); - } return Scaffold( appBar: AppBar( title: Text(localizations.licensesPageTitle), @@ -491,7 +472,23 @@ class _LicensePageState extends State { child: Scrollbar( child: ListView( padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 12.0), - children: contents, + children: [ + Text(name, style: Theme.of(context).textTheme.headline, textAlign: TextAlign.center), + Text(version, style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center), + Container(height: 18.0), + Text(widget.applicationLegalese ?? '', style: Theme.of(context).textTheme.caption, textAlign: TextAlign.center), + Container(height: 18.0), + Text('Powered by Flutter', style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center), + Container(height: 24.0), + ..._licenses, + if (!_loaded) + const Padding( + padding: EdgeInsets.symmetric(vertical: 24.0), + child: Center( + child: CircularProgressIndicator(), + ), + ) + ], ), ), ), diff --git a/packages/flutter/lib/src/material/date_picker.dart b/packages/flutter/lib/src/material/date_picker.dart index 81540f1f90..7e3e985311 100644 --- a/packages/flutter/lib/src/material/date_picker.dart +++ b/packages/flutter/lib/src/material/date_picker.dart @@ -392,8 +392,9 @@ class DayPicker extends StatelessWidget { final int month = displayedMonth.month; final int daysInMonth = getDaysInMonth(year, month); final int firstDayOffset = _computeFirstDayOffset(year, month, localizations); - final List labels = []; - labels.addAll(_getDayHeaders(themeData.textTheme.caption, localizations)); + final List labels = [ + ..._getDayHeaders(themeData.textTheme.caption, localizations), + ]; for (int i = 0; true; i += 1) { // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on // a leap year. diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index d15ebe810c..99a9544c68 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -2110,14 +2110,12 @@ class ScaffoldState extends State with TickerProviderStateMixin { } if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) { - final List bottomSheets = []; - if (_dismissedBottomSheets.isNotEmpty) - bottomSheets.addAll(_dismissedBottomSheets); - if (_currentBottomSheet != null) - bottomSheets.add(_currentBottomSheet._widget); final Widget stack = Stack( - children: bottomSheets, alignment: Alignment.bottomCenter, + children: [ + ..._dismissedBottomSheets, + if (_currentBottomSheet != null) _currentBottomSheet._widget, + ], ); _addIfNonNull( children, diff --git a/packages/flutter/lib/src/painting/borders.dart b/packages/flutter/lib/src/painting/borders.dart index c1585c3994..59300f32b4 100644 --- a/packages/flutter/lib/src/painting/borders.dart +++ b/packages/flutter/lib/src/painting/borders.dart @@ -528,22 +528,18 @@ class _CompoundBorder extends ShapeBorder { final ShapeBorder merged = ours.add(other, reversed: reversed) ?? other.add(ours, reversed: !reversed); if (merged != null) { - final List result = []; - result.addAll(borders); + final List result = [...borders]; result[reversed ? result.length - 1 : 0] = merged; return _CompoundBorder(result); } } // We can't, so fall back to just adding the new border to the list. - final List mergedBorders = []; - if (reversed) - mergedBorders.addAll(borders); - if (other is _CompoundBorder) - mergedBorders.addAll(other.borders); - else - mergedBorders.add(other); - if (!reversed) - mergedBorders.addAll(borders); + final List mergedBorders = [ + if (reversed) ...borders, + if (other is _CompoundBorder) ...other.borders + else other, + if (!reversed) ...borders, + ]; return _CompoundBorder(mergedBorders); } diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 99e03b2972..394a988368 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -498,13 +498,11 @@ class BoxConstraints extends Constraints { }) { assert(() { void throwError(DiagnosticsNode message) { - final List information = [message]; - if (informationCollector != null) { - information.addAll(informationCollector()); - } - - information.add(DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty)); - throw FlutterError.fromParts(information); + throw FlutterError.fromParts([ + message, + if (informationCollector != null) ...informationCollector(), + DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty), + ]); } if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { final List affectedFieldsList = []; @@ -1952,12 +1950,12 @@ abstract class RenderBox extends RenderObject { information.add(node.describeForError('The nearest ancestor providing an unbounded height constraint is')); } - final List errorParts = []; - errorParts.addAll(information); - errorParts.add(DiagnosticsProperty('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty)); - errorParts.add(DiagnosticsProperty('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty)); - errorParts.add(ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.')); - throw FlutterError.fromParts(errorParts); + throw FlutterError.fromParts([ + ...information, + DiagnosticsProperty('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty), + ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.'), + ]); } // verify that the size is within the constraints if (!constraints.isSatisfiedBy(_size)) { diff --git a/packages/flutter/lib/src/rendering/custom_paint.dart b/packages/flutter/lib/src/rendering/custom_paint.dart index 3edf474771..907c78d0da 100644 --- a/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/packages/flutter/lib/src/rendering/custom_paint.dart @@ -628,12 +628,11 @@ class RenderCustomPaint extends RenderProxyBox { final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes.isNotEmpty; final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes.isNotEmpty; - final List finalChildren = []; - if (hasBackgroundSemantics) - finalChildren.addAll(_backgroundSemanticsNodes); - finalChildren.addAll(children); - if (hasForegroundSemantics) - finalChildren.addAll(_foregroundSemanticsNodes); + final List finalChildren = [ + if (hasBackgroundSemantics) ..._backgroundSemanticsNodes, + ...children, + if (hasForegroundSemantics) ..._foregroundSemanticsNodes, + ]; super.assembleSemanticsNode(node, config, finalChildren); } diff --git a/packages/flutter/lib/src/rendering/object.dart b/packages/flutter/lib/src/rendering/object.dart index 5c9f545873..52711d37aa 100644 --- a/packages/flutter/lib/src/rendering/object.dart +++ b/packages/flutter/lib/src/rendering/object.dart @@ -3326,15 +3326,16 @@ class _RootSemanticsFragment extends _InterestingSemanticsFragment { node.rect = owner.semanticBounds; - final List children = []; - for (_InterestingSemanticsFragment fragment in _children) { - assert(fragment.config == null); - children.addAll(fragment.compileChildren( - parentSemanticsClipRect: parentSemanticsClipRect, - parentPaintClipRect: parentPaintClipRect, - elevationAdjustment: 0.0, - )); - } + final List children = _children + .expand((_InterestingSemanticsFragment fragment) { + assert(fragment.config == null); + return fragment.compileChildren( + parentSemanticsClipRect: parentSemanticsClipRect, + parentPaintClipRect: parentPaintClipRect, + elevationAdjustment: 0.0, + ); + }) + .toList(); node.updateWith(config: null, childrenInInversePaintOrder: children); // The root node is the only semantics node allowed to be invisible. This @@ -3447,14 +3448,13 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment { } } - final List children = []; - for (_InterestingSemanticsFragment fragment in _children) { - children.addAll(fragment.compileChildren( + final List children = _children + .expand((_InterestingSemanticsFragment fragment) => fragment.compileChildren( parentSemanticsClipRect: node.parentSemanticsClipRect, parentPaintClipRect: node.parentPaintClipRect, elevationAdjustment: 0.0, - )); - } + )) + .toList(); if (_config.isSemanticBoundary) { owner.assembleSemanticsNode(node, _config, children); diff --git a/packages/flutter/lib/src/rendering/sliver.dart b/packages/flutter/lib/src/rendering/sliver.dart index f79ca92c70..6d8a569859 100644 --- a/packages/flutter/lib/src/rendering/sliver.dart +++ b/packages/flutter/lib/src/rendering/sliver.dart @@ -421,14 +421,12 @@ class SliverConstraints extends Constraints { void verify(bool check, String message) { if (check) return; - final List information = []; - information.add(ErrorSummary('$runtimeType is not valid: $message')); - - if (informationCollector != null) { - information.addAll(informationCollector()); - } - information.add(DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty)); - throw FlutterError.fromParts(information); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType is not valid: $message'), + if (informationCollector != null) + ...informationCollector(), + DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty) + ]); } verify(axis != null, 'The "axis" is null.'); verify(growthDirection != null, 'The "growthDirection" is null.'); @@ -700,15 +698,12 @@ class SliverGeometry extends Diagnosticable { void verify(bool check, String summary, {List details}) { if (check) return; - final List information = []; - information.add(ErrorSummary('$runtimeType is not valid: $summary')); - if (details != null) { - information.addAll(details); - } - if (informationCollector != null) { - information.addAll(informationCollector()); - } - throw FlutterError.fromParts(information); + throw FlutterError.fromParts([ + ErrorSummary('$runtimeType is not valid: $summary'), + ...?details, + if (informationCollector != null) + ...informationCollector(), + ]); } verify(scrollExtent != null, 'The "scrollExtent" is null.'); diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 6da0b2042d..8a2f40d43a 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -2280,12 +2280,9 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> { horizontalGroups = horizontalGroups.reversed.toList(); } - final List result = []; - for (_SemanticsSortGroup group in horizontalGroups) { - final List sortedKnotNodes = group.sortedWithinKnot(); - result.addAll(sortedKnotNodes); - } - return result; + return horizontalGroups + .expand((_SemanticsSortGroup group) => group.sortedWithinKnot()) + .toList(); } /// Sorts [nodes] where nodes intersect both vertically and horizontally. @@ -2423,12 +2420,9 @@ List _childrenInDefaultOrder(List children, TextDi } verticalGroups.sort(); - final List result = []; - for (_SemanticsSortGroup group in verticalGroups) { - final List sortedGroupNodes = group.sortedWithinVerticalGroup(); - result.addAll(sortedGroupNodes); - } - return result; + return verticalGroups + .expand((_SemanticsSortGroup group) => group.sortedWithinVerticalGroup()) + .toList(); } /// The implementation of [Comparable] that implements the ordering of diff --git a/packages/flutter/lib/src/widgets/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index 7d0f5c5ea8..982596cc98 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -272,15 +272,15 @@ class NestedScrollView extends StatefulWidget { } List _buildSlivers(BuildContext context, ScrollController innerController, bool bodyIsScrolled) { - final List slivers = []; - slivers.addAll(headerSliverBuilder(context, bodyIsScrolled)); - slivers.add(SliverFillRemaining( - child: PrimaryScrollController( - controller: innerController, - child: body, + return [ + ...headerSliverBuilder(context, bodyIsScrolled), + SliverFillRemaining( + child: PrimaryScrollController( + controller: innerController, + child: body, + ), ), - )); - return slivers; + ]; } @override diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index c46d497844..a1031824d4 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -1534,14 +1534,13 @@ mixin WidgetInspectorService { List nodes, _SerializationDelegate delegate, ) { - final List children = []; - for (DiagnosticsNode child in nodes) { - if (!delegate.summaryTree || _shouldShowInSummaryTree(child)) { - children.add(child); - } else { - children.addAll(_getChildrenFiltered(child, delegate)); - } - } + final List children = [ + for (DiagnosticsNode child in nodes) + if (!delegate.summaryTree || _shouldShowInSummaryTree(child)) + child + else + ..._getChildrenFiltered(child, delegate), + ]; return children; } @@ -2154,8 +2153,10 @@ class _WidgetInspectorState extends State return size == null ? double.maxFinite : size.width * size.height; } regularHits.sort((RenderObject a, RenderObject b) => _area(a).compareTo(_area(b))); - final Set hits = {}; - hits..addAll(edgeHits)..addAll(regularHits); + final Set hits = { + ...edgeHits, + ...regularHits, + }; return hits.toList(); } diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index a5fbda6fb8..e17b15e267 100644 --- a/packages/flutter/test/foundation/diagnostics_json_test.dart +++ b/packages/flutter/test/foundation/diagnostics_json_test.dart @@ -174,11 +174,7 @@ void main() { final Map result = testTree.toDiagnosticsNode().toJsonMap(TestDiagnosticsSerializationDelegate( subtreeDepth: 1, childFilter: (List nodes, DiagnosticsNode owner) { - final List result = []; - for (DiagnosticsNode node in nodes) { - result.addAll(node.getChildren()); - } - return result; + return nodes.expand((DiagnosticsNode node) => node.getChildren()).toList(); } )); final List> children = result['children']; diff --git a/packages/flutter/test/rendering/paragraph_test.dart b/packages/flutter/test/rendering/paragraph_test.dart index f9d7df7189..7a07bb9f4c 100644 --- a/packages/flutter/test/rendering/paragraph_test.dart +++ b/packages/flutter/test/rendering/paragraph_test.dart @@ -260,13 +260,13 @@ void main() { expect(paragraph.size.height, 26.0); // Test the sizes of nested spans. - final List boxes = []; final String text = testSpan.toStringDeep(); - for (int i = 0; i < text.length; ++i) { - boxes.addAll(paragraph.getBoxesForSelection( + final List boxes = [ + for (int i = 0; i < text.length; ++i) + ...paragraph.getBoxesForSelection( TextSelection(baseOffset: i, extentOffset: i + 1) - )); - } + ), + ]; expect(boxes.length, equals(4)); // anyOf is needed here and below because Linux and Mac have different text diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index 21507916d8..bf7d337f48 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -836,15 +836,11 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { _allowedAssetKeys = {}; return; } - final Map manifest = json.decode( - manifestFile.readAsStringSync()); + final Map manifest = json.decode(manifestFile.readAsStringSync()); _allowedAssetKeys = { 'AssetManifest.json', + ...manifest.values.cast>().expand((List e) => e).cast(), }; - for (List value in manifest.values) { - final List strList = List.from(value); - _allowedAssetKeys.addAll(strList); - } } @override diff --git a/packages/flutter_test/pubspec.yaml b/packages/flutter_test/pubspec.yaml index 7641191be9..03651bb2c9 100644 --- a/packages/flutter_test/pubspec.yaml +++ b/packages/flutter_test/pubspec.yaml @@ -2,7 +2,7 @@ name: flutter_test environment: # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: # To update these, use "flutter update-packages --force-upgrade". diff --git a/packages/flutter_tools/bin/fuchsia_attach.dart b/packages/flutter_tools/bin/fuchsia_attach.dart index 04f713f144..2427b9b091 100644 --- a/packages/flutter_tools/bin/fuchsia_attach.dart +++ b/packages/flutter_tools/bin/fuchsia_attach.dart @@ -72,6 +72,7 @@ Future main(List args) async { // Otherwise assume the package is flat. targetFile = entrypoint; } + final String deviceName = argResults['device']; final List command = [ 'attach', '--module', @@ -86,14 +87,9 @@ Future main(List args) async { outputDill, '--packages', packages, + if (deviceName != null && deviceName.isNotEmpty) ...['-d', deviceName], + if (verbose) '--verbose', ]; - final String deviceName = argResults['device']; - if (deviceName != null && deviceName.isNotEmpty) { - command.addAll(['-d', deviceName]); - } - if (verbose) { - command.add('--verbose'); - } Cache.disableLocking(); // ignore: invalid_use_of_visible_for_testing_member await runner.run( command, diff --git a/packages/flutter_tools/lib/src/android/android_device.dart b/packages/flutter_tools/lib/src/android/android_device.dart index 6ebd461bbf..ff3661adb4 100644 --- a/packages/flutter_tools/lib/src/android/android_device.dart +++ b/packages/flutter_tools/lib/src/android/android_device.dart @@ -520,40 +520,40 @@ class AndroidDevice extends Device { '-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP '--ez', 'enable-background-compilation', 'true', '--ez', 'enable-dart-profiling', 'true', + if (traceStartup) + ...['--ez', 'trace-startup', 'true'], + if (route != null) + ...['--es', 'route', route], + if (debuggingOptions.enableSoftwareRendering) + ...['--ez', 'enable-software-rendering', 'true'], + if (debuggingOptions.skiaDeterministicRendering) + ...['--ez', 'skia-deterministic-rendering', 'true'], + if (debuggingOptions.traceSkia) + ...['--ez', 'trace-skia', 'true'], + if (debuggingOptions.traceSystrace) + ...['--ez', 'trace-systrace', 'true'], + if (debuggingOptions.dumpSkpOnShaderCompilation) + ...['--ez', 'dump-skp-on-shader-compilation', 'true'], + if (debuggingOptions.debuggingEnabled) + ...[ + if (debuggingOptions.buildInfo.isDebug) + ...[ + ...['--ez', 'enable-checked-mode', 'true'], + ...['--ez', 'verify-entry-points', 'true'], + ], + if (debuggingOptions.startPaused) + ...['--ez', 'start-paused', 'true'], + if (debuggingOptions.disableServiceAuthCodes) + ...['--ez', 'disable-service-auth-codes', 'true'], + if (debuggingOptions.dartFlags.isNotEmpty) + ...['--es', 'dart-flags', debuggingOptions.dartFlags], + if (debuggingOptions.useTestFonts) + ...['--ez', 'use-test-fonts', 'true'], + if (debuggingOptions.verboseSystemLogs) + ...['--ez', 'verbose-logging', 'true'], + ], + apk.launchActivity, ]; - - if (traceStartup) - cmd.addAll(['--ez', 'trace-startup', 'true']); - if (route != null) - cmd.addAll(['--es', 'route', route]); - if (debuggingOptions.enableSoftwareRendering) - cmd.addAll(['--ez', 'enable-software-rendering', 'true']); - if (debuggingOptions.skiaDeterministicRendering) - cmd.addAll(['--ez', 'skia-deterministic-rendering', 'true']); - if (debuggingOptions.traceSkia) - cmd.addAll(['--ez', 'trace-skia', 'true']); - if (debuggingOptions.traceSystrace) - cmd.addAll(['--ez', 'trace-systrace', 'true']); - if (debuggingOptions.dumpSkpOnShaderCompilation) - cmd.addAll(['--ez', 'dump-skp-on-shader-compilation', 'true']); - if (debuggingOptions.debuggingEnabled) { - if (debuggingOptions.buildInfo.isDebug) { - cmd.addAll(['--ez', 'enable-checked-mode', 'true']); - cmd.addAll(['--ez', 'verify-entry-points', 'true']); - } - if (debuggingOptions.startPaused) - cmd.addAll(['--ez', 'start-paused', 'true']); - if (debuggingOptions.disableServiceAuthCodes) - cmd.addAll(['--ez', 'disable-service-auth-codes', 'true']); - if (debuggingOptions.dartFlags.isNotEmpty) - cmd.addAll(['--es', 'dart-flags', debuggingOptions.dartFlags]); - if (debuggingOptions.useTestFonts) - cmd.addAll(['--ez', 'use-test-fonts', 'true']); - if (debuggingOptions.verboseSystemLogs) { - cmd.addAll(['--ez', 'verbose-logging', 'true']); - } - } - cmd.add(apk.launchActivity); final String result = (await runAdbCheckedAsync(cmd)).stdout; // This invocation returns 0 even when it fails. if (result.contains('Error: ')) { diff --git a/packages/flutter_tools/lib/src/android/android_studio_validator.dart b/packages/flutter_tools/lib/src/android/android_studio_validator.dart index 3fc1b797f5..368d3a45c4 100644 --- a/packages/flutter_tools/lib/src/android/android_studio_validator.dart +++ b/packages/flutter_tools/lib/src/android/android_studio_validator.dart @@ -17,15 +17,13 @@ class AndroidStudioValidator extends DoctorValidator { final AndroidStudio _studio; static List get allValidators { - final List validators = []; final List studios = AndroidStudio.allInstalled(); - if (studios.isEmpty) { - validators.add(NoAndroidStudioValidator()); - } else { - validators.addAll(studios - .map((AndroidStudio studio) => AndroidStudioValidator(studio))); - } - return validators; + return [ + if (studios.isEmpty) + NoAndroidStudioValidator() + else + ...studios.map((AndroidStudio studio) => AndroidStudioValidator(studio)) + ]; } @override diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart index 30a734fced..d121d83c8b 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart @@ -216,10 +216,10 @@ class _ManifestAssetBundle implements AssetBundle { } } - final List<_Asset> materialAssets = <_Asset>[]; - if (flutterManifest.usesMaterialDesign && includeDefaultFonts) { - materialAssets.addAll(_getMaterialAssets(_fontSetMaterial)); - } + final List<_Asset> materialAssets = <_Asset>[ + if (flutterManifest.usesMaterialDesign && includeDefaultFonts) + ..._getMaterialAssets(_fontSetMaterial), + ]; for (_Asset asset in materialAssets) { assert(asset.assetFileExists); entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile); @@ -421,20 +421,18 @@ List> _parseFonts( PackageMap packageMap, { String packageName, }) { - final List> fonts = >[]; - if (manifest.usesMaterialDesign && includeDefaultFonts) { - fonts.addAll(_getMaterialFonts(_ManifestAssetBundle._fontSetMaterial)); - } - if (packageName == null) { - fonts.addAll(manifest.fontsDescriptor); - } else { - fonts.addAll(_createFontsDescriptor(_parsePackageFonts( - manifest, - packageName, - packageMap, - ))); - } - return fonts; + return >[ + if (manifest.usesMaterialDesign && includeDefaultFonts) + ..._getMaterialFonts(_ManifestAssetBundle._fontSetMaterial), + if (packageName == null) + ...manifest.fontsDescriptor + else + ..._createFontsDescriptor(_parsePackageFonts( + manifest, + packageName, + packageMap, + )), + ]; } /// Prefixes family names and asset paths of fonts included from packages with diff --git a/packages/flutter_tools/lib/src/base/build.dart b/packages/flutter_tools/lib/src/base/build.dart index 8dded9789b..8d2338af66 100644 --- a/packages/flutter_tools/lib/src/base/build.dart +++ b/packages/flutter_tools/lib/src/base/build.dart @@ -228,7 +228,7 @@ class AOTSnapshotter { final List commonBuildOptions = ['-arch', targetArch, '-miphoneos-version-min=8.0']; final String assemblyO = fs.path.join(outputPath, 'snapshot_assembly.o'); - final RunResult compileResult = await xcode.cc(commonBuildOptions.toList()..addAll(['-c', assemblyPath, '-o', assemblyO])); + final RunResult compileResult = await xcode.cc([...commonBuildOptions, '-c', assemblyPath, '-o', assemblyO]); if (compileResult.exitCode != 0) { printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}'); return compileResult; @@ -237,14 +237,15 @@ class AOTSnapshotter { final String frameworkDir = fs.path.join(outputPath, 'App.framework'); fs.directory(frameworkDir).createSync(recursive: true); final String appLib = fs.path.join(frameworkDir, 'App'); - final List linkArgs = commonBuildOptions.toList()..addAll([ - '-dynamiclib', - '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks', - '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks', - '-install_name', '@rpath/App.framework/App', - '-o', appLib, - assemblyO, - ]); + final List linkArgs = [ + ...commonBuildOptions, + '-dynamiclib', + '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks', + '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks', + '-install_name', '@rpath/App.framework/App', + '-o', appLib, + assemblyO, + ]; final RunResult linkResult = await xcode.clang(linkArgs); if (linkResult.exitCode != 0) { printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}'); @@ -371,8 +372,10 @@ class JITSnapshotter { genSnapshotArgs.addAll(extraGenSnapshotOptions); } - final Set outputPaths = {}; - outputPaths.addAll([isolateSnapshotData, isolateSnapshotInstructions]); + final Set outputPaths = { + isolateSnapshotData, + isolateSnapshotInstructions, + }; // There are a couple special cases below where we create a snapshot // with only the data section, which only contains interpreted code. diff --git a/packages/flutter_tools/lib/src/base/fingerprint.dart b/packages/flutter_tools/lib/src/base/fingerprint.dart index 3346ec7b7d..69ce8fc6a2 100644 --- a/packages/flutter_tools/lib/src/base/fingerprint.dart +++ b/packages/flutter_tools/lib/src/base/fingerprint.dart @@ -94,9 +94,11 @@ class Fingerprinter { } Future> _getPaths() async { - final Set paths = _paths.toSet(); - for (String depfilePath in _depfilePaths) - paths.addAll(await readDepfile(depfilePath)); + final Set paths = { + ..._paths, + for (String depfilePath in _depfilePaths) + ...await readDepfile(depfilePath), + }; final FingerprintPathFilter filter = _pathFilter ?? (String path) => true; return paths.where(filter).toList()..sort(); } @@ -118,7 +120,7 @@ class Fingerprint { final List bytes = file.readAsBytesSync(); _checksums[file.path] = md5.convert(bytes).toString(); } - _properties = {}..addAll(properties); + _properties = {...properties}; } /// Creates a Fingerprint from serialized JSON. diff --git a/packages/flutter_tools/lib/src/cache.dart b/packages/flutter_tools/lib/src/cache.dart index d310d10bbf..6d2d13e023 100644 --- a/packages/flutter_tools/lib/src/cache.dart +++ b/packages/flutter_tools/lib/src/cache.dart @@ -637,30 +637,22 @@ class FlutterSdk extends EngineCachedArtifact { @override List> getBinaryDirs() { - final List> binaryDirs = >[ + return >[ ['common', 'flutter_patched_sdk.zip'], ['common', 'flutter_patched_sdk_product.zip'], + if (cache.includeAllPlatforms) + ...>[ + ['windows-x64', 'windows-x64/artifacts.zip'], + ['linux-x64', 'linux-x64/artifacts.zip'], + ['darwin-x64', 'darwin-x64/artifacts.zip'], + ] + else if (platform.isWindows) + ['windows-x64', 'windows-x64/artifacts.zip'] + else if (platform.isMacOS) + ['darwin-x64', 'darwin-x64/artifacts.zip'] + else if (platform.isLinux) + ['linux-x64', 'linux-x64/artifacts.zip'], ]; - if (cache.includeAllPlatforms) { - binaryDirs.addAll(>[ - ['windows-x64', 'windows-x64/artifacts.zip'], - ['linux-x64', 'linux-x64/artifacts.zip'], - ['darwin-x64', 'darwin-x64/artifacts.zip'], - ]); - } else if (platform.isWindows) { - binaryDirs.addAll(>[ - ['windows-x64', 'windows-x64/artifacts.zip'], - ]); - } else if (platform.isMacOS) { - binaryDirs.addAll(>[ - ['darwin-x64', 'darwin-x64/artifacts.zip'], - ]); - } else if (platform.isLinux) { - binaryDirs.addAll(>[ - ['linux-x64', 'linux-x64/artifacts.zip'], - ]); - } - return binaryDirs; } @override @@ -745,28 +737,31 @@ class AndroidEngineArtifacts extends EngineCachedArtifact { @override List> getBinaryDirs() { - final List> binaryDirs = >[]; - if (cache.includeAllPlatforms) { - binaryDirs - ..addAll(_osxBinaryDirs) - ..addAll(_linuxBinaryDirs) - ..addAll(_windowsBinaryDirs) - ..addAll(_androidBinaryDirs) - ..addAll(_dartSdks); - } else if (platform.isWindows) { - binaryDirs - ..addAll(_windowsBinaryDirs) - ..addAll(_androidBinaryDirs); - } else if (platform.isMacOS) { - binaryDirs - ..addAll(_osxBinaryDirs) - ..addAll(_androidBinaryDirs); - } else if (platform.isLinux) { - binaryDirs - ..addAll(_linuxBinaryDirs) - ..addAll(_androidBinaryDirs); - } - return binaryDirs; + return >[ + if (cache.includeAllPlatforms) + ...>[ + ..._osxBinaryDirs, + ..._linuxBinaryDirs, + ..._windowsBinaryDirs, + ..._androidBinaryDirs, + ..._dartSdks, + ] + else if (platform.isWindows) + ...>[ + ..._windowsBinaryDirs, + ..._androidBinaryDirs, + ] + else if (platform.isMacOS) + ...>[ + ..._osxBinaryDirs, + ..._androidBinaryDirs, + ] + else if (platform.isLinux) + ...>[ + ..._linuxBinaryDirs, + ..._androidBinaryDirs, + ] + ]; } @override @@ -782,11 +777,10 @@ class IOSEngineArtifacts extends EngineCachedArtifact { @override List> getBinaryDirs() { - final List> binaryDirs = >[]; - if (platform.isMacOS || cache.includeAllPlatforms) { - binaryDirs.addAll(_iosBinaryDirs); - } - return binaryDirs; + return >[ + if (platform.isMacOS || cache.includeAllPlatforms) + ..._iosBinaryDirs, + ]; } @override @@ -914,10 +908,10 @@ final Map> _flattenNameSubstitutions = >{ /// Given a name containing slashes, colons, and backslashes, expand it into /// something that doesn't. String _flattenNameNoSubdirs(String fileName) { - final List replacedCodeUnits = []; - for (int codeUnit in fileName.codeUnits) { - replacedCodeUnits.addAll(_flattenNameSubstitutions[codeUnit] ?? [codeUnit]); - } + final List replacedCodeUnits = [ + for (int codeUnit in fileName.codeUnits) + ..._flattenNameSubstitutions[codeUnit] ?? [codeUnit], + ]; return String.fromCharCodes(replacedCodeUnits); } diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index 079582a4f1..dff4b34e73 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -618,10 +618,10 @@ class AppDomain extends Domain { } void _sendAppEvent(AppInstance app, String name, [ Map args ]) { - final Map eventArgs = {'appId': app.id}; - if (args != null) - eventArgs.addAll(args); - sendEvent('app.$name', eventArgs); + sendEvent('app.$name', { + 'appId': app.id, + ...?args, + }); } } diff --git a/packages/flutter_tools/lib/src/commands/format.dart b/packages/flutter_tools/lib/src/commands/format.dart index 1b0c407891..6107c0989d 100644 --- a/packages/flutter_tools/lib/src/commands/format.dart +++ b/packages/flutter_tools/lib/src/commands/format.dart @@ -61,23 +61,14 @@ class FormatCommand extends FlutterCommand { } final String dartfmt = sdkBinaryName('dartfmt'); - final List command = [dartfmt]; - - if (argResults['dry-run']) { - command.add('-n'); - } - if (argResults['machine']) { - command.add('-m'); - } - if (!argResults['dry-run'] && !argResults['machine']) { - command.add('-w'); - } - - if (argResults['set-exit-if-changed']) { - command.add('--set-exit-if-changed'); - } - - command..addAll(argResults.rest); + final List command = [ + dartfmt, + if (argResults['dry-run']) '-n', + if (argResults['machine']) '-m', + if (!argResults['dry-run'] && !argResults['machine']) '-w', + if (argResults['set-exit-if-changed']) '--set-exit-if-changed', + ...argResults.rest, + ]; final int result = await runCommandAndStreamOutput(command); if (result != 0) diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 81090cda40..edb2b6e307 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -179,15 +179,13 @@ class TestCommand extends FastFlutterCommand { ); } } else { - final List fileCopy = []; - for (String file in files) { - if (file.endsWith(platform.pathSeparator)) { - fileCopy.addAll(_findTests(fs.directory(file))); - } else { - fileCopy.add(file); - } - } - files = fileCopy; + files = [ + for (String file in files) + if (file.endsWith(platform.pathSeparator)) + ..._findTests(fs.directory(file)) + else + file + ]; } CoverageCollector collector; diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index 8e98f75fef..691001be2b 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart @@ -728,9 +728,11 @@ class PubspecYaml { // Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies, // and the dependencies we know this file mentions that are already pinned // (and which didn't get special processing above). - final Set implied = Set.from(directDependencies) - ..addAll(specialDependencies) - ..addAll(devDependencies); + final Set implied = { + ...directDependencies, + ...specialDependencies, + ...devDependencies, + }; // Create a new set to hold the list of packages we've already processed, so // that we don't redundantly process them multiple times. @@ -751,12 +753,12 @@ class PubspecYaml { transitiveDevDependencyOutput.add(' $package: ${versions.versionFor(package)} $kTransitiveMagicString'); // Build a sorted list of all dependencies for the checksum. - final Set checksumDependencies = {} - ..addAll(directDependencies) - ..addAll(devDependencies) - ..addAll(transitiveDependenciesAsList) - ..addAll(transitiveDevDependenciesAsList); - checksumDependencies.removeAll(specialDependencies); + final Set checksumDependencies = { + ...directDependencies, + ...devDependencies, + ...transitiveDependenciesAsList, + ...transitiveDevDependenciesAsList, + }..removeAll(specialDependencies); // Add a blank line before and after each section to keep the resulting output clean. transitiveDependencyOutput diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index ebbb02d740..ca694e9b94 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -96,12 +96,12 @@ Future pubGet({ 'Running "flutter pub $command" in ${fs.path.basename(directory)}...', timeout: timeoutConfiguration.slowOperation, ); - final List args = ['--verbosity=warning']; - if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose']) - args.add('--verbose'); - args.addAll([command, '--no-precompile']); - if (offline) - args.add('--offline'); + final List args = [ + '--verbosity=warning', + if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose']) '--verbose', + ...[command, '--no-precompile'], + if (offline) '--offline', + ]; try { await pub( args, @@ -228,21 +228,13 @@ const String _pubCacheEnvironmentKey = 'PUB_CACHE'; String _getPubEnvironmentValue(PubContext pubContext) { // DO NOT update this function without contacting kevmoo. // We have server-side tooling that assumes the values are consistent. - final List values = []; - final String existing = platform.environment[_pubEnvironmentKey]; - - if ((existing != null) && existing.isNotEmpty) { - values.add(existing); - } - - if (isRunningOnBot) { - values.add('flutter_bot'); - } - - values.add('flutter_cli'); - values.addAll(pubContext._values); - + final List values = [ + if (existing != null && existing.isNotEmpty) existing, + if (isRunningOnBot) 'flutter_bot', + 'flutter_cli', + ...pubContext._values, + ]; return values.join(':'); } diff --git a/packages/flutter_tools/lib/src/device.dart b/packages/flutter_tools/lib/src/device.dart index 765ef35c0f..261e1a06b7 100644 --- a/packages/flutter_tools/lib/src/device.dart +++ b/packages/flutter_tools/lib/src/device.dart @@ -161,11 +161,10 @@ class DeviceManager { /// Get diagnostics about issues with any connected devices. Future> getDeviceDiagnostics() async { - final List diagnostics = []; - for (DeviceDiscovery discoverer in _platformDiscoverers) { - diagnostics.addAll(await discoverer.getDiagnostics()); - } - return diagnostics; + return [ + for (DeviceDiscovery discoverer in _platformDiscoverers) + ...await discoverer.getDiagnostics(), + ]; } /// Find and return a list of devices based on the current project and environment. diff --git a/packages/flutter_tools/lib/src/doctor.dart b/packages/flutter_tools/lib/src/doctor.dart index 15526ca712..58ba4de796 100644 --- a/packages/flutter_tools/lib/src/doctor.dart +++ b/packages/flutter_tools/lib/src/doctor.dart @@ -60,45 +60,37 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider { @override List get validators { if (_validators == null) { - _validators = []; - _validators.add(FlutterValidator()); + final List ideValidators = [ + ...AndroidStudioValidator.allValidators, + ...IntelliJValidator.installedValidators, + ...VsCodeValidator.installedValidators, + ]; - if (androidWorkflow.appliesToHostPlatform) - _validators.add(GroupedValidator([androidValidator, androidLicenseValidator])); - - if (iosWorkflow.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform) - _validators.add(GroupedValidator([xcodeValidator, cocoapodsValidator])); - - if (iosWorkflow.appliesToHostPlatform) - _validators.add(iosValidator); - - if (webWorkflow.appliesToHostPlatform) - _validators.add(const WebValidator()); - - // Add desktop doctors to workflow if the flag is enabled. - if (flutterDesktopEnabled) { - if (linuxWorkflow.appliesToHostPlatform) { - _validators.add(LinuxDoctorValidator()); - } - if (windowsWorkflow.appliesToHostPlatform) { - _validators.add(visualStudioValidator); - } - } - - final List ideValidators = []; - ideValidators.addAll(AndroidStudioValidator.allValidators); - ideValidators.addAll(IntelliJValidator.installedValidators); - ideValidators.addAll(VsCodeValidator.installedValidators); - if (ideValidators.isNotEmpty) - _validators.addAll(ideValidators); - else - _validators.add(NoIdeValidator()); - - if (ProxyValidator.shouldShow) - _validators.add(ProxyValidator()); - - if (deviceManager.canListAnything) - _validators.add(DeviceValidator()); + _validators = [ + FlutterValidator(), + if (androidWorkflow.appliesToHostPlatform) + GroupedValidator([androidValidator, androidLicenseValidator]), + if (iosWorkflow.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform) + GroupedValidator([xcodeValidator, cocoapodsValidator]), + if (iosWorkflow.appliesToHostPlatform) + iosValidator, + if (webWorkflow.appliesToHostPlatform) + const WebValidator(), + // Add desktop doctors to workflow if the flag is enabled. + if (flutterDesktopEnabled) + ...[ + if (linuxWorkflow.appliesToHostPlatform) LinuxDoctorValidator(), + if (windowsWorkflow.appliesToHostPlatform) visualStudioValidator, + ], + if (ideValidators.isNotEmpty) + ...ideValidators + else + NoIdeValidator(), + if (ProxyValidator.shouldShow) + ProxyValidator(), + if (deviceManager.canListAnything) + DeviceValidator(), + ]; } return _validators; } diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index 9ff8e7b57a..ecf9bf52c7 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -144,12 +144,16 @@ class SimControl { } Future launch(String deviceId, String appIdentifier, [ List launchArgs ]) { - final List args = [_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier]; - if (launchArgs != null) - args.addAll(launchArgs); Future result; try { - result = runCheckedAsync(args); + result = runCheckedAsync([ + _xcrunPath, + 'simctl', + 'launch', + deviceId, + appIdentifier, + ...?launchArgs, + ]); } on ProcessException catch (exception) { throwToolExit('Unable to launch $appIdentifier on $deviceId:\n$exception'); } diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 2e655bb579..788114836d 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -407,12 +407,10 @@ abstract class FlutterCommand extends Command { } // Send screen. - final Map additionalUsageValues = {}; final Map currentUsageValues = await usageValues; - - if (currentUsageValues != null) { - additionalUsageValues.addAll(currentUsageValues); - } + final Map additionalUsageValues = { + ...?currentUsageValues, + }; if (commandResult != null) { switch (commandResult.exitStatus) { case ExitStatus.success: @@ -429,11 +427,12 @@ abstract class FlutterCommand extends Command { flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues); // Send timing. - final List labels = []; - if (commandResult?.exitStatus != null) - labels.add(getEnumName(commandResult.exitStatus)); - if (commandResult?.timingLabelParts?.isNotEmpty ?? false) - labels.addAll(commandResult.timingLabelParts); + final List labels = [ + if (commandResult?.exitStatus != null) + getEnumName(commandResult.exitStatus), + if (commandResult?.timingLabelParts?.isNotEmpty ?? false) + ...commandResult.timingLabelParts, + ]; final String label = labels .where((String label) => !isBlank(label)) diff --git a/packages/flutter_tools/lib/src/test/runner.dart b/packages/flutter_tools/lib/src/test/runner.dart index 9f814c4132..a230b21191 100644 --- a/packages/flutter_tools/lib/src/test/runner.dart +++ b/packages/flutter_tools/lib/src/test/runner.dart @@ -47,26 +47,19 @@ Future runTests( bool web = false, }) async { // Compute the command-line arguments for package:test. - final List testArgs = []; - if (!terminal.supportsColor) { - testArgs.addAll(['--no-color']); - } - - if (machine) { - testArgs.addAll(['-r', 'json']); - } else { - testArgs.addAll(['-r', 'compact']); - } - - testArgs.add('--concurrency=$concurrency'); - - for (String name in names) { - testArgs..add('--name')..add(name); - } - - for (String plainName in plainNames) { - testArgs..add('--plain-name')..add(plainName); - } + final List testArgs = [ + if (!terminal.supportsColor) + '--no-color', + if (machine) + ...['-r', 'json'] + else + ...['-r', 'compact'], + '--concurrency=$concurrency', + for (String name in names) + ...['--name', name], + for (String plainName in plainNames) + ...['--plain-name', plainName], + ]; if (web) { final String tempBuildDir = fs.systemTempDirectory .createTempSync('_flutter_test') @@ -80,10 +73,11 @@ Future runTests( if (!result) { throwToolExit('Failed to compile tests'); } - testArgs.add('--platform=chrome'); - testArgs.add('--precompiled=$tempBuildDir'); - testArgs.add('--'); - testArgs.addAll(testFiles); + testArgs + ..add('--platform=chrome') + ..add('--precompiled=$tempBuildDir') + ..add('--') + ..addAll(testFiles); hack.registerPlatformPlugin( [Runtime.chrome], () { @@ -94,8 +88,9 @@ Future runTests( return exitCode; } - testArgs.add('--'); - testArgs.addAll(testFiles); + testArgs + ..add('--') + ..addAll(testFiles); // Configure package:test to use the Flutter engine for child processes. final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester); diff --git a/packages/flutter_tools/lib/src/version.dart b/packages/flutter_tools/lib/src/version.dart index f56487353a..c3c14c4205 100644 --- a/packages/flutter_tools/lib/src/version.dart +++ b/packages/flutter_tools/lib/src/version.dart @@ -133,12 +133,15 @@ class FlutterVersion { String get frameworkCommitDate => _latestGitCommitDate(); static String _latestGitCommitDate([ String branch ]) { - final List args = ['git', 'log']; - - if (branch != null) - args.add(branch); - - args.addAll(['-n', '1', '--pretty=format:%ad', '--date=iso']); + final List args = [ + 'git', + 'log', + if (branch != null) branch, + '-n', + '1', + '--pretty=format:%ad', + '--date=iso', + ]; return _runSync(args, lenient: false); } diff --git a/packages/flutter_tools/test/base/fingerprint_test.dart b/packages/flutter_tools/test/base/fingerprint_test.dart index 04ed53e136..2397cfc8ef 100644 --- a/packages/flutter_tools/test/base/fingerprint_test.dart +++ b/packages/flutter_tools/test/base/fingerprint_test.dart @@ -211,7 +211,8 @@ void main() { expect(await fingerprinter.doesFingerprintMatch(), isFalse); }, overrides: { Platform: () => mockPlatformDisabledCache, - }..addAll(contextOverrides)); + ...contextOverrides, + }); final Platform mockPlatformEnabledCache = MockPlatform(); mockPlatformEnabledCache.environment['DISABLE_FLUTTER_BUILD_CACHE'] = 'false'; @@ -231,7 +232,8 @@ void main() { expect(await fingerprinter.doesFingerprintMatch(), isTrue); }, overrides: { Platform: () => mockPlatformEnabledCache, - }..addAll(contextOverrides)); + ...contextOverrides, + }); testUsingContext('fails to write fingerprint if inputs are missing', () async { final Fingerprinter fingerprinter = Fingerprinter( diff --git a/packages/flutter_tools/test/commands/build_bundle_test.dart b/packages/flutter_tools/test/commands/build_bundle_test.dart index 65506bacbf..5000eb9d7d 100644 --- a/packages/flutter_tools/test/commands/build_bundle_test.dart +++ b/packages/flutter_tools/test/commands/build_bundle_test.dart @@ -53,13 +53,11 @@ void main() { Future runCommandIn(String projectPath, { List arguments }) async { final BuildBundleCommand command = BuildBundleCommand(bundleBuilder: mockBundleBuilder); final CommandRunner runner = createTestCommandRunner(command); - - final List commandArgs = ['bundle']; - if (arguments != null) - commandArgs.addAll(arguments); - commandArgs.add('--target=$projectPath/lib/main.dart'); - - await runner.run(commandArgs); + await runner.run([ + 'bundle', + ...?arguments, + '--target=$projectPath/lib/main.dart', + ]); return command; } diff --git a/packages/flutter_tools/test/commands/create_test.dart b/packages/flutter_tools/test/commands/create_test.dart index 4da6a9c434..2a3543e426 100644 --- a/packages/flutter_tools/test/commands/create_test.dart +++ b/packages/flutter_tools/test/commands/create_test.dart @@ -1129,10 +1129,11 @@ Future _createProject( Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner runner = createTestCommandRunner(command); - final List args = ['create']; - args.addAll(createArgs); - args.add(dir.path); - await runner.run(args); + await runner.run([ + 'create', + ...createArgs, + dir.path, + ]); bool pathExists(String path) { final String fullPath = fs.path.join(dir.path, path); diff --git a/packages/flutter_tools/test/commands/ide_config_test.dart b/packages/flutter_tools/test/commands/ide_config_test.dart index 70348ea64d..0bed2322ad 100644 --- a/packages/flutter_tools/test/commands/ide_config_test.dart +++ b/packages/flutter_tools/test/commands/ide_config_test.dart @@ -85,9 +85,11 @@ void main() { dir ??= tempDir; final IdeConfigCommand command = IdeConfigCommand(); final CommandRunner runner = createTestCommandRunner(command); - final List finalArgs = ['--flutter-root=${tempDir.absolute.path}', 'ide-config']; - finalArgs.addAll(args); - await runner.run(finalArgs); + await runner.run([ + '--flutter-root=${tempDir.absolute.path}', + 'ide-config', + ...args, + ]); for (String path in expectedContents.keys) { final String absPath = fs.path.join(tempDir.absolute.path, path); @@ -148,8 +150,10 @@ void main() { 'template', ); _populateDir(templateManifest); - final Map expectedContents = templateManifest; - expectedContents.addAll(flutterManifest); + final Map expectedContents = { + ...templateManifest, + ...flutterManifest, + }; return _updateIdeConfig( expectedContents: expectedContents, ); @@ -171,8 +175,10 @@ void main() { tempDir, 'template', ); - final Map expectedContents = templateManifest; - expectedContents.addAll(overwrittenManifest); + final Map expectedContents = { + ...templateManifest, + ...overwrittenManifest, + }; return _updateIdeConfig( args: ['--overwrite'], expectedContents: expectedContents, @@ -200,8 +206,10 @@ void main() { 'existing', ); _populateDir(flutterManifest); - final Map expectedContents = flutterManifest; - expectedContents.addAll(templateManifest); + final Map expectedContents = { + ...flutterManifest, + ...templateManifest, + }; return _updateIdeConfig( args: ['--update-templates'], expectedContents: expectedContents, @@ -225,8 +233,10 @@ void main() { 'existing', isTemplate: true, ); - final Map expectedContents = flutterManifest; - expectedContents.addAll(updatedTemplates); + final Map expectedContents = { + ...flutterManifest, + ...updatedTemplates, + }; return _updateIdeConfig( args: ['--update-templates', '--overwrite'], expectedContents: expectedContents, @@ -259,8 +269,10 @@ void main() { 'flutter.iml${Template.copyTemplateExtension}', ); updatedTemplates.remove(flutterIml); - final Map expectedContents = flutterManifest; - expectedContents.addAll(updatedTemplates); + final Map expectedContents = { + ...flutterManifest, + ...updatedTemplates, + }; return _updateIdeConfig( args: ['--update-templates', '--overwrite'], expectedContents: expectedContents, @@ -298,8 +310,10 @@ void main() { updatedTemplates.remove(deepIml); deepIml = fs.path.join(deepIml, 'deep.iml'); updatedTemplates.remove(deepIml); - final Map expectedContents = flutterManifest; - expectedContents.addAll(updatedTemplates); + final Map expectedContents = { + ...flutterManifest, + ...updatedTemplates, + }; return _updateIdeConfig( args: ['--update-templates', '--overwrite'], expectedContents: expectedContents, diff --git a/packages/flutter_tools/test/commands/packages_test.dart b/packages/flutter_tools/test/commands/packages_test.dart index e3b6119486..a508acbbd1 100644 --- a/packages/flutter_tools/test/commands/packages_test.dart +++ b/packages/flutter_tools/test/commands/packages_test.dart @@ -61,13 +61,12 @@ void main() { Future runCommandIn(String projectPath, String verb, { List args }) async { final PackagesCommand command = PackagesCommand(); final CommandRunner runner = createTestCommandRunner(command); - - final List commandArgs = ['packages', verb]; - if (args != null) - commandArgs.addAll(args); - commandArgs.add(projectPath); - - await runner.run(commandArgs); + await runner.run([ + 'packages', + verb, + ...?args, + projectPath, + ]); return command; } diff --git a/packages/flutter_tools/test/src/testbed.dart b/packages/flutter_tools/test/src/testbed.dart index dc69d52500..00986dc5ca 100644 --- a/packages/flutter_tools/test/src/testbed.dart +++ b/packages/flutter_tools/test/src/testbed.dart @@ -77,15 +77,13 @@ class Testbed { /// `overrides` may be used to provide new context values for the single test /// case or override any context values from the setup. FutureOr run(FutureOr Function() test, {Map overrides}) { - final Map testOverrides = Map.from(_testbedDefaults); - // Add the initial setUp overrides - if (_overrides != null) { - testOverrides.addAll(_overrides); - } - // Add the test-specific overrides - if (overrides != null) { - testOverrides.addAll(overrides); - } + final Map testOverrides = { + ..._testbedDefaults, + // Add the initial setUp overrides + ...?_overrides, + // Add the test-specific overrides + ...?overrides, + }; // Cache the original flutter root to restore after the test case. final String originalFlutterRoot = Cache.flutterRoot; return runInContext(() { diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart index 66cba359e8..0935d475eb 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart @@ -606,24 +606,21 @@ class _SshPortForwarder implements PortForwarder { // IPv6 interface, it cannot be used to connect to a websocket. final String formattedForwardingUrl = '${localSocket.port}:$_ipv4Loopback:$remotePort'; - final List command = ['ssh']; - if (isIpV6) { - command.add('-6'); - } - if (sshConfigPath != null) { - command.addAll(['-F', sshConfigPath]); - } final String targetAddress = isIpV6 && interface.isNotEmpty ? '$address%$interface' : address; const String dummyRemoteCommand = 'true'; - command.addAll([ + final List command = [ + 'ssh', + if (isIpV6) '-6', + if (sshConfigPath != null) + ...['-F', sshConfigPath], '-nNT', '-f', '-L', formattedForwardingUrl, targetAddress, dummyRemoteCommand, - ]); + ]; _log.fine("_SshPortForwarder running '${command.join(' ')}'"); // Must await for the port forwarding function to completer here, as // forwarding must be completed before surfacing VM events (as the user may @@ -649,20 +646,19 @@ class _SshPortForwarder implements PortForwarder { // uses the IPv4 loopback. final String formattedForwardingUrl = '${_localSocket.port}:$_ipv4Loopback:$_remotePort'; - final List command = ['ssh']; final String targetAddress = _ipV6 && _interface.isNotEmpty ? '$_remoteAddress%$_interface' : _remoteAddress; - if (_sshConfigPath != null) { - command.addAll(['-F', _sshConfigPath]); - } - command.addAll([ + final List command = [ + 'ssh', + if (_sshConfigPath != null) + ...['-F', _sshConfigPath], '-O', 'cancel', '-L', formattedForwardingUrl, targetAddress, - ]); + ]; _log.fine( 'Shutting down SSH forwarding with command: ${command.join(' ')}'); final ProcessResult result = await _processManager.run(command); diff --git a/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart b/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart index c2494d0d01..58a3b235f9 100644 --- a/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart +++ b/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart @@ -82,18 +82,16 @@ class SshCommandRunner { /// If the subprocess creating the SSH tunnel returns a nonzero exit status, /// then an [SshCommandError] is raised. Future> run(String command) async { - final List args = ['ssh']; - if (sshConfigPath != null) { - args.addAll(['-F', sshConfigPath]); - } - if (isIpV6Address(address)) { - final String fullAddress = - interface.isEmpty ? address : '$address%$interface'; - args.addAll(['-6', fullAddress]); - } else { - args.add(address); - } - args.add(command); + final List args = [ + 'ssh', + if (sshConfigPath != null) + ...['-F', sshConfigPath], + if (isIpV6Address(address)) + ...['-6', interface.isEmpty ? address : '$address%$interface'] + else + address, + command, + ]; _log.fine('Running command through SSH: ${args.join(' ')}'); final ProcessResult result = await _processManager.run(args); if (result.exitCode != 0) { diff --git a/packages/fuchsia_remote_debug_protocol/pubspec.yaml b/packages/fuchsia_remote_debug_protocol/pubspec.yaml index 33f9019c6d..9416dd8625 100644 --- a/packages/fuchsia_remote_debug_protocol/pubspec.yaml +++ b/packages/fuchsia_remote_debug_protocol/pubspec.yaml @@ -5,7 +5,7 @@ author: Flutter Authors environment: # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: json_rpc_2: 2.1.0