diff --git a/analysis_options.yaml b/analysis_options.yaml index b43a755b4f..1b7d3ffeb0 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -140,7 +140,7 @@ linter: - prefer_foreach # - prefer_function_declarations_over_variables # not yet tested - prefer_generic_function_type_aliases - # - prefer_if_elements_to_conditional_expressions # not yet tested + - prefer_if_elements_to_conditional_expressions - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds diff --git a/dev/bots/analyze-sample-code.dart b/dev/bots/analyze-sample-code.dart index a04d220d4d..ac3219895b 100644 --- a/dev/bots/analyze-sample-code.dart +++ b/dev/bots/analyze-sample-code.dart @@ -208,23 +208,20 @@ class SampleChecker { /// Computes the headers needed for each sample file. List get headers { - if (_headers == null) { - final List buffer = []; - buffer.add('// generated code'); - buffer.add('import \'dart:async\';'); - buffer.add('import \'dart:convert\';'); - buffer.add('import \'dart:math\' as math;'); - buffer.add('import \'dart:typed_data\';'); - buffer.add('import \'dart:ui\' as ui;'); - buffer.add('import \'package:flutter_test/flutter_test.dart\';'); - for (File file in _listDartFiles(Directory(_defaultFlutterPackage))) { - buffer.add(''); - buffer.add('// ${file.path}'); - buffer.add('import \'package:flutter/${path.basename(file.path)}\';'); - } - _headers = buffer.map((String code) => Line(code)).toList(); - } - return _headers; + return _headers ??= [ + '// generated code', + "import 'dart:async';", + "import 'dart:convert';", + "import 'dart:math' as math;", + "import 'dart:typed_data';", + "import 'dart:ui' as ui;", + "import 'package:flutter_test/flutter_test.dart';", + for (File file in _listDartFiles(Directory(_defaultFlutterPackage))) ...[ + '', + '// ${file.path}', + "import 'package:flutter/${path.basename(file.path)}';", + ], + ].map((String code) => Line(code)).toList(); } List _headers; diff --git a/dev/bots/analyze.dart b/dev/bots/analyze.dart index bc742ee74d..3c5f2838df 100644 --- a/dev/bots/analyze.dart +++ b/dev/bots/analyze.dart @@ -177,7 +177,7 @@ Future _checkForTrailingSpaces() async { '*.dart', '*.cxx', '*.cpp', '*.cc', '*.c', '*.C', '*.h', '*.java', '*.mm', '*.m', '*.yml', ]; final EvalResult changedFilesResult = await _evalCommand( - 'git', ['diff', '-U0', '--no-color', '--name-only', commitRange, '--'] + fileTypes, + 'git', ['diff', '-U0', '--no-color', '--name-only', commitRange, '--', ...fileTypes], workingDirectory: flutterRoot, ); if (changedFilesResult.stdout == null || changedFilesResult.stdout.trim().isEmpty) { @@ -195,7 +195,8 @@ Future _checkForTrailingSpaces() async { '--line-number', '--extended-regexp', r'[[:blank:]]$', - ] + changedFiles, + ...changedFiles, + ], workingDirectory: flutterRoot, failureMessage: '${red}Whitespace detected at the end of source code lines.$reset\nPlease remove:', expectNonZeroExit: true, // Just means a non-zero exit code is expected. diff --git a/dev/bots/prepare_package.dart b/dev/bots/prepare_package.dart index 2f42a43e25..9dc33ca387 100644 --- a/dev/bots/prepare_package.dart +++ b/dev/bots/prepare_package.dart @@ -527,20 +527,16 @@ class ArchivePublisher { // Search for any entries with the same hash and channel and remove them. final List releases = jsonData['releases']; - final List> prunedReleases = >[]; - for (Map entry in releases) { - if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel']) { - prunedReleases.add(entry); - } - } - - prunedReleases.add(newEntry); - prunedReleases.sort((Map a, Map b) { + jsonData['releases'] = >[ + for (Map entry in releases) + if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel']) + entry, + newEntry, + ]..sort((Map a, Map b) { final DateTime aDate = DateTime.parse(a['release_date']); final DateTime bDate = DateTime.parse(b['release_date']); return bDate.compareTo(aDate); }); - jsonData['releases'] = prunedReleases; return jsonData; } diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 823956f94c..7dcfaef6bc 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -184,17 +184,16 @@ Future _getBigqueryApi() async { // Partition tool tests into two groups, see explanation on `_runToolCoverage`. List> _partitionToolTests() { - final List pending = []; final String toolTestDir = path.join(toolRoot, 'test'); - for (FileSystemEntity entity in Directory(toolTestDir).listSync(recursive: true)) { - if (entity is File && entity.path.endsWith('_test.dart')) { - final String relativePath = path.relative(entity.path, from: toolRoot); - pending.add(relativePath); - } - } + final List pending = [ + for (FileSystemEntity entity in Directory(toolTestDir).listSync(recursive: true)) + if (entity is File && entity.path.endsWith('_test.dart')) + path.relative(entity.path, from: toolRoot), + ]; + // Shuffle the tests to avoid giving an expensive test directory like // integration to a single run of tests. - pending..shuffle(); + pending.shuffle(); final int aboutHalf = pending.length ~/ 2; final List groupA = pending.take(aboutHalf).toList(); final List groupB = pending.skip(aboutHalf).toList(); @@ -512,19 +511,20 @@ Future _buildRunnerTest( bool enableFlutterToolAsserts = false, bq.TabledataResourceApi tableData, }) async { - final List args = ['run', 'build_runner', 'test', '--', useFlutterTestFormatter ? '-rjson' : '-rcompact', '-j1']; - if (!hasColor) { - args.add('--no-color'); - } - if (testPath != null) { - args.add(testPath); - } + final List args = [ + 'run', + 'build_runner', + 'test', + '--', + if (useFlutterTestFormatter) '-rjson' else '-rcompact', + '-j1', + if (!hasColor) '--no-color', + if (testPath != null) testPath, + ]; final Map pubEnvironment = { 'FLUTTER_ROOT': flutterRoot, + if (Directory(pubCache).existsSync()) 'PUB_CACHE': pubCache, }; - if (Directory(pubCache).existsSync()) { - pubEnvironment['PUB_CACHE'] = pubCache; - } if (enableFlutterToolAsserts) { // If an existing env variable exists append to it, but only if // it doesn't appear to already include enable-asserts. @@ -574,15 +574,17 @@ Future _pubRunTest( bool enableFlutterToolAsserts = false, bq.TabledataResourceApi tableData, }) async { - final List args = ['run', 'test', useFlutterTestFormatter ? '-rjson' : '-rcompact', '-j1']; - if (!hasColor) - args.add('--no-color'); - if (testPath != null) - args.add(testPath); - final Map pubEnvironment = {}; - if (Directory(pubCache).existsSync()) { - pubEnvironment['PUB_CACHE'] = pubCache; - } + final List args = [ + 'run', + 'test', + if (useFlutterTestFormatter) '-rjson' else '-rcompact', + '-j1', + if (!hasColor) '--no-color', + if (testPath != null) testPath, + ]; + final Map pubEnvironment = { + if (Directory(pubCache).existsSync()) 'PUB_CACHE': pubCache, + }; if (enableFlutterToolAsserts) { // If an existing env variable exists append to it, but only if // it doesn't appear to already include enable-asserts. diff --git a/dev/devicelab/bin/tasks/named_isolates_test.dart b/dev/devicelab/bin/tasks/named_isolates_test.dart index 9fb6796271..d293210a53 100644 --- a/dev/devicelab/bin/tasks/named_isolates_test.dart +++ b/dev/devicelab/bin/tasks/named_isolates_test.dart @@ -71,7 +71,7 @@ Future _run({@required Device device, @required List command, @ await inDirectory(appDir, () async { runner = await startProcess( path.join(flutterDirectory.path, 'bin', 'flutter'), - ['--suppress-analytics', '-d', device.deviceId] + command, + ['--suppress-analytics', '-d', device.deviceId, ...command], isBot: false, // we just want to test the output, not have any debugging info ); final StreamController stdout = StreamController.broadcast(); diff --git a/dev/devicelab/lib/framework/runner.dart b/dev/devicelab/lib/framework/runner.dart index 642afd476e..9fae747266 100644 --- a/dev/devicelab/lib/framework/runner.dart +++ b/dev/devicelab/lib/framework/runner.dart @@ -82,12 +82,11 @@ Future> runTask( } Future _connectToRunnerIsolate(Uri vmServiceUri) async { - final List pathSegments = []; - if (vmServiceUri.pathSegments.isNotEmpty) { + final List pathSegments = [ // Add authentication code. - pathSegments.add(vmServiceUri.pathSegments[0]); - } - pathSegments.add('ws'); + if (vmServiceUri.pathSegments.isNotEmpty) vmServiceUri.pathSegments[0], + 'ws', + ]; final String url = vmServiceUri.replace(scheme: 'ws', pathSegments: pathSegments).toString(); final Stopwatch stopwatch = Stopwatch()..start(); diff --git a/dev/devicelab/lib/tasks/analysis.dart b/dev/devicelab/lib/tasks/analysis.dart index a938d49179..eb3c24043e 100644 --- a/dev/devicelab/lib/tasks/analysis.dart +++ b/dev/devicelab/lib/tasks/analysis.dart @@ -65,12 +65,10 @@ abstract class _Benchmark { Directory get directory; - List get options { - final List result = [ '--benchmark' ]; - if (watch) - result.add('--watch'); - return result; - } + List get options => [ + '--benchmark', + if (watch) '--watch', + ]; Future execute(int iteration, int targetIterations) async { section('Analyze $title ${watch ? 'with watcher' : ''} - ${iteration + 1} / $targetIterations'); diff --git a/dev/devicelab/lib/tasks/save_catalog_screenshots.dart b/dev/devicelab/lib/tasks/save_catalog_screenshots.dart index 89ee043576..12c4fde118 100644 --- a/dev/devicelab/lib/tasks/save_catalog_screenshots.dart +++ b/dev/devicelab/lib/tasks/save_catalog_screenshots.dart @@ -119,13 +119,11 @@ Future saveCatalogScreenshots({ String token, // Cloud storage authorization token. String prefix, // Prefix for all file names. }) async { - final List screenshots = []; - for (FileSystemEntity entity in directory.listSync()) { - if (entity is File && entity.path.endsWith('.png')) { - final File file = entity; - screenshots.add(file.path); - } - } + final List screenshots = [ + for (FileSystemEntity entity in directory.listSync()) + if (entity is File && entity.path.endsWith('.png')) + entity.path, + ]; final List largeNames = []; // Cloud storage names for the full res screenshots. final List smallNames = []; // Likewise for the scaled down screenshots. diff --git a/dev/integration_tests/android_semantics_testing/lib/src/common.dart b/dev/integration_tests/android_semantics_testing/lib/src/common.dart index 43b316d8f0..c53eb76d76 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/common.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/common.dart @@ -144,13 +144,9 @@ class AndroidSemanticsNode { } /// Gets a list of [AndroidSemanticsActions] which are defined for the node. - List getActions() { - final List result = []; - for (int id in _values['actions']) { - result.add(AndroidSemanticsAction.deserialize(id)); - } - return result; - } + List getActions() => [ + for (int id in _values['actions']) AndroidSemanticsAction.deserialize(id), + ]; @override String toString() { diff --git a/dev/integration_tests/codegen/lib/main.dart b/dev/integration_tests/codegen/lib/main.dart index 556c37d36c..7ee8003a29 100644 --- a/dev/integration_tests/codegen/lib/main.dart +++ b/dev/integration_tests/codegen/lib/main.dart @@ -34,7 +34,7 @@ class _ExampleWidgetState extends State { }); }, ), - _pressed ? GeneratedWidget() : const SizedBox(), + if (_pressed) GeneratedWidget() else const SizedBox(), ], ), ), diff --git a/dev/integration_tests/codegen/pubspec.yaml b/dev/integration_tests/codegen/pubspec.yaml index 13e0362536..e00f9cc373 100644 --- a/dev/integration_tests/codegen/pubspec.yaml +++ b/dev/integration_tests/codegen/pubspec.yaml @@ -3,7 +3,7 @@ description: A test of Flutter integrating code generation. environment: # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. - sdk: ">=2.0.0-dev.68.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: flutter: diff --git a/dev/manual_tests/lib/overlay_geometry.dart b/dev/manual_tests/lib/overlay_geometry.dart index 3f1cb370b5..8a2bd78e5f 100644 --- a/dev/manual_tests/lib/overlay_geometry.dart +++ b/dev/manual_tests/lib/overlay_geometry.dart @@ -179,26 +179,27 @@ class OverlayGeometryAppState extends State { @override Widget build(BuildContext context) { - final List layers = [ - Scaffold( - appBar: AppBar(title: const Text('Tap a Card')), - body: Container( - padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0), - child: NotificationListener( - onNotification: handleScrollNotification, - child: ListView.custom( - childrenDelegate: CardBuilder( - cardModels: cardModels, - onTapUp: handleTapUp, + return Stack( + children: [ + Scaffold( + appBar: AppBar(title: const Text('Tap a Card')), + body: Container( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0), + child: NotificationListener( + onNotification: handleScrollNotification, + child: ListView.custom( + childrenDelegate: CardBuilder( + cardModels: cardModels, + onTapUp: handleTapUp, + ), ), ), ), ), - ), - ]; - for (MarkerType type in markers.keys) - layers.add(Marker(type: type, position: markers[type])); - return Stack(children: layers); + for (MarkerType type in markers.keys) + Marker(type: type, position: markers[type]), + ], + ); } } diff --git a/dev/manual_tests/lib/text.dart b/dev/manual_tests/lib/text.dart index cfb8461ccf..023e2260b2 100644 --- a/dev/manual_tests/lib/text.dart +++ b/dev/manual_tests/lib/text.dart @@ -556,9 +556,6 @@ class _UnderlinesState extends State { @override Widget build(BuildContext context) { - final List lines = [_wrap(null)]; - for (TextDecorationStyle style in TextDecorationStyle.values) - lines.add(_wrap(style)); final Size size = MediaQuery.of(context).size; return Container( color: Colors.black, @@ -572,7 +569,10 @@ class _UnderlinesState extends State { vertical: size.height * 0.1, ), child: ListBody( - children: lines, + children: [ + _wrap(null), + for (TextDecorationStyle style in TextDecorationStyle.values) _wrap(style), + ], ), ), ), @@ -647,9 +647,6 @@ class _FallbackState extends State { @override Widget build(BuildContext context) { - final List lines = []; - for (String font in androidFonts) - lines.add(Text(multiScript, style: style.copyWith(fontFamily: font, fontSize: math.exp(_fontSize)))); final Size size = MediaQuery.of(context).size; return Container( color: Colors.black, @@ -666,7 +663,16 @@ class _FallbackState extends State { ), child: IntrinsicWidth( child: ListBody( - children: lines, + children: [ + for (String font in androidFonts) + Text( + multiScript, + style: style.copyWith( + fontFamily: font, + fontSize: math.exp(_fontSize), + ), + ), + ], ), ), ), diff --git a/dev/manual_tests/pubspec.yaml b/dev/manual_tests/pubspec.yaml index 71cec9d950..e6bb028688 100644 --- a/dev/manual_tests/pubspec.yaml +++ b/dev/manual_tests/pubspec.yaml @@ -2,7 +2,7 @@ name: manual_tests 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: flutter: diff --git a/dev/tools/dartdoc.dart b/dev/tools/dartdoc.dart index 729a4f0400..b846b6cd34 100644 --- a/dev/tools/dartdoc.dart +++ b/dev/tools/dartdoc.dart @@ -108,11 +108,12 @@ Future main(List arguments) async { createSearchMetadata('$kDocsRoot/lib/opensearch.xml', '$kDocsRoot/doc/opensearch.xml'); cleanOutSnippets(); - final List dartdocBaseArgs = ['global', 'run']; - if (args['checked']) { - dartdocBaseArgs.add('-c'); - } - dartdocBaseArgs.add('dartdoc'); + final List dartdocBaseArgs = [ + 'global', + 'run', + if (args['checked']) '-c', + 'dartdoc', + ]; // Verify which version of dartdoc we're using. final ProcessResult result = Process.runSync( @@ -123,24 +124,17 @@ Future main(List arguments) async { ); print('\n${result.stdout}flutter version: $version\n'); - dartdocBaseArgs.add('--allow-tools'); - - if (args['json']) { - dartdocBaseArgs.add('--json'); - } - if (args['validate-links']) { - dartdocBaseArgs.add('--validate-links'); - } else { - dartdocBaseArgs.add('--no-validate-links'); - } - dartdocBaseArgs.addAll(['--link-to-source-excludes', '../../bin/cache', - '--link-to-source-root', '../..', - '--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/master/%f%#L%l%']); // Generate the documentation. // We don't need to exclude flutter_tools in this list because it's not in the // recursive dependencies of the package defined at dev/docs/pubspec.yaml final List dartdocArgs = [ ...dartdocBaseArgs, + '--allow-tools', + if (args['json']) '--json', + if (args['validate-links']) '--validate-links' else '--no-validate-links', + '--link-to-source-excludes', '../../bin/cache', + '--link-to-source-root', '../..', + '--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/master/%f%#L%l%', '--inject-html', '--header', 'styles.html', '--header', 'analytics.html', diff --git a/dev/tools/gen_keycodes/lib/key_data.dart b/dev/tools/gen_keycodes/lib/key_data.dart index 71492ca3c5..95304a1aca 100644 --- a/dev/tools/gen_keycodes/lib/key_data.dart +++ b/dev/tools/gen_keycodes/lib/key_data.dart @@ -52,10 +52,9 @@ class KeyData { /// Parses the given JSON data and populates the data structure from it. KeyData.fromJson(Map contentMap) { - data = []; - for (String key in contentMap.keys) { - data.add(Key.fromJsonMapEntry(key, contentMap[key])); - } + data = [ + for (String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key]), + ]; } /// Converts the data structure into a JSON structure that can be parsed by diff --git a/dev/tools/gen_keycodes/pubspec.yaml b/dev/tools/gen_keycodes/pubspec.yaml index a0c56f34f9..5ecc9589b4 100644 --- a/dev/tools/gen_keycodes/pubspec.yaml +++ b/dev/tools/gen_keycodes/pubspec.yaml @@ -3,7 +3,7 @@ description: Generates keycode source files from various resources. environment: # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. - sdk: ">=2.0.0-dev.68.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: args: 1.5.2 diff --git a/dev/tools/vitool/bin/main.dart b/dev/tools/vitool/bin/main.dart index b7b55bebda..d2f0dc8924 100644 --- a/dev/tools/vitool/bin/main.dart +++ b/dev/tools/vitool/bin/main.dart @@ -64,11 +64,9 @@ void main(List args) { return; } - final List frames = []; - for (String filePath in argResults.rest) { - final FrameData data = interpretSvg(filePath); - frames.add(data); - } + final List frames = [ + for (String filePath in argResults.rest) interpretSvg(filePath), + ]; final StringBuffer generatedSb = StringBuffer(); diff --git a/dev/tools/vitool/pubspec.yaml b/dev/tools/vitool/pubspec.yaml index 457733b1a5..5b1ce42b7d 100644 --- a/dev/tools/vitool/pubspec.yaml +++ b/dev/tools/vitool/pubspec.yaml @@ -6,7 +6,7 @@ author: Flutter Authors environment: # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. - sdk: ">=2.0.0-dev.68.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: args: 1.5.2 diff --git a/examples/flutter_gallery/lib/demo/calculator/logic.dart b/examples/flutter_gallery/lib/demo/calculator/logic.dart index 121b1ae99b..43ddf65989 100644 --- a/examples/flutter_gallery/lib/demo/calculator/logic.dart +++ b/examples/flutter_gallery/lib/demo/calculator/logic.dart @@ -302,8 +302,9 @@ class CalcExpression { assert(false); } } - final List outList = []; - outList.add(ResultToken(currentTermValue)); + final List outList = [ + ResultToken(currentTermValue), + ]; return CalcExpression(outList, ExpressionState.Result); } diff --git a/examples/flutter_gallery/lib/demo/contacts_demo.dart b/examples/flutter_gallery/lib/demo/contacts_demo.dart index 3dc5e5cd65..76753c4ae4 100644 --- a/examples/flutter_gallery/lib/demo/contacts_demo.dart +++ b/examples/flutter_gallery/lib/demo/contacts_demo.dart @@ -54,33 +54,31 @@ class _ContactItem extends StatelessWidget { @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - final List columnChildren = lines.sublist(0, lines.length - 1).map((String line) => Text(line)).toList(); - columnChildren.add(Text(lines.last, style: themeData.textTheme.caption)); - - final List rowChildren = [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: columnChildren, - ), - ), - ]; - if (icon != null) { - rowChildren.add(SizedBox( - width: 72.0, - child: IconButton( - icon: Icon(icon), - color: themeData.primaryColor, - onPressed: onPressed, - ), - )); - } return MergeSemantics( child: Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: rowChildren, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ...lines.sublist(0, lines.length - 1).map((String line) => Text(line)), + Text(lines.last, style: themeData.textTheme.caption), + ], + ), + ), + if (icon != null) + SizedBox( + width: 72.0, + child: IconButton( + icon: Icon(icon), + color: themeData.primaryColor, + onPressed: onPressed, + ), + ), + ], ), ), ); diff --git a/examples/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart b/examples/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart index ce0d749fd6..afe71706e8 100644 --- a/examples/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart +++ b/examples/flutter_gallery/lib/demo/cupertino/cupertino_alert_demo.dart @@ -53,153 +53,148 @@ class _CupertinoAlertDemoState extends State { style: CupertinoTheme.of(context).textTheme.textStyle, child: Builder( builder: (BuildContext context) { - final List stackChildren = [ - CupertinoScrollbar( - child: ListView( - // Add more padding to the normal safe area. - padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0) - + MediaQuery.of(context).padding, - children: [ - CupertinoButton.filled( - child: const Text('Alert'), - onPressed: () { - showDemoDialog( - context: context, - child: CupertinoAlertDialog( - title: const Text('Discard draft?'), - actions: [ - CupertinoDialogAction( - child: const Text('Discard'), - isDestructiveAction: true, - onPressed: () { - Navigator.pop(context, 'Discard'); - }, - ), - CupertinoDialogAction( + return Stack( + alignment: Alignment.center, + children: [ + CupertinoScrollbar( + child: ListView( + // Add more padding to the normal safe area. + padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0) + + MediaQuery.of(context).padding, + children: [ + CupertinoButton.filled( + child: const Text('Alert'), + onPressed: () { + showDemoDialog( + context: context, + child: CupertinoAlertDialog( + title: const Text('Discard draft?'), + actions: [ + CupertinoDialogAction( + child: const Text('Discard'), + isDestructiveAction: true, + onPressed: () { + Navigator.pop(context, 'Discard'); + }, + ), + CupertinoDialogAction( + child: const Text('Cancel'), + isDefaultAction: true, + onPressed: () { + Navigator.pop(context, 'Cancel'); + }, + ), + ], + ), + ); + }, + ), + const Padding(padding: EdgeInsets.all(8.0)), + CupertinoButton.filled( + child: const Text('Alert with Title'), + padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), + onPressed: () { + showDemoDialog( + context: context, + child: CupertinoAlertDialog( + title: const Text('Allow "Maps" to access your location while you are using the app?'), + content: const Text('Your current location will be displayed on the map and used ' + 'for directions, nearby search results, and estimated travel times.'), + actions: [ + CupertinoDialogAction( + child: const Text('Don\'t Allow'), + onPressed: () { + Navigator.pop(context, 'Disallow'); + }, + ), + CupertinoDialogAction( + child: const Text('Allow'), + onPressed: () { + Navigator.pop(context, 'Allow'); + }, + ), + ], + ), + ); + }, + ), + const Padding(padding: EdgeInsets.all(8.0)), + CupertinoButton.filled( + child: const Text('Alert with Buttons'), + padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), + onPressed: () { + showDemoDialog( + context: context, + child: const CupertinoDessertDialog( + title: Text('Select Favorite Dessert'), + content: Text('Please select your favorite type of dessert from the ' + 'list below. Your selection will be used to customize the suggested ' + 'list of eateries in your area.'), + ), + ); + }, + ), + const Padding(padding: EdgeInsets.all(8.0)), + CupertinoButton.filled( + child: const Text('Alert Buttons Only'), + padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), + onPressed: () { + showDemoDialog( + context: context, + child: const CupertinoDessertDialog(), + ); + }, + ), + const Padding(padding: EdgeInsets.all(8.0)), + CupertinoButton.filled( + child: const Text('Action Sheet'), + padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), + onPressed: () { + showDemoActionSheet( + context: context, + child: CupertinoActionSheet( + title: const Text('Favorite Dessert'), + message: const Text('Please select the best dessert from the options below.'), + actions: [ + CupertinoActionSheetAction( + child: const Text('Profiteroles'), + onPressed: () { + Navigator.pop(context, 'Profiteroles'); + }, + ), + CupertinoActionSheetAction( + child: const Text('Cannolis'), + onPressed: () { + Navigator.pop(context, 'Cannolis'); + }, + ), + CupertinoActionSheetAction( + child: const Text('Trifle'), + onPressed: () { + Navigator.pop(context, 'Trifle'); + }, + ), + ], + cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), isDefaultAction: true, onPressed: () { Navigator.pop(context, 'Cancel'); }, ), - ], - ), - ); - }, - ), - const Padding(padding: EdgeInsets.all(8.0)), - CupertinoButton.filled( - child: const Text('Alert with Title'), - padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), - onPressed: () { - showDemoDialog( - context: context, - child: CupertinoAlertDialog( - title: const Text('Allow "Maps" to access your location while you are using the app?'), - content: const Text('Your current location will be displayed on the map and used ' - 'for directions, nearby search results, and estimated travel times.'), - actions: [ - CupertinoDialogAction( - child: const Text('Don\'t Allow'), - onPressed: () { - Navigator.pop(context, 'Disallow'); - }, - ), - CupertinoDialogAction( - child: const Text('Allow'), - onPressed: () { - Navigator.pop(context, 'Allow'); - }, - ), - ], - ), - ); - }, - ), - const Padding(padding: EdgeInsets.all(8.0)), - CupertinoButton.filled( - child: const Text('Alert with Buttons'), - padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), - onPressed: () { - showDemoDialog( - context: context, - child: const CupertinoDessertDialog( - title: Text('Select Favorite Dessert'), - content: Text('Please select your favorite type of dessert from the ' - 'list below. Your selection will be used to customize the suggested ' - 'list of eateries in your area.'), - ), - ); - }, - ), - const Padding(padding: EdgeInsets.all(8.0)), - CupertinoButton.filled( - child: const Text('Alert Buttons Only'), - padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), - onPressed: () { - showDemoDialog( - context: context, - child: const CupertinoDessertDialog(), - ); - }, - ), - const Padding(padding: EdgeInsets.all(8.0)), - CupertinoButton.filled( - child: const Text('Action Sheet'), - padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0), - onPressed: () { - showDemoActionSheet( - context: context, - child: CupertinoActionSheet( - title: const Text('Favorite Dessert'), - message: const Text('Please select the best dessert from the options below.'), - actions: [ - CupertinoActionSheetAction( - child: const Text('Profiteroles'), - onPressed: () { - Navigator.pop(context, 'Profiteroles'); - }, - ), - CupertinoActionSheetAction( - child: const Text('Cannolis'), - onPressed: () { - Navigator.pop(context, 'Cannolis'); - }, - ), - CupertinoActionSheetAction( - child: const Text('Trifle'), - onPressed: () { - Navigator.pop(context, 'Trifle'); - }, - ), - ], - cancelButton: CupertinoActionSheetAction( - child: const Text('Cancel'), - isDefaultAction: true, - onPressed: () { - Navigator.pop(context, 'Cancel'); - }, ), - ), - ); - }, - ), - ], + ); + }, + ), + ], + ), ), - ), - ]; - - if (lastSelectedValue != null) { - stackChildren.add( - Positioned( - bottom: 32.0, - child: Text('You selected: $lastSelectedValue'), - ), - ); - } - return Stack( - alignment: Alignment.center, - children: stackChildren, + if (lastSelectedValue != null) + Positioned( + bottom: 32.0, + child: Text('You selected: $lastSelectedValue'), + ), + ], ); }, ), diff --git a/examples/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart b/examples/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart index 5f842a0f78..5730c43ad3 100644 --- a/examples/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart +++ b/examples/flutter_gallery/lib/demo/cupertino/cupertino_navigation_demo.dart @@ -647,25 +647,21 @@ class Tab2ConversationRow extends StatelessWidget { @override Widget build(BuildContext context) { - final List children = []; - if (avatar != null) - children.add(avatar); - final bool isSelf = avatar == null; - children.add( - Tab2ConversationBubble( - text: text, - color: isSelf - ? Tab2ConversationBubbleColor.blue - : Tab2ConversationBubbleColor.gray, - ), - ); return SafeArea( child: Row( mainAxisAlignment: isSelf ? MainAxisAlignment.end : MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, crossAxisAlignment: isSelf ? CrossAxisAlignment.center : CrossAxisAlignment.end, - children: children, + children: [ + if (avatar != null) avatar, + Tab2ConversationBubble( + text: text, + color: isSelf + ? Tab2ConversationBubbleColor.blue + : Tab2ConversationBubbleColor.gray, + ), + ], ), ); } diff --git a/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart b/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart index 6efefa3cc8..b94a402c6c 100644 --- a/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart @@ -164,10 +164,9 @@ class _BottomNavigationDemoState extends State } Widget _buildTransitionsStack() { - final List transitions = []; - - for (NavigationIconView view in _navigationViews) - transitions.add(view.transition(_type, context)); + final List transitions = [ + for (NavigationIconView view in _navigationViews) view.transition(_type, context), + ]; // We want to have the newly animating (fading in) views on top. transitions.sort((FadeTransition a, FadeTransition b) { diff --git a/examples/flutter_gallery/lib/demo/material/cards_demo.dart b/examples/flutter_gallery/lib/demo/material/cards_demo.dart index 39c110695a..fe7e29971b 100644 --- a/examples/flutter_gallery/lib/demo/material/cards_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/cards_demo.dart @@ -262,89 +262,83 @@ class TravelDestinationContent extends StatelessWidget { final TextStyle titleStyle = theme.textTheme.headline.copyWith(color: Colors.white); final TextStyle descriptionStyle = theme.textTheme.subhead; - final List children = [ - // Photo and title. - SizedBox( - height: 184.0, - child: Stack( - children: [ - Positioned.fill( - // In order to have the ink splash appear above the image, you - // must use Ink.image. This allows the image to be painted as part - // of the Material and display ink effects above it. Using a - // standard Image will obscure the ink splash. - child: Ink.image( - image: AssetImage(destination.assetName, package: destination.assetPackage), - fit: BoxFit.cover, - child: Container(), - ), - ), - Positioned( - bottom: 16.0, - left: 16.0, - right: 16.0, - child: FittedBox( - fit: BoxFit.scaleDown, - alignment: Alignment.centerLeft, - child: Text( - destination.title, - style: titleStyle, - ), - ), - ), - ], - ), - ), - // Description and share/explore buttons. - Padding( - padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0.0), - child: DefaultTextStyle( - softWrap: false, - overflow: TextOverflow.ellipsis, - style: descriptionStyle, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Photo and title. + SizedBox( + height: 184.0, + child: Stack( children: [ - // three line description - Padding( - padding: const EdgeInsets.only(bottom: 8.0), - child: Text( - destination.description, - style: descriptionStyle.copyWith(color: Colors.black54), + Positioned.fill( + // In order to have the ink splash appear above the image, you + // must use Ink.image. This allows the image to be painted as part + // of the Material and display ink effects above it. Using a + // standard Image will obscure the ink splash. + child: Ink.image( + image: AssetImage(destination.assetName, package: destination.assetPackage), + fit: BoxFit.cover, + child: Container(), + ), + ), + Positioned( + bottom: 16.0, + left: 16.0, + right: 16.0, + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + destination.title, + style: titleStyle, + ), ), ), - Text(destination.city), - Text(destination.location), ], ), ), - ), - ]; - - if (destination.type == CardDemoType.standard) { - children.add( - // share, explore buttons - ButtonBar( - alignment: MainAxisAlignment.start, - children: [ - FlatButton( - child: Text('SHARE', semanticsLabel: 'Share ${destination.title}'), - textColor: Colors.amber.shade500, - onPressed: () { print('pressed'); }, + // Description and share/explore buttons. + Padding( + padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0.0), + child: DefaultTextStyle( + softWrap: false, + overflow: TextOverflow.ellipsis, + style: descriptionStyle, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // three line description + Padding( + padding: const EdgeInsets.only(bottom: 8.0), + child: Text( + destination.description, + style: descriptionStyle.copyWith(color: Colors.black54), + ), + ), + Text(destination.city), + Text(destination.location), + ], ), - FlatButton( - child: Text('EXPLORE', semanticsLabel: 'Explore ${destination.title}'), - textColor: Colors.amber.shade500, - onPressed: () { print('pressed'); }, - ), - ], + ), ), - ); - } - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: children, + if (destination.type == CardDemoType.standard) + // share, explore buttons + ButtonBar( + alignment: MainAxisAlignment.start, + children: [ + FlatButton( + child: Text('SHARE', semanticsLabel: 'Share ${destination.title}'), + textColor: Colors.amber.shade500, + onPressed: () { print('pressed'); }, + ), + FlatButton( + child: Text('EXPLORE', semanticsLabel: 'Explore ${destination.title}'), + textColor: Colors.amber.shade500, + onPressed: () { print('pressed'); }, + ), + ], + ), + ], ); } } diff --git a/examples/flutter_gallery/lib/demo/material/chip_demo.dart b/examples/flutter_gallery/lib/demo/material/chip_demo.dart index 6c464db70f..8528bd1a49 100644 --- a/examples/flutter_gallery/lib/demo/material/chip_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/chip_demo.dart @@ -83,40 +83,36 @@ class _ChipsTile extends StatelessWidget { // Wraps a list of chips into a ListTile for display as a section in the demo. @override Widget build(BuildContext context) { - final List cardChildren = [ - Container( - padding: const EdgeInsets.only(top: 16.0, bottom: 4.0), - alignment: Alignment.center, - child: Text(label, textAlign: TextAlign.start), - ), - ]; - if (children.isNotEmpty) { - cardChildren.add(Wrap( - children: children.map((Widget chip) { - return Padding( - padding: const EdgeInsets.all(2.0), - child: chip, - ); - }).toList())); - } else { - final TextStyle textStyle = Theme.of(context).textTheme.caption.copyWith(fontStyle: FontStyle.italic); - cardChildren.add( - Semantics( - container: true, - child: Container( - alignment: Alignment.center, - constraints: const BoxConstraints(minWidth: 48.0, minHeight: 48.0), - padding: const EdgeInsets.all(8.0), - child: Text('None', style: textStyle), - ), - )); - } - return Card( semanticContainer: false, child: Column( mainAxisSize: MainAxisSize.min, - children: cardChildren, + children: [ + Container( + padding: const EdgeInsets.only(top: 16.0, bottom: 4.0), + alignment: Alignment.center, + child: Text(label, textAlign: TextAlign.start), + ), + if (children.isNotEmpty) + Wrap( + children: children.map((Widget chip) { + return Padding( + padding: const EdgeInsets.all(2.0), + child: chip, + ); + }).toList(), + ) + else + Semantics( + container: true, + child: Container( + alignment: Alignment.center, + constraints: const BoxConstraints(minWidth: 48.0, minHeight: 48.0), + padding: const EdgeInsets.all(8.0), + child: Text('None', style: Theme.of(context).textTheme.caption.copyWith(fontStyle: FontStyle.italic)), + ), + ), + ], ), ); } diff --git a/examples/flutter_gallery/lib/demo/material/search_demo.dart b/examples/flutter_gallery/lib/demo/material/search_demo.dart index d497bdd7d7..bf33573637 100644 --- a/examples/flutter_gallery/lib/demo/material/search_demo.dart +++ b/examples/flutter_gallery/lib/demo/material/search_demo.dart @@ -204,22 +204,23 @@ class _SearchDemoSearchDelegate extends SearchDelegate { @override List buildActions(BuildContext context) { return [ - query.isEmpty - ? IconButton( - tooltip: 'Voice Search', - icon: const Icon(Icons.mic), - onPressed: () { - query = 'TODO: implement voice input'; - }, - ) - : IconButton( - tooltip: 'Clear', - icon: const Icon(Icons.clear), - onPressed: () { - query = ''; - showSuggestions(context); - }, - ), + if (query.isEmpty) + IconButton( + tooltip: 'Voice Search', + icon: const Icon(Icons.mic), + onPressed: () { + query = 'TODO: implement voice input'; + }, + ) + else + IconButton( + tooltip: 'Clear', + icon: const Icon(Icons.clear), + onPressed: () { + query = ''; + showSuggestions(context); + }, + ), ]; } } diff --git a/examples/flutter_gallery/lib/demo/typography_demo.dart b/examples/flutter_gallery/lib/demo/typography_demo.dart index 18c3e3a966..b974be5567 100644 --- a/examples/flutter_gallery/lib/demo/typography_demo.dart +++ b/examples/flutter_gallery/lib/demo/typography_demo.dart @@ -48,6 +48,8 @@ class TypographyDemo extends StatelessWidget { Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final List styleItems = [ + if (MediaQuery.of(context).size.width > 500.0) + TextStyleItem(name: 'Display 4', style: textTheme.display4, text: 'Light 112sp'), TextStyleItem(name: 'Display 3', style: textTheme.display3, text: 'Regular 56sp'), TextStyleItem(name: 'Display 2', style: textTheme.display2, text: 'Regular 45sp'), TextStyleItem(name: 'Display 1', style: textTheme.display1, text: 'Regular 34sp'), @@ -60,14 +62,6 @@ class TypographyDemo extends StatelessWidget { TextStyleItem(name: 'Button', style: textTheme.button, text: 'MEDIUM (ALL CAPS) 14sp'), ]; - if (MediaQuery.of(context).size.width > 500.0) { - styleItems.insert(0, TextStyleItem( - name: 'Display 4', - style: textTheme.display4, - text: 'Light 112sp', - )); - } - return Scaffold( appBar: AppBar(title: const Text('Typography')), body: SafeArea( diff --git a/examples/flutter_gallery/lib/gallery/backdrop.dart b/examples/flutter_gallery/lib/gallery/backdrop.dart index 974e6afee1..5ad7ff0e28 100644 --- a/examples/flutter_gallery/lib/gallery/backdrop.dart +++ b/examples/flutter_gallery/lib/gallery/backdrop.dart @@ -138,36 +138,31 @@ class _BackAppBar extends StatelessWidget { @override Widget build(BuildContext context) { - final List children = [ - Container( - alignment: Alignment.center, - width: 56.0, - child: leading, - ), - Expanded( - child: title, - ), - ]; - - if (trailing != null) { - children.add( - Container( - alignment: Alignment.center, - width: 56.0, - child: trailing, - ), - ); - } - final ThemeData theme = Theme.of(context); - return IconTheme.merge( data: theme.primaryIconTheme, child: DefaultTextStyle( style: theme.primaryTextTheme.title, child: SizedBox( height: _kBackAppBarHeight, - child: Row(children: children), + child: Row( + children: [ + Container( + alignment: Alignment.center, + width: 56.0, + child: leading, + ), + Expanded( + child: title, + ), + if (trailing != null) + Container( + alignment: Alignment.center, + width: 56.0, + child: trailing, + ), + ], + ), ), ), ); @@ -255,95 +250,88 @@ class _BackdropState extends State with SingleTickerProviderStateMixin begin: RelativeRect.fromLTRB(0.0, constraints.biggest.height - _kFrontClosedHeight, 0.0, 0.0), end: const RelativeRect.fromLTRB(0.0, _kBackAppBarHeight, 0.0, 0.0), )); - - final List layers = [ - // Back layer - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _BackAppBar( - leading: widget.frontAction, - title: _CrossFadeTransition( - progress: _controller, - alignment: AlignmentDirectional.centerStart, - child0: Semantics(namesRoute: true, child: widget.frontTitle), - child1: Semantics(namesRoute: true, child: widget.backTitle), - ), - trailing: IconButton( - onPressed: _toggleFrontLayer, - tooltip: 'Toggle options page', - icon: AnimatedIcon( - icon: AnimatedIcons.close_menu, - progress: _controller, - ), - ), - ), - Expanded( - child: Visibility( - child: widget.backLayer, - visible: _controller.status != AnimationStatus.completed, - maintainState: true, - ), - ), - ], - ), - // Front layer - PositionedTransition( - rect: frontRelativeRect, - child: AnimatedBuilder( - animation: _controller, - builder: (BuildContext context, Widget child) { - return PhysicalShape( - elevation: 12.0, - color: Theme.of(context).canvasColor, - clipper: ShapeBorderClipper( - shape: BeveledRectangleBorder( - borderRadius: _kFrontHeadingBevelRadius.transform(_controller.value), - ), - ), - clipBehavior: Clip.antiAlias, - child: child, - ); - }, - child: _TappableWhileStatusIs( - AnimationStatus.completed, - controller: _controller, - child: FadeTransition( - opacity: _frontOpacity, - child: widget.frontLayer, - ), - ), - ), - ), - ]; - - // The front "heading" is a (typically transparent) widget that's stacked on - // top of, and at the top of, the front layer. It adds support for dragging - // the front layer up and down and for opening and closing the front layer - // with a tap. It may obscure part of the front layer's topmost child. - if (widget.frontHeading != null) { - layers.add( - PositionedTransition( - rect: frontRelativeRect, - child: ExcludeSemantics( - child: Container( - alignment: Alignment.topLeft, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: _toggleFrontLayer, - onVerticalDragUpdate: _handleDragUpdate, - onVerticalDragEnd: _handleDragEnd, - child: widget.frontHeading, - ), - ), - ), - ), - ); - } - return Stack( key: _backdropKey, - children: layers, + children: [ + // Back layer + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _BackAppBar( + leading: widget.frontAction, + title: _CrossFadeTransition( + progress: _controller, + alignment: AlignmentDirectional.centerStart, + child0: Semantics(namesRoute: true, child: widget.frontTitle), + child1: Semantics(namesRoute: true, child: widget.backTitle), + ), + trailing: IconButton( + onPressed: _toggleFrontLayer, + tooltip: 'Toggle options page', + icon: AnimatedIcon( + icon: AnimatedIcons.close_menu, + progress: _controller, + ), + ), + ), + Expanded( + child: Visibility( + child: widget.backLayer, + visible: _controller.status != AnimationStatus.completed, + maintainState: true, + ), + ), + ], + ), + // Front layer + PositionedTransition( + rect: frontRelativeRect, + child: AnimatedBuilder( + animation: _controller, + builder: (BuildContext context, Widget child) { + return PhysicalShape( + elevation: 12.0, + color: Theme.of(context).canvasColor, + clipper: ShapeBorderClipper( + shape: BeveledRectangleBorder( + borderRadius: _kFrontHeadingBevelRadius.transform(_controller.value), + ), + ), + clipBehavior: Clip.antiAlias, + child: child, + ); + }, + child: _TappableWhileStatusIs( + AnimationStatus.completed, + controller: _controller, + child: FadeTransition( + opacity: _frontOpacity, + child: widget.frontLayer, + ), + ), + ), + ), + // The front "heading" is a (typically transparent) widget that's stacked on + // top of, and at the top of, the front layer. It adds support for dragging + // the front layer up and down and for opening and closing the front layer + // with a tap. It may obscure part of the front layer's topmost child. + if (widget.frontHeading != null) + PositionedTransition( + rect: frontRelativeRect, + child: ExcludeSemantics( + child: Container( + alignment: Alignment.topLeft, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _toggleFrontLayer, + onVerticalDragUpdate: _handleDragUpdate, + onVerticalDragEnd: _handleDragEnd, + child: widget.frontHeading, + ), + ), + ), + ), + ], ); } diff --git a/examples/flutter_gallery/lib/gallery/home.dart b/examples/flutter_gallery/lib/gallery/home.dart index 38810876cd..ec785383c6 100644 --- a/examples/flutter_gallery/lib/gallery/home.dart +++ b/examples/flutter_gallery/lib/gallery/home.dart @@ -184,26 +184,6 @@ class _DemoItem extends StatelessWidget { final ThemeData theme = Theme.of(context); final bool isDark = theme.brightness == Brightness.dark; final double textScaleFactor = MediaQuery.textScaleFactorOf(context); - - final List titleChildren = [ - Text( - demo.title, - style: theme.textTheme.subhead.copyWith( - color: isDark ? Colors.white : const Color(0xFF202124), - ), - ), - ]; - if (demo.subtitle != null) { - titleChildren.add( - Text( - demo.subtitle, - style: theme.textTheme.body1.copyWith( - color: isDark ? Colors.white : const Color(0xFF60646B) - ), - ), - ); - } - return RawMaterialButton( padding: EdgeInsets.zero, splashColor: theme.primaryColor.withOpacity(0.12), @@ -229,7 +209,21 @@ class _DemoItem extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, - children: titleChildren, + children: [ + Text( + demo.title, + style: theme.textTheme.subhead.copyWith( + color: isDark ? Colors.white : const Color(0xFF202124), + ), + ), + if (demo.subtitle != null) + Text( + demo.subtitle, + style: theme.textTheme.body1.copyWith( + color: isDark ? Colors.white : const Color(0xFF60646B) + ), + ), + ], ), ), const SizedBox(width: 44.0), @@ -294,11 +288,11 @@ class _GalleryHomeState extends State with SingleTickerProviderStat GalleryDemoCategory _category; static Widget _topHomeLayout(Widget currentChild, List previousChildren) { - List children = previousChildren; - if (currentChild != null) - children = children.toList()..add(currentChild); return Stack( - children: children, + children: [ + ...previousChildren, + if (currentChild != null) currentChild, + ], alignment: Alignment.topCenter, ); } diff --git a/examples/flutter_gallery/lib/gallery/options.dart b/examples/flutter_gallery/lib/gallery/options.dart index 6076d01085..865e19f9f1 100644 --- a/examples/flutter_gallery/lib/gallery/options.dart +++ b/examples/flutter_gallery/lib/gallery/options.dart @@ -425,13 +425,10 @@ class GalleryOptionsPage extends StatelessWidget { options.showPerformanceOverlay == null) return const []; - final List items = [ + return [ const Divider(), const _Heading('Diagnostics'), - ]; - - if (options.showOffscreenLayersCheckerboard != null) { - items.add( + if (options.showOffscreenLayersCheckerboard != null) _BooleanItem( 'Highlight offscreen layers', options.showOffscreenLayersCheckerboard, @@ -439,10 +436,7 @@ class GalleryOptionsPage extends StatelessWidget { onOptionsChanged(options.copyWith(showOffscreenLayersCheckerboard: value)); }, ), - ); - } - if (options.showRasterCacheImagesCheckerboard != null) { - items.add( + if (options.showRasterCacheImagesCheckerboard != null) _BooleanItem( 'Highlight raster cache images', options.showRasterCacheImagesCheckerboard, @@ -450,10 +444,7 @@ class GalleryOptionsPage extends StatelessWidget { onOptionsChanged(options.copyWith(showRasterCacheImagesCheckerboard: value)); }, ), - ); - } - if (options.showPerformanceOverlay != null) { - items.add( + if (options.showPerformanceOverlay != null) _BooleanItem( 'Show performance overlay', options.showPerformanceOverlay, @@ -461,10 +452,7 @@ class GalleryOptionsPage extends StatelessWidget { onOptionsChanged(options.copyWith(showPerformanceOverlay: value)); }, ), - ); - } - - return items; + ]; } @override diff --git a/examples/layers/widgets/media_query.dart b/examples/layers/widgets/media_query.dart index 4ef26874e0..441ccd8bd9 100644 --- a/examples/layers/widgets/media_query.dart +++ b/examples/layers/widgets/media_query.dart @@ -85,12 +85,7 @@ class AdaptiveContainer extends StatelessWidget { } } -List _initNames() { - final List names = []; - for (int i = 0; i < 30; i++) - names.add('Item $i'); - return names; -} +List _initNames() => List.generate(30, (int i) => 'Item $i'); final List _kNames = _initNames(); diff --git a/examples/layers/widgets/styled_text.dart b/examples/layers/widgets/styled_text.dart index ffabd253b6..b63a3f9404 100644 --- a/examples/layers/widgets/styled_text.dart +++ b/examples/layers/widgets/styled_text.dart @@ -94,25 +94,20 @@ class _StyledTextDemoState extends State { @override Widget build(BuildContext context) { - final List lines = _kNameLines - .map((List nameAndText) => _toText(nameAndText[0], nameAndText[1])) - .toList(); - - final List children = []; - for (Widget line in lines) { - children.add(line); - if (line != lines.last) - children.add(SpeakerSeparator()); - } - return GestureDetector( onTap: _handleTap, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Column( - children: children, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, + children: _kNameLines + .map((List nameAndText) => _toText(nameAndText[0], nameAndText[1])) + .expand((Widget line) => [ + line, + SpeakerSeparator(), + ]) + .toList()..removeLast(), ), ), ); diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index 009fea3402..7f5a9c9566 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -174,16 +174,17 @@ class CupertinoAlertDialog extends StatelessWidget { final ScrollController actionScrollController; Widget _buildContent(BuildContext context) { - final List children = []; - - if (title != null || content != null) { - final Widget titleSection = _CupertinoAlertContentSection( - title: title, - content: content, - scrollController: scrollController, - ); - children.add(Flexible(flex: 3, child: titleSection)); - } + final List children = [ + if (title != null || content != null) + Flexible( + flex: 3, + child: _CupertinoAlertContentSection( + title: title, + content: content, + scrollController: scrollController, + ), + ), + ]; return Container( color: CupertinoDynamicColor.resolve(_kDialogColor, context), @@ -597,16 +598,10 @@ class _RenderCupertinoDialog extends RenderBox { } @override - List debugDescribeChildren() { - final List value = []; - if (contentSection != null) { - value.add(contentSection.toDiagnosticsNode(name: 'content')); - } - if (actionsSection != null) { - value.add(actionsSection.toDiagnosticsNode(name: 'actions')); - } - return value; - } + List debugDescribeChildren() => [ + if (contentSection != null) contentSection.toDiagnosticsNode(name: 'content'), + if (actionsSection != null) actionsSection.toDiagnosticsNode(name: 'actions'), + ]; @override double computeMinIntrinsicWidth(double height) { diff --git a/packages/flutter/lib/src/cupertino/page_scaffold.dart b/packages/flutter/lib/src/cupertino/page_scaffold.dart index 593eaed240..6fff14faa2 100644 --- a/packages/flutter/lib/src/cupertino/page_scaffold.dart +++ b/packages/flutter/lib/src/cupertino/page_scaffold.dart @@ -90,8 +90,6 @@ class _CupertinoPageScaffoldState extends State { @override Widget build(BuildContext context) { - final List stacked = []; - Widget paddedContent = widget.child; final MediaQueryData existingMediaQuery = MediaQuery.of(context); @@ -157,44 +155,40 @@ class _CupertinoPageScaffoldState extends State { ); } - // The main content being at the bottom is added to the stack first. - stacked.add(PrimaryScrollController( - controller: _primaryScrollController, - child: paddedContent, - )); - - if (widget.navigationBar != null) { - stacked.add(Positioned( - top: 0.0, - left: 0.0, - right: 0.0, - child: MediaQuery( - data: existingMediaQuery.copyWith(textScaleFactor: 1), - child: widget.navigationBar, - ), - )); - } - - // Add a touch handler the size of the status bar on top of all contents - // to handle scroll to top by status bar taps. - stacked.add(Positioned( - top: 0.0, - left: 0.0, - right: 0.0, - height: existingMediaQuery.padding.top, - child: GestureDetector( - excludeFromSemantics: true, - onTap: _handleStatusBarTap, - ), - ), - ); - return DecoratedBox( decoration: BoxDecoration( color: widget.backgroundColor ?? CupertinoTheme.of(context).scaffoldBackgroundColor, ), child: Stack( - children: stacked, + children: [ + // The main content being at the bottom is added to the stack first. + PrimaryScrollController( + controller: _primaryScrollController, + child: paddedContent, + ), + if (widget.navigationBar != null) + Positioned( + top: 0.0, + left: 0.0, + right: 0.0, + child: MediaQuery( + data: existingMediaQuery.copyWith(textScaleFactor: 1), + child: widget.navigationBar, + ), + ), + // Add a touch handler the size of the status bar on top of all contents + // to handle scroll to top by status bar taps. + Positioned( + top: 0.0, + left: 0.0, + right: 0.0, + height: existingMediaQuery.padding.top, + child: GestureDetector( + excludeFromSemantics: true, + onTap: _handleStatusBarTap, + ), + ), + ], ), ); } diff --git a/packages/flutter/lib/src/cupertino/tab_scaffold.dart b/packages/flutter/lib/src/cupertino/tab_scaffold.dart index f348b62ff2..7673806d5d 100644 --- a/packages/flutter/lib/src/cupertino/tab_scaffold.dart +++ b/packages/flutter/lib/src/cupertino/tab_scaffold.dart @@ -346,8 +346,6 @@ class _CupertinoTabScaffoldState extends State { @override Widget build(BuildContext context) { - final List stacked = []; - final MediaQueryData existingMediaQuery = MediaQuery.of(context); MediaQueryData newMediaQuery = MediaQuery.of(context); @@ -397,36 +395,33 @@ class _CupertinoTabScaffoldState extends State { ), ); - // The main content being at the bottom is added to the stack first. - stacked.add(content); - - stacked.add( - MediaQuery( - data: existingMediaQuery.copyWith(textScaleFactor: 1), - child: Align( - alignment: Alignment.bottomCenter, - // Override the tab bar's currentIndex to the current tab and hook in - // our own listener to update the [_controller.currentIndex] on top of a possibly user - // provided callback. - child: widget.tabBar.copyWith( - currentIndex: _controller.index, - onTap: (int newIndex) { - _controller.index = newIndex; - // Chain the user's original callback. - if (widget.tabBar.onTap != null) - widget.tabBar.onTap(newIndex); - }, - ), - ), - ), - ); - return DecoratedBox( decoration: BoxDecoration( color: widget.backgroundColor ?? CupertinoTheme.of(context).scaffoldBackgroundColor, ), child: Stack( - children: stacked, + children: [ + // The main content being at the bottom is added to the stack first. + content, + MediaQuery( + data: existingMediaQuery.copyWith(textScaleFactor: 1), + child: Align( + alignment: Alignment.bottomCenter, + // Override the tab bar's currentIndex to the current tab and hook in + // our own listener to update the [_controller.currentIndex] on top of a possibly user + // provided callback. + child: widget.tabBar.copyWith( + currentIndex: _controller.index, + onTap: (int newIndex) { + _controller.index = newIndex; + // Chain the user's original callback. + if (widget.tabBar.onTap != null) + widget.tabBar.onTap(newIndex); + }, + ), + ), + ), + ], ), ); } diff --git a/packages/flutter/lib/src/cupertino/text_field.dart b/packages/flutter/lib/src/cupertino/text_field.dart index 79081a1353..0fbfbf3d6a 100644 --- a/packages/flutter/lib/src/cupertino/text_field.dart +++ b/packages/flutter/lib/src/cupertino/text_field.dart @@ -730,44 +730,38 @@ class _CupertinoTextFieldState extends State with AutomaticK valueListenable: _effectiveController, child: editableText, builder: (BuildContext context, TextEditingValue text, Widget child) { - final List rowChildren = []; - - // Insert a prefix at the front if the prefix visibility mode matches - // the current text state. - if (_showPrefixWidget(text)) { - rowChildren.add(widget.prefix); - } - - final List stackChildren = []; - - // In the middle part, stack the placeholder on top of the main EditableText - // if needed. - if (widget.placeholder != null && text.text.isEmpty) { - stackChildren.add( - SizedBox( - width: double.infinity, - child: Padding( - padding: widget.padding, - child: Text( - widget.placeholder, - maxLines: widget.maxLines, - overflow: TextOverflow.ellipsis, - style: placeholderStyle, - textAlign: widget.textAlign, - ), - ), + return Row(children: [ + // Insert a prefix at the front if the prefix visibility mode matches + // the current text state. + if (_showPrefixWidget(text)) widget.prefix, + // In the middle part, stack the placeholder on top of the main EditableText + // if needed. + Expanded( + child: Stack( + children: [ + if (widget.placeholder != null && text.text.isEmpty) + SizedBox( + width: double.infinity, + child: Padding( + padding: widget.padding, + child: Text( + widget.placeholder, + maxLines: widget.maxLines, + overflow: TextOverflow.ellipsis, + style: placeholderStyle, + textAlign: widget.textAlign, + ), + ), + ), + child, + ], ), - ); - } - - rowChildren.add(Expanded(child: Stack(children: stackChildren..add(child)))); - - // First add the explicit suffix if the suffix visibility mode matches. - if (_showSuffixWidget(text)) { - rowChildren.add(widget.suffix); - // Otherwise, try to show a clear button if its visibility mode matches. - } else if (_showClearButton(text)) { - rowChildren.add( + ), + // First add the explicit suffix if the suffix visibility mode matches. + if (_showSuffixWidget(text)) + widget.suffix + // Otherwise, try to show a clear button if its visibility mode matches. + else if (_showClearButton(text)) GestureDetector( key: _clearGlobalKey, onTap: widget.enabled ?? true ? () { @@ -787,10 +781,7 @@ class _CupertinoTextFieldState extends State with AutomaticK ), ), ), - ); - } - - return Row(children: rowChildren); + ]); }, ); } diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index 76edc678cd..456d039629 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -547,9 +547,9 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti '(one line) summary description of the problem that was ' 'detected.' ), + DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace), + ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'), ]; - message.add(DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace)); - message.add(ErrorDescription('\nThe malformed error has ${summaries.length} summaries.')); int i = 1; for (DiagnosticsNode summary in summaries) { message.add(DiagnosticsProperty('Summary $i', summary, expandableValue : true)); diff --git a/packages/flutter/lib/src/material/app_bar.dart b/packages/flutter/lib/src/material/app_bar.dart index bad79ac93a..464a45c497 100644 --- a/packages/flutter/lib/src/material/app_bar.dart +++ b/packages/flutter/lib/src/material/app_bar.dart @@ -552,10 +552,13 @@ class _AppBarState extends State { child: appBar, ), ), - widget.bottomOpacity == 1.0 ? widget.bottom : Opacity( - opacity: const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn).transform(widget.bottomOpacity), - child: widget.bottom, - ), + if (widget.bottomOpacity == 1.0) + widget.bottom + else + Opacity( + opacity: const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn).transform(widget.bottomOpacity), + child: widget.bottom, + ), ], ); } diff --git a/packages/flutter/lib/src/material/dialog.dart b/packages/flutter/lib/src/material/dialog.dart index f23ddf74ea..dc4132113c 100644 --- a/packages/flutter/lib/src/material/dialog.dart +++ b/packages/flutter/lib/src/material/dialog.dart @@ -303,22 +303,9 @@ class AlertDialog extends StatelessWidget { assert(debugCheckHasMaterialLocalizations(context)); final ThemeData theme = Theme.of(context); final DialogTheme dialogTheme = DialogTheme.of(context); - final List children = []; - String label = semanticLabel; - if (title != null) { - children.add(Padding( - padding: titlePadding ?? EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0), - child: DefaultTextStyle( - style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.title, - child: Semantics( - child: title, - namesRoute: true, - container: true, - ), - ), - )); - } else { + String label = semanticLabel; + if (title == null) { switch (theme.platform) { case TargetPlatform.iOS: label = semanticLabel; @@ -329,29 +316,38 @@ class AlertDialog extends StatelessWidget { } } - if (content != null) { - children.add(Flexible( - child: Padding( - padding: contentPadding, - child: DefaultTextStyle( - style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subhead, - child: content, - ), - ), - )); - } - - if (actions != null) { - children.add(ButtonBar( - children: actions, - )); - } - Widget dialogChild = IntrinsicWidth( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, - children: children, + children: [ + if (title != null) + Padding( + padding: titlePadding ?? EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0), + child: DefaultTextStyle( + style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.title, + child: Semantics( + child: title, + namesRoute: true, + container: true, + ), + ), + ), + if (content != null) + Flexible( + child: Padding( + padding: contentPadding, + child: DefaultTextStyle( + style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subhead, + child: content, + ), + ), + ), + if (actions != null) + ButtonBar( + children: actions, + ), + ], ), ); @@ -584,20 +580,10 @@ class SimpleDialog extends StatelessWidget { @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); - final List body = []; - String label = semanticLabel; - final ThemeData theme = Theme.of(context); - if (title != null) { - body.add(Padding( - padding: titlePadding, - child: DefaultTextStyle( - style: theme.textTheme.title, - child: Semantics(namesRoute: true, child: title), - ), - )); - } else { + String label = semanticLabel; + if (title == null) { switch (theme.platform) { case TargetPlatform.iOS: label = semanticLabel; @@ -608,15 +594,6 @@ class SimpleDialog extends StatelessWidget { } } - if (children != null) { - body.add(Flexible( - child: SingleChildScrollView( - padding: contentPadding, - child: ListBody(children: children), - ), - )); - } - Widget dialogChild = IntrinsicWidth( stepWidth: 56.0, child: ConstrainedBox( @@ -624,7 +601,23 @@ class SimpleDialog extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, - children: body, + children: [ + if (title != null) + Padding( + padding: titlePadding, + child: DefaultTextStyle( + style: theme.textTheme.title, + child: Semantics(namesRoute: true, child: title), + ), + ), + if (children != null) + Flexible( + child: SingleChildScrollView( + padding: contentPadding, + child: ListBody(children: children), + ), + ), + ], ), ), ); diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index 6fda5ed069..d82e81f4bd 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -951,9 +951,10 @@ class _DropdownButtonState extends State> with WidgetsBindi mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.min, children: [ - widget.isExpanded - ? Expanded(child: innerItemsWidget) - : innerItemsWidget, + if (widget.isExpanded) + Expanded(child: innerItemsWidget) + else + innerItemsWidget, IconTheme( data: IconThemeData( color: _iconColor, diff --git a/packages/flutter/lib/src/material/grid_tile.dart b/packages/flutter/lib/src/material/grid_tile.dart index 7116e7c9c6..ff1e24865f 100644 --- a/packages/flutter/lib/src/material/grid_tile.dart +++ b/packages/flutter/lib/src/material/grid_tile.dart @@ -48,27 +48,26 @@ class GridTile extends StatelessWidget { if (header == null && footer == null) return child; - final List children = [ - Positioned.fill( - child: child, - ), - ]; - if (header != null) { - children.add(Positioned( - top: 0.0, - left: 0.0, - right: 0.0, - child: header, - )); - } - if (footer != null) { - children.add(Positioned( - left: 0.0, - bottom: 0.0, - right: 0.0, - child: footer, - )); - } - return Stack(children: children); + return Stack( + children: [ + Positioned.fill( + child: child, + ), + if (header != null) + Positioned( + top: 0.0, + left: 0.0, + right: 0.0, + child: header, + ), + if (footer != null) + Positioned( + left: 0.0, + bottom: 0.0, + right: 0.0, + child: footer, + ), + ], + ); } } diff --git a/packages/flutter/lib/src/material/grid_tile_bar.dart b/packages/flutter/lib/src/material/grid_tile_bar.dart index 1df0ae889e..8e2cc5dfbb 100644 --- a/packages/flutter/lib/src/material/grid_tile_bar.dart +++ b/packages/flutter/lib/src/material/grid_tile_bar.dart @@ -62,60 +62,17 @@ class GridTileBar extends StatelessWidget { if (backgroundColor != null) decoration = BoxDecoration(color: backgroundColor); - final List children = []; final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only( start: leading != null ? 8.0 : 16.0, end: trailing != null ? 8.0 : 16.0, ); - if (leading != null) - children.add(Padding(padding: const EdgeInsetsDirectional.only(end: 8.0), child: leading)); - final ThemeData theme = Theme.of(context); final ThemeData darkTheme = ThemeData( brightness: Brightness.dark, accentColor: theme.accentColor, accentColorBrightness: theme.accentColorBrightness, ); - if (title != null && subtitle != null) { - children.add( - Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - DefaultTextStyle( - style: darkTheme.textTheme.subhead, - softWrap: false, - overflow: TextOverflow.ellipsis, - child: title, - ), - DefaultTextStyle( - style: darkTheme.textTheme.caption, - softWrap: false, - overflow: TextOverflow.ellipsis, - child: subtitle, - ), - ], - ), - ) - ); - } else if (title != null || subtitle != null) { - children.add( - Expanded( - child: DefaultTextStyle( - style: darkTheme.textTheme.subhead, - softWrap: false, - overflow: TextOverflow.ellipsis, - child: title ?? subtitle, - ), - ) - ); - } - - if (trailing != null) - children.add(Padding(padding: const EdgeInsetsDirectional.only(start: 8.0), child: trailing)); - return Container( padding: padding, decoration: decoration, @@ -126,7 +83,42 @@ class GridTileBar extends StatelessWidget { data: const IconThemeData(color: Colors.white), child: Row( crossAxisAlignment: CrossAxisAlignment.center, - children: children, + children: [ + if (leading != null) + Padding(padding: const EdgeInsetsDirectional.only(end: 8.0), child: leading), + if (title != null && subtitle != null) + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DefaultTextStyle( + style: darkTheme.textTheme.subhead, + softWrap: false, + overflow: TextOverflow.ellipsis, + child: title, + ), + DefaultTextStyle( + style: darkTheme.textTheme.caption, + softWrap: false, + overflow: TextOverflow.ellipsis, + child: subtitle, + ), + ], + ), + ) + else if (title != null || subtitle != null) + Expanded( + child: DefaultTextStyle( + style: darkTheme.textTheme.subhead, + softWrap: false, + overflow: TextOverflow.ellipsis, + child: title ?? subtitle, + ), + ), + if (trailing != null) + Padding(padding: const EdgeInsetsDirectional.only(start: 8.0), child: trailing), + ], ), ), ), diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 2cfded7141..a69c8ff3dc 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -433,17 +433,13 @@ class InkResponse extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final List gestures = []; - if (onTap != null) - gestures.add('tap'); - if (onDoubleTap != null) - gestures.add('double tap'); - if (onLongPress != null) - gestures.add('long press'); - if (onTapDown != null) - gestures.add('tap down'); - if (onTapCancel != null) - gestures.add('tap cancel'); + final List gestures = [ + if (onTap != null) 'tap', + if (onDoubleTap != null) 'double tap', + if (onLongPress != null) 'long press', + if (onTapDown != null) 'tap down', + if (onTapCancel != null) 'tap cancel', + ]; properties.add(IterableProperty('gestures', gestures, ifEmpty: '')); properties.add(DiagnosticsProperty('containedInkWell', containedInkWell, level: DiagnosticLevel.fine)); properties.add(DiagnosticsProperty( diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index 35e8b0aaa8..bd351d6ffe 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -3145,79 +3145,44 @@ class InputDecoration { @override String toString() { - final List description = []; - if (icon != null) - description.add('icon: $icon'); - if (labelText != null) - description.add('labelText: "$labelText"'); - if (helperText != null) - description.add('helperText: "$helperText"'); - if (hintText != null) - description.add('hintText: "$hintText"'); - if (hintMaxLines != null) - description.add('hintMaxLines: "$hintMaxLines"'); - if (errorText != null) - description.add('errorText: "$errorText"'); - if (errorStyle != null) - description.add('errorStyle: "$errorStyle"'); - if (errorMaxLines != null) - description.add('errorMaxLines: "$errorMaxLines"'); - if (hasFloatingPlaceholder == false) - description.add('hasFloatingPlaceholder: false'); - if (isDense ?? false) - description.add('isDense: $isDense'); - if (contentPadding != null) - description.add('contentPadding: $contentPadding'); - if (isCollapsed) - description.add('isCollapsed: $isCollapsed'); - if (prefixIcon != null) - description.add('prefixIcon: $prefixIcon'); - if (prefix != null) - description.add('prefix: $prefix'); - if (prefixText != null) - description.add('prefixText: $prefixText'); - if (prefixStyle != null) - description.add('prefixStyle: $prefixStyle'); - if (suffixIcon != null) - description.add('suffixIcon: $suffixIcon'); - if (suffix != null) - description.add('suffix: $suffix'); - if (suffixText != null) - description.add('suffixText: $suffixText'); - if (suffixStyle != null) - description.add('suffixStyle: $suffixStyle'); - if (counter != null) - description.add('counter: $counter'); - if (counterText != null) - description.add('counterText: $counterText'); - if (counterStyle != null) - description.add('counterStyle: $counterStyle'); - if (filled == true) // filled == null same as filled == false - description.add('filled: true'); - if (fillColor != null) - description.add('fillColor: $fillColor'); - if (focusColor != null) - description.add('focusColor: $focusColor'); - if (hoverColor != null) - description.add('hoverColor: $hoverColor'); - if (errorBorder != null) - description.add('errorBorder: $errorBorder'); - if (focusedBorder != null) - description.add('focusedBorder: $focusedBorder'); - if (focusedErrorBorder != null) - description.add('focusedErrorBorder: $focusedErrorBorder'); - if (disabledBorder != null) - description.add('disabledBorder: $disabledBorder'); - if (enabledBorder != null) - description.add('enabledBorder: $enabledBorder'); - if (border != null) - description.add('border: $border'); - if (!enabled) - description.add('enabled: false'); - if (semanticCounterText != null) - description.add('semanticCounterText: $semanticCounterText'); - if (alignLabelWithHint != null) - description.add('alignLabelWithHint: $alignLabelWithHint'); + final List description = [ + if (icon != null) 'icon: $icon', + if (labelText != null) 'labelText: "$labelText"', + if (helperText != null) 'helperText: "$helperText"', + if (hintText != null) 'hintText: "$hintText"', + if (hintMaxLines != null) 'hintMaxLines: "$hintMaxLines"', + if (errorText != null) 'errorText: "$errorText"', + if (errorStyle != null) 'errorStyle: "$errorStyle"', + if (errorMaxLines != null) 'errorMaxLines: "$errorMaxLines"', + if (hasFloatingPlaceholder == false) 'hasFloatingPlaceholder: false', + if (isDense ?? false) 'isDense: $isDense', + if (contentPadding != null) 'contentPadding: $contentPadding', + if (isCollapsed) 'isCollapsed: $isCollapsed', + if (prefixIcon != null) 'prefixIcon: $prefixIcon', + if (prefix != null) 'prefix: $prefix', + if (prefixText != null) 'prefixText: $prefixText', + if (prefixStyle != null) 'prefixStyle: $prefixStyle', + if (suffixIcon != null) 'suffixIcon: $suffixIcon', + if (suffix != null) 'suffix: $suffix', + if (suffixText != null) 'suffixText: $suffixText', + if (suffixStyle != null) 'suffixStyle: $suffixStyle', + if (counter != null) 'counter: $counter', + if (counterText != null) 'counterText: $counterText', + if (counterStyle != null) 'counterStyle: $counterStyle', + if (filled == true) 'filled: true', // filled == null same as filled == false + if (fillColor != null) 'fillColor: $fillColor', + if (focusColor != null) 'focusColor: $focusColor', + if (hoverColor != null) 'hoverColor: $hoverColor', + if (errorBorder != null) 'errorBorder: $errorBorder', + if (focusedBorder != null) 'focusedBorder: $focusedBorder', + if (focusedErrorBorder != null) 'focusedErrorBorder: $focusedErrorBorder', + if (disabledBorder != null) 'disabledBorder: $disabledBorder', + if (enabledBorder != null) 'enabledBorder: $enabledBorder', + if (border != null) 'border: $border', + if (!enabled) 'enabled: false', + if (semanticCounterText != null) 'semanticCounterText: $semanticCounterText', + if (alignLabelWithHint != null) 'alignLabelWithHint: $alignLabelWithHint', + ]; return 'InputDecoration(${description.join(', ')})'; } } diff --git a/packages/flutter/lib/src/material/reorderable_list.dart b/packages/flutter/lib/src/material/reorderable_list.dart index 0f2120f125..7e901c4d96 100644 --- a/packages/flutter/lib/src/material/reorderable_list.dart +++ b/packages/flutter/lib/src/material/reorderable_list.dart @@ -538,13 +538,6 @@ class _ReorderableListContentState extends State<_ReorderableListContent> with T assert(debugCheckHasMaterialLocalizations(context)); // We use the layout builder to constrain the cross-axis size of dragging child widgets. return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - final List wrappedChildren = []; - if (widget.header != null) { - wrappedChildren.add(widget.header); - } - for (int i = 0; i < widget.children.length; i += 1) { - wrappedChildren.add(_wrap(widget.children[i], i, constraints)); - } const Key endWidgetKey = Key('DraggableList - End Widget'); Widget finalDropArea; switch (widget.scrollDirection) { @@ -564,25 +557,19 @@ class _ReorderableListContentState extends State<_ReorderableListContent> with T ); break; } - if (widget.reverse) { - wrappedChildren.insert(0, _wrap( - finalDropArea, - widget.children.length, - constraints), - ); - } else { - wrappedChildren.add(_wrap( - finalDropArea, - widget.children.length, - constraints), - ); - } return SingleChildScrollView( scrollDirection: widget.scrollDirection, - child: _buildContainerForScrollDirection(children: wrappedChildren), padding: widget.padding, controller: _scrollController, reverse: widget.reverse, + child: _buildContainerForScrollDirection( + children: [ + if (widget.reverse) _wrap(finalDropArea, widget.children.length, constraints), + if (widget.header != null) widget.header, + for (int i = 0; i < widget.children.length; i += 1) _wrap(widget.children[i], i, constraints), + if (!widget.reverse) _wrap(finalDropArea, widget.children.length, constraints), + ], + ), ); }); } diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index de90ca9ddc..32604e3b3f 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -749,46 +749,40 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr @override Widget build(BuildContext context) { - final List children = []; - - if (_previousController.status != AnimationStatus.dismissed) { - if (_isExtendedFloatingActionButton(_previousChild)) { - children.add(FadeTransition( - opacity: _previousScaleAnimation, - child: _previousChild, - )); - } else { - children.add(ScaleTransition( - scale: _previousScaleAnimation, - child: RotationTransition( - turns: _previousRotationAnimation, - child: _previousChild, - ), - )); - } - } - - if (_isExtendedFloatingActionButton(widget.child)) { - children.add(ScaleTransition( - scale: _extendedCurrentScaleAnimation, - child: FadeTransition( - opacity: _currentScaleAnimation, - child: widget.child, - ), - )); - } else { - children.add(ScaleTransition( - scale: _currentScaleAnimation, - child: RotationTransition( - turns: _currentRotationAnimation, - child: widget.child, - ), - )); - } - return Stack( alignment: Alignment.centerRight, - children: children, + children: [ + if (_previousController.status != AnimationStatus.dismissed) + if (_isExtendedFloatingActionButton(_previousChild)) + FadeTransition( + opacity: _previousScaleAnimation, + child: _previousChild, + ) + else + ScaleTransition( + scale: _previousScaleAnimation, + child: RotationTransition( + turns: _previousRotationAnimation, + child: _previousChild, + ), + ), + if (_isExtendedFloatingActionButton(widget.child)) + ScaleTransition( + scale: _extendedCurrentScaleAnimation, + child: FadeTransition( + opacity: _currentScaleAnimation, + child: widget.child, + ), + ) + else + ScaleTransition( + scale: _currentScaleAnimation, + child: RotationTransition( + turns: _currentRotationAnimation, + child: widget.child, + ), + ), + ], ); } diff --git a/packages/flutter/lib/src/material/snack_bar.dart b/packages/flutter/lib/src/material/snack_bar.dart index db70eec518..660c77e4e6 100644 --- a/packages/flutter/lib/src/material/snack_bar.dart +++ b/packages/flutter/lib/src/material/snack_bar.dart @@ -288,28 +288,6 @@ class SnackBar extends StatelessWidget { final bool isFloatingSnackBar = snackBarBehavior == SnackBarBehavior.floating; final double snackBarPadding = isFloatingSnackBar ? 16.0 : 24.0; - final List children = [ - SizedBox(width: snackBarPadding), - Expanded( - child: Container( - padding: const EdgeInsets.symmetric(vertical: _singleLineVerticalPadding), - child: DefaultTextStyle( - style: contentTextStyle, - child: content, - ), - ), - ), - ]; - if (action != null) { - children.add(ButtonTheme( - textTheme: ButtonTextTheme.accent, - minWidth: 64.0, - padding: EdgeInsets.symmetric(horizontal: snackBarPadding), - child: action, - )); - } else { - children.add(SizedBox(width: snackBarPadding)); - } final CurvedAnimation heightAnimation = CurvedAnimation(parent: animation, curve: _snackBarHeightCurve); final CurvedAnimation fadeInAnimation = CurvedAnimation(parent: animation, curve: _snackBarFadeInCurve); final CurvedAnimation fadeOutAnimation = CurvedAnimation( @@ -322,8 +300,28 @@ class SnackBar extends StatelessWidget { top: false, bottom: !isFloatingSnackBar, child: Row( - children: children, crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox(width: snackBarPadding), + Expanded( + child: Container( + padding: const EdgeInsets.symmetric(vertical: _singleLineVerticalPadding), + child: DefaultTextStyle( + style: contentTextStyle, + child: content, + ), + ), + ), + if (action != null) + ButtonTheme( + textTheme: ButtonTextTheme.accent, + minWidth: 64.0, + padding: EdgeInsets.symmetric(horizontal: snackBarPadding), + child: action, + ) + else + SizedBox(width: snackBarPadding), + ], ), ); diff --git a/packages/flutter/lib/src/material/stepper.dart b/packages/flutter/lib/src/material/stepper.dart index a63a7dada9..e0f7aa90b5 100644 --- a/packages/flutter/lib/src/material/stepper.dart +++ b/packages/flutter/lib/src/material/stepper.dart @@ -480,32 +480,27 @@ class _StepperState extends State with TickerProviderStateMixin { } Widget _buildHeaderText(int index) { - final List children = [ - AnimatedDefaultTextStyle( - style: _titleStyle(index), - duration: kThemeAnimationDuration, - curve: Curves.fastOutSlowIn, - child: widget.steps[index].title, - ), - ]; - - if (widget.steps[index].subtitle != null) - children.add( - Container( - margin: const EdgeInsets.only(top: 2.0), - child: AnimatedDefaultTextStyle( - style: _subtitleStyle(index), - duration: kThemeAnimationDuration, - curve: Curves.fastOutSlowIn, - child: widget.steps[index].subtitle, - ), - ), - ); - return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, - children: children, + children: [ + AnimatedDefaultTextStyle( + style: _titleStyle(index), + duration: kThemeAnimationDuration, + curve: Curves.fastOutSlowIn, + child: widget.steps[index].title, + ), + if (widget.steps[index].subtitle != null) + Container( + margin: const EdgeInsets.only(top: 2.0), + child: AnimatedDefaultTextStyle( + style: _subtitleStyle(index), + duration: kThemeAnimationDuration, + curve: Curves.fastOutSlowIn, + child: widget.steps[index].subtitle, + ), + ), + ], ); } @@ -577,46 +572,39 @@ class _StepperState extends State with TickerProviderStateMixin { } Widget _buildVertical() { - final List children = []; - - for (int i = 0; i < widget.steps.length; i += 1) { - children.add( - Column( - key: _keys[i], - children: [ - InkWell( - onTap: widget.steps[i].state != StepState.disabled ? () { - // In the vertical case we need to scroll to the newly tapped - // step. - Scrollable.ensureVisible( - _keys[i].currentContext, - curve: Curves.fastOutSlowIn, - duration: kThemeAnimationDuration, - ); - - if (widget.onStepTapped != null) - widget.onStepTapped(i); - } : null, - child: _buildVerticalHeader(i), - ), - _buildVerticalBody(i), - ], - ) - ); - } - return ListView( shrinkWrap: true, physics: widget.physics, - children: children, + children: [ + for (int i = 0; i < widget.steps.length; i += 1) + Column( + key: _keys[i], + children: [ + InkWell( + onTap: widget.steps[i].state != StepState.disabled ? () { + // In the vertical case we need to scroll to the newly tapped + // step. + Scrollable.ensureVisible( + _keys[i].currentContext, + curve: Curves.fastOutSlowIn, + duration: kThemeAnimationDuration, + ); + + if (widget.onStepTapped != null) + widget.onStepTapped(i); + } : null, + child: _buildVerticalHeader(i), + ), + _buildVerticalBody(i), + ], + ), + ], ); } Widget _buildHorizontal() { - final List children = []; - - for (int i = 0; i < widget.steps.length; i += 1) { - children.add( + final List children = [ + for (int i = 0; i < widget.steps.length; i += 1) ...[ InkResponse( onTap: widget.steps[i].state != StepState.disabled ? () { if (widget.onStepTapped != null) @@ -637,10 +625,7 @@ class _StepperState extends State with TickerProviderStateMixin { ], ), ), - ); - - if (!_isLast(i)) { - children.add( + if (!_isLast(i)) Expanded( child: Container( margin: const EdgeInsets.symmetric(horizontal: 8.0), @@ -648,9 +633,8 @@ class _StepperState extends State with TickerProviderStateMixin { color: Colors.grey.shade400, ), ), - ); - } - } + ], + ]; return Column( children: [ diff --git a/packages/flutter/lib/src/material/text_selection.dart b/packages/flutter/lib/src/material/text_selection.dart index 183de6c2a6..e19b971735 100644 --- a/packages/flutter/lib/src/material/text_selection.dart +++ b/packages/flutter/lib/src/material/text_selection.dart @@ -40,17 +40,13 @@ class _TextSelectionToolbar extends StatelessWidget { @override Widget build(BuildContext context) { - final List items = []; final MaterialLocalizations localizations = MaterialLocalizations.of(context); - - if (handleCut != null) - items.add(FlatButton(child: Text(localizations.cutButtonLabel), onPressed: handleCut)); - if (handleCopy != null) - items.add(FlatButton(child: Text(localizations.copyButtonLabel), onPressed: handleCopy)); - if (handlePaste != null) - items.add(FlatButton(child: Text(localizations.pasteButtonLabel), onPressed: handlePaste,)); - if (handleSelectAll != null) - items.add(FlatButton(child: Text(localizations.selectAllButtonLabel), onPressed: handleSelectAll)); + final List items = [ + if (handleCut != null) FlatButton(child: Text(localizations.cutButtonLabel), onPressed: handleCut), + if (handleCopy != null) FlatButton(child: Text(localizations.copyButtonLabel), onPressed: handleCopy), + if (handlePaste != null) FlatButton(child: Text(localizations.pasteButtonLabel), onPressed: handlePaste), + if (handleSelectAll != null) FlatButton(child: Text(localizations.selectAllButtonLabel), onPressed: handleSelectAll), + ]; // If there is no option available, build an empty widget. if (items.isEmpty) { diff --git a/packages/flutter/lib/src/material/time_picker.dart b/packages/flutter/lib/src/material/time_picker.dart index 1745cdfb20..78ba676a01 100644 --- a/packages/flutter/lib/src/material/time_picker.dart +++ b/packages/flutter/lib/src/material/time_picker.dart @@ -541,12 +541,13 @@ _TimePickerHeaderFormat _buildHeaderFormat( _TimePickerHeaderFragment fragment2, _TimePickerHeaderFragment fragment3, }) { - final List<_TimePickerHeaderFragment> fragments = <_TimePickerHeaderFragment>[fragment1]; - if (fragment2 != null) { - fragments.add(fragment2); - if (fragment3 != null) - fragments.add(fragment3); - } + final List<_TimePickerHeaderFragment> fragments = <_TimePickerHeaderFragment>[ + fragment1, + if (fragment2 != null) ...<_TimePickerHeaderFragment>[ + fragment2, + if (fragment3 != null) fragment3, + ], + ]; return _TimePickerHeaderPiece(pivotIndex, fragments, bottomMargin: bottomMargin); } @@ -1336,50 +1337,41 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ); } - List<_TappableLabel> _build24HourInnerRing(TextTheme textTheme) { - final List<_TappableLabel> labels = <_TappableLabel>[]; - for (TimeOfDay timeOfDay in _amHours) { - labels.add(_buildTappableLabel( + List<_TappableLabel> _build24HourInnerRing(TextTheme textTheme) => <_TappableLabel>[ + for (TimeOfDay timeOfDay in _amHours) + _buildTappableLabel( textTheme, timeOfDay.hour, localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat), () { _selectHour(timeOfDay.hour); }, - )); - } - return labels; - } + ), + ]; - List<_TappableLabel> _build24HourOuterRing(TextTheme textTheme) { - final List<_TappableLabel> labels = <_TappableLabel>[]; - for (TimeOfDay timeOfDay in _pmHours) { - labels.add(_buildTappableLabel( + List<_TappableLabel> _build24HourOuterRing(TextTheme textTheme) => <_TappableLabel>[ + for (TimeOfDay timeOfDay in _pmHours) + _buildTappableLabel( textTheme, timeOfDay.hour, localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat), () { _selectHour(timeOfDay.hour); }, - )); - } - return labels; - } + ), + ]; - List<_TappableLabel> _build12HourOuterRing(TextTheme textTheme) { - final List<_TappableLabel> labels = <_TappableLabel>[]; - for (TimeOfDay timeOfDay in _amHours) { - labels.add(_buildTappableLabel( + List<_TappableLabel> _build12HourOuterRing(TextTheme textTheme) => <_TappableLabel>[ + for (TimeOfDay timeOfDay in _amHours) + _buildTappableLabel( textTheme, timeOfDay.hour, localizations.formatHour(timeOfDay, alwaysUse24HourFormat: media.alwaysUse24HourFormat), () { _selectHour(timeOfDay.hour); }, - )); - } - return labels; - } + ), + ]; List<_TappableLabel> _buildMinutes(TextTheme textTheme) { const List _minuteMarkerValues = [ @@ -1397,18 +1389,17 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { TimeOfDay(hour: 0, minute: 55), ]; - final List<_TappableLabel> labels = <_TappableLabel>[]; - for (TimeOfDay timeOfDay in _minuteMarkerValues) { - labels.add(_buildTappableLabel( - textTheme, - timeOfDay.minute, - localizations.formatMinute(timeOfDay), - () { - _selectMinute(timeOfDay.minute); - }, - )); - } - return labels; + return <_TappableLabel>[ + for (TimeOfDay timeOfDay in _minuteMarkerValues) + _buildTappableLabel( + textTheme, + timeOfDay.minute, + localizations.formatMinute(timeOfDay), + () { + _selectMinute(timeOfDay.minute); + }, + ), + ]; } @override diff --git a/packages/flutter/lib/src/material/user_accounts_drawer_header.dart b/packages/flutter/lib/src/material/user_accounts_drawer_header.dart index 1098a28b91..efa276176c 100644 --- a/packages/flutter/lib/src/material/user_accounts_drawer_header.dart +++ b/packages/flutter/lib/src/material/user_accounts_drawer_header.dart @@ -134,71 +134,63 @@ class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProvi assert(debugCheckHasMaterialLocalizations(context)); final ThemeData theme = Theme.of(context); - final List children = []; - - if (widget.accountName != null) { - final Widget accountNameLine = LayoutId( - id: _AccountDetailsLayout.accountName, - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 2.0), - child: DefaultTextStyle( - style: theme.primaryTextTheme.body2, - overflow: TextOverflow.ellipsis, - child: widget.accountName, - ), - ), - ); - children.add(accountNameLine); - } - - if (widget.accountEmail != null) { - final Widget accountEmailLine = LayoutId( - id: _AccountDetailsLayout.accountEmail, - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 2.0), - child: DefaultTextStyle( - style: theme.primaryTextTheme.body1, - overflow: TextOverflow.ellipsis, - child: widget.accountEmail, - ), - ), - ); - children.add(accountEmailLine); - } - if (widget.onTap != null) { - final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final Widget dropDownIcon = LayoutId( - id: _AccountDetailsLayout.dropdownIcon, - child: Semantics( - container: true, - button: true, - onTap: widget.onTap, - child: SizedBox( - height: _kAccountDetailsHeight, - width: _kAccountDetailsHeight, - child: Center( - child: Transform.rotate( - angle: _animation.value * math.pi, - child: Icon( - Icons.arrow_drop_down, - color: widget.arrowColor, - semanticLabel: widget.isOpen - ? localizations.hideAccountsLabel - : localizations.showAccountsLabel, - ), - ), - ), - ), - ), - ); - children.add(dropDownIcon); - } + final MaterialLocalizations localizations = MaterialLocalizations.of(context); Widget accountDetails = CustomMultiChildLayout( delegate: _AccountDetailsLayout( textDirection: Directionality.of(context), ), - children: children, + children: [ + if (widget.accountName != null) + LayoutId( + id: _AccountDetailsLayout.accountName, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2.0), + child: DefaultTextStyle( + style: theme.primaryTextTheme.body2, + overflow: TextOverflow.ellipsis, + child: widget.accountName, + ), + ), + ), + if (widget.accountEmail != null) + LayoutId( + id: _AccountDetailsLayout.accountEmail, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2.0), + child: DefaultTextStyle( + style: theme.primaryTextTheme.body1, + overflow: TextOverflow.ellipsis, + child: widget.accountEmail, + ), + ), + ), + if (widget.onTap != null) + LayoutId( + id: _AccountDetailsLayout.dropdownIcon, + child: Semantics( + container: true, + button: true, + onTap: widget.onTap, + child: SizedBox( + height: _kAccountDetailsHeight, + width: _kAccountDetailsHeight, + child: Center( + child: Transform.rotate( + angle: _animation.value * math.pi, + child: Icon( + Icons.arrow_drop_down, + color: widget.arrowColor, + semanticLabel: widget.isOpen + ? localizations.hideAccountsLabel + : localizations.showAccountsLabel, + ), + ), + ), + ), + ), + ), + ], ); if (widget.onTap != null) { diff --git a/packages/flutter/lib/src/painting/box_border.dart b/packages/flutter/lib/src/painting/box_border.dart index a6c082a249..5d6f432ca3 100644 --- a/packages/flutter/lib/src/painting/box_border.dart +++ b/packages/flutter/lib/src/painting/box_border.dart @@ -533,15 +533,12 @@ class Border extends BoxBorder { String toString() { if (isUniform) return '$runtimeType.all($top)'; - final List arguments = []; - if (top != BorderSide.none) - arguments.add('top: $top'); - if (right != BorderSide.none) - arguments.add('right: $right'); - if (bottom != BorderSide.none) - arguments.add('bottom: $bottom'); - if (left != BorderSide.none) - arguments.add('left: $left'); + final List arguments = [ + if (top != BorderSide.none) 'top: $top', + if (right != BorderSide.none) 'right: $right', + if (bottom != BorderSide.none) 'bottom: $bottom', + if (left != BorderSide.none) 'left: $left', + ]; return '$runtimeType(${arguments.join(", ")})'; } } @@ -838,15 +835,12 @@ class BorderDirectional extends BoxBorder { @override String toString() { - final List arguments = []; - if (top != BorderSide.none) - arguments.add('top: $top'); - if (start != BorderSide.none) - arguments.add('start: $start'); - if (end != BorderSide.none) - arguments.add('end: $end'); - if (bottom != BorderSide.none) - arguments.add('bottom: $bottom'); + final List arguments = [ + if (top != BorderSide.none) 'top: $top', + if (start != BorderSide.none) 'start: $start', + if (end != BorderSide.none) 'end: $end', + if (bottom != BorderSide.none) 'bottom: $bottom', + ]; return '$runtimeType(${arguments.join(", ")})'; } } diff --git a/packages/flutter/lib/src/painting/box_shadow.dart b/packages/flutter/lib/src/painting/box_shadow.dart index cadc77e784..f13448c739 100644 --- a/packages/flutter/lib/src/painting/box_shadow.dart +++ b/packages/flutter/lib/src/painting/box_shadow.dart @@ -104,15 +104,12 @@ class BoxShadow extends ui.Shadow { return null; a ??= []; b ??= []; - final List result = []; final int commonLength = math.min(a.length, b.length); - for (int i = 0; i < commonLength; i += 1) - result.add(BoxShadow.lerp(a[i], b[i], t)); - for (int i = commonLength; i < a.length; i += 1) - result.add(a[i].scale(1.0 - t)); - for (int i = commonLength; i < b.length; i += 1) - result.add(b[i].scale(t)); - return result; + return [ + for (int i = 0; i < commonLength; i += 1) BoxShadow.lerp(a[i], b[i], t), + for (int i = commonLength; i < a.length; i += 1) a[i].scale(1.0 - t), + for (int i = commonLength; i < b.length; i += 1) b[i].scale(t), + ]; } @override diff --git a/packages/flutter/lib/src/painting/decoration_image.dart b/packages/flutter/lib/src/painting/decoration_image.dart index a4ba07269a..2099c6126f 100644 --- a/packages/flutter/lib/src/painting/decoration_image.dart +++ b/packages/flutter/lib/src/painting/decoration_image.dart @@ -156,21 +156,22 @@ class DecorationImage { @override String toString() { - final List properties = []; - properties.add('$image'); - if (colorFilter != null) - properties.add('$colorFilter'); - if (fit != null && - !(fit == BoxFit.fill && centerSlice != null) && - !(fit == BoxFit.scaleDown && centerSlice == null)) - properties.add('$fit'); - properties.add('$alignment'); - if (centerSlice != null) - properties.add('centerSlice: $centerSlice'); - if (repeat != ImageRepeat.noRepeat) - properties.add('$repeat'); - if (matchTextDirection) - properties.add('match text direction'); + final List properties = [ + '$image', + if (colorFilter != null) + '$colorFilter', + if (fit != null && + !(fit == BoxFit.fill && centerSlice != null) && + !(fit == BoxFit.scaleDown && centerSlice == null)) + '$fit', + '$alignment', + if (centerSlice != null) + 'centerSlice: $centerSlice', + if (repeat != ImageRepeat.noRepeat) + '$repeat', + if (matchTextDirection) + 'match text direction', + ]; return '$runtimeType(${properties.join(", ")})'; } } diff --git a/packages/flutter/lib/src/painting/strut_style.dart b/packages/flutter/lib/src/painting/strut_style.dart index e697ca974c..4cc1fb900a 100644 --- a/packages/flutter/lib/src/painting/strut_style.dart +++ b/packages/flutter/lib/src/painting/strut_style.dart @@ -578,10 +578,11 @@ class StrutStyle extends Diagnosticable { super.debugFillProperties(properties); if (debugLabel != null) properties.add(MessageProperty('${prefix}debugLabel', debugLabel)); - final List styles = []; - styles.add(StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false)); - styles.add(IterableProperty('${prefix}familyFallback', fontFamilyFallback, defaultValue: null)); - styles.add(DoubleProperty('${prefix}size', fontSize, defaultValue: null)); + final List styles = [ + StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false), + IterableProperty('${prefix}familyFallback', fontFamilyFallback, defaultValue: null), + DoubleProperty('${prefix}size', fontSize, defaultValue: null), + ]; String weightDescription; if (fontWeight != null) { weightDescription = 'w${fontWeight.index + 1}00'; diff --git a/packages/flutter/lib/src/painting/text_style.dart b/packages/flutter/lib/src/painting/text_style.dart index 4ab45452b6..87172e10b3 100644 --- a/packages/flutter/lib/src/painting/text_style.dart +++ b/packages/flutter/lib/src/painting/text_style.dart @@ -1202,12 +1202,13 @@ class TextStyle extends Diagnosticable { super.debugFillProperties(properties); if (debugLabel != null) properties.add(MessageProperty('${prefix}debugLabel', debugLabel)); - final List styles = []; - styles.add(ColorProperty('${prefix}color', color, defaultValue: null)); - styles.add(ColorProperty('${prefix}backgroundColor', backgroundColor, defaultValue: null)); - styles.add(StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false)); - styles.add(IterableProperty('${prefix}familyFallback', fontFamilyFallback, defaultValue: null)); - styles.add(DoubleProperty('${prefix}size', fontSize, defaultValue: null)); + final List styles = [ + ColorProperty('${prefix}color', color, defaultValue: null), + ColorProperty('${prefix}backgroundColor', backgroundColor, defaultValue: null), + StringProperty('${prefix}family', fontFamily, defaultValue: null, quoted: false), + IterableProperty('${prefix}familyFallback', fontFamilyFallback, defaultValue: null), + DoubleProperty('${prefix}size', fontSize, defaultValue: null), + ]; String weightDescription; if (fontWeight != null) { weightDescription = '${fontWeight.index + 1}00'; diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index 8404b47131..4076130859 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -505,15 +505,12 @@ class BoxConstraints extends Constraints { ]); } if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { - final List affectedFieldsList = []; - if (minWidth.isNaN) - affectedFieldsList.add('minWidth'); - if (maxWidth.isNaN) - affectedFieldsList.add('maxWidth'); - if (minHeight.isNaN) - affectedFieldsList.add('minHeight'); - if (maxHeight.isNaN) - affectedFieldsList.add('maxHeight'); + final List affectedFieldsList = [ + if (minWidth.isNaN) 'minWidth', + if (maxWidth.isNaN) 'maxWidth', + if (minHeight.isNaN) 'minHeight', + if (maxHeight.isNaN) 'maxHeight', + ]; assert(affectedFieldsList.isNotEmpty); if (affectedFieldsList.length > 1) affectedFieldsList.add('and ${affectedFieldsList.removeLast()}'); @@ -1711,8 +1708,9 @@ abstract class RenderBox extends RenderObject { (!sizedByParent && debugDoingThisLayout)) return true; assert(!debugDoingThisResize); - final List information = []; - information.add(ErrorSummary('RenderBox size setter called incorrectly.')); + final List information = [ + ErrorSummary('RenderBox size setter called incorrectly.'), + ]; if (debugDoingThisLayout) { assert(sizedByParent); information.add(ErrorDescription('It appears that the size setter was called from performLayout().')); diff --git a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart index e65203ba6b..772df20485 100644 --- a/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart +++ b/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart @@ -217,15 +217,12 @@ mixin DebugOverflowIndicatorMixin on RenderObject { )); } - final List overflows = []; - if (overflow.left > 0.0) - overflows.add('${_formatPixels(overflow.left)} pixels on the left'); - if (overflow.top > 0.0) - overflows.add('${_formatPixels(overflow.top)} pixels on the top'); - if (overflow.bottom > 0.0) - overflows.add('${_formatPixels(overflow.bottom)} pixels on the bottom'); - if (overflow.right > 0.0) - overflows.add('${_formatPixels(overflow.right)} pixels on the right'); + final List overflows = [ + if (overflow.left > 0.0) '${_formatPixels(overflow.left)} pixels on the left', + if (overflow.top > 0.0) '${_formatPixels(overflow.top)} pixels on the top', + if (overflow.bottom > 0.0) '${_formatPixels(overflow.bottom)} pixels on the bottom', + if (overflow.right > 0.0) '${_formatPixels(overflow.right)} pixels on the right', + ]; String overflowText = ''; assert(overflows.isNotEmpty, "Somehow $runtimeType didn't actually overflow like it thought it did."); diff --git a/packages/flutter/lib/src/rendering/paragraph.dart b/packages/flutter/lib/src/rendering/paragraph.dart index 6585cacf0e..4dd8fa124b 100644 --- a/packages/flutter/lib/src/rendering/paragraph.dart +++ b/packages/flutter/lib/src/rendering/paragraph.dart @@ -44,12 +44,11 @@ class TextParentData extends ContainerBoxParentData { @override String toString() { - final List values = []; - if (offset != null) - values.add('offset=$offset'); - if (scale != null) - values.add('scale=$scale'); - values.add(super.toString()); + final List values = [ + if (offset != null) 'offset=$offset', + if (scale != null) 'scale=$scale', + super.toString(), + ]; return values.join('; '); } } diff --git a/packages/flutter/lib/src/rendering/proxy_box.dart b/packages/flutter/lib/src/rendering/proxy_box.dart index bc37669c56..43ad5e1889 100644 --- a/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/packages/flutter/lib/src/rendering/proxy_box.dart @@ -3456,15 +3456,12 @@ class RenderSemanticsGestureHandler extends RenderProxyBox { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final List gestures = []; - if (onTap != null) - gestures.add('tap'); - if (onLongPress != null) - gestures.add('long press'); - if (onHorizontalDragUpdate != null) - gestures.add('horizontal scroll'); - if (onVerticalDragUpdate != null) - gestures.add('vertical scroll'); + final List gestures = [ + if (onTap != null) 'tap', + if (onLongPress != null) 'long press', + if (onHorizontalDragUpdate != null) 'horizontal scroll', + if (onVerticalDragUpdate != null) 'vertical scroll', + ]; if (gestures.isEmpty) gestures.add(''); properties.add(IterableProperty('gestures', gestures)); diff --git a/packages/flutter/lib/src/rendering/sliver.dart b/packages/flutter/lib/src/rendering/sliver.dart index 1dc72a04fa..5789993a9f 100644 --- a/packages/flutter/lib/src/rendering/sliver.dart +++ b/packages/flutter/lib/src/rendering/sliver.dart @@ -953,21 +953,20 @@ class SliverPhysicalParentData extends ParentData { class SliverPhysicalContainerParentData extends SliverPhysicalParentData with ContainerParentDataMixin { } List _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) { - final List information = []; - if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1)) { - information..add(ErrorDescription( - 'The $labelA is ${valueA.toStringAsFixed(1)}, but ' - 'the $labelB is ${valueB.toStringAsFixed(1)}.' - )); - } else { - information - ..add(ErrorDescription('The $labelA is $valueA, but the $labelB is $valueB.')) - ..add(ErrorHint( + return [ + if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1)) + ErrorDescription( + 'The $labelA is ${valueA.toStringAsFixed(1)}, but ' + 'the $labelB is ${valueB.toStringAsFixed(1)}.' + ) + else ...[ + ErrorDescription('The $labelA is $valueA, but the $labelB is $valueB.'), + ErrorHint( 'Maybe you have fallen prey to floating point rounding errors, and should explicitly ' 'apply the min() or max() functions, or the clamp() method, to the $labelB?' - )); - } - return information; + ), + ], + ]; } /// Base class for the render objects that implement scroll effects in viewports. @@ -1146,13 +1145,11 @@ abstract class RenderSliver extends RenderObject { final List information = [ ErrorSummary('RenderSliver geometry setter called incorrectly.'), - violation + violation, + if (hint != null) hint, + contract, + describeForError('The RenderSliver in question is'), ]; - if (hint != null) - information.add(hint); - information.add(contract); - information.add(describeForError('The RenderSliver in question is')); - throw FlutterError.fromParts(information); }()); _geometry = value; diff --git a/packages/flutter/lib/src/rendering/stack.dart b/packages/flutter/lib/src/rendering/stack.dart index 50991f50a4..26a2dc95a7 100644 --- a/packages/flutter/lib/src/rendering/stack.dart +++ b/packages/flutter/lib/src/rendering/stack.dart @@ -213,19 +213,14 @@ class StackParentData extends ContainerBoxParentData { @override String toString() { - final List values = []; - if (top != null) - values.add('top=${debugFormatDouble(top)}'); - if (right != null) - values.add('right=${debugFormatDouble(right)}'); - if (bottom != null) - values.add('bottom=${debugFormatDouble(bottom)}'); - if (left != null) - values.add('left=${debugFormatDouble(left)}'); - if (width != null) - values.add('width=${debugFormatDouble(width)}'); - if (height != null) - values.add('height=${debugFormatDouble(height)}'); + final List values = [ + if (top != null) 'top=${debugFormatDouble(top)}', + if (right != null) 'right=${debugFormatDouble(right)}', + if (bottom != null) 'bottom=${debugFormatDouble(bottom)}', + if (left != null) 'left=${debugFormatDouble(left)}', + if (width != null) 'width=${debugFormatDouble(width)}', + if (height != null) 'height=${debugFormatDouble(height)}', + ]; if (values.isEmpty) values.add('not positioned'); values.add(super.toString()); diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 463fdfaa18..cc38f3e94c 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -363,22 +363,22 @@ class SemanticsData extends Diagnosticable { properties.add(TransformProperty('transform', transform, showName: false, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0)); properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0)); - final List actionSummary = []; - for (SemanticsAction action in SemanticsAction.values.values) { - if ((actions & action.index) != 0) - actionSummary.add(describeEnum(action)); - } + final List actionSummary = [ + for (SemanticsAction action in SemanticsAction.values.values) + if ((actions & action.index) != 0) + describeEnum(action), + ]; final List customSemanticsActionSummary = customSemanticsActionIds .map((int actionId) => CustomSemanticsAction.getAction(actionId).label) .toList(); properties.add(IterableProperty('actions', actionSummary, ifEmpty: null)); properties.add(IterableProperty('customActions', customSemanticsActionSummary, ifEmpty: null)); - final List flagSummary = []; - for (SemanticsFlag flag in SemanticsFlag.values.values) { - if ((flags & flag.index) != 0) - flagSummary.add(describeEnum(flag)); - } + final List flagSummary = [ + for (SemanticsFlag flag in SemanticsFlag.values.values) + if ((flags & flag.index) != 0) + describeEnum(flag), + ]; properties.add(IterableProperty('flags', flagSummary, ifEmpty: null)); properties.add(StringProperty('label', label, defaultValue: '')); properties.add(StringProperty('value', value, defaultValue: '')); diff --git a/packages/flutter/lib/src/services/system_chrome.dart b/packages/flutter/lib/src/services/system_chrome.dart index b9d33f8b0f..eed220552b 100644 --- a/packages/flutter/lib/src/services/system_chrome.dart +++ b/packages/flutter/lib/src/services/system_chrome.dart @@ -206,12 +206,9 @@ class SystemUiOverlayStyle { } } -List _stringify(List list) { - final List result = []; - for (dynamic item in list) - result.add(item.toString()); - return result; -} +List _stringify(List list) => [ + for (dynamic item in list) item.toString(), +]; /// Controls specific aspects of the operating system's graphical interface and /// how it interacts with the application. diff --git a/packages/flutter/lib/src/widgets/animated_switcher.dart b/packages/flutter/lib/src/widgets/animated_switcher.dart index 5bbc49d693..338e86baa7 100644 --- a/packages/flutter/lib/src/widgets/animated_switcher.dart +++ b/packages/flutter/lib/src/widgets/animated_switcher.dart @@ -276,11 +276,11 @@ class AnimatedSwitcher extends StatefulWidget { /// /// This is an [AnimatedSwitcherLayoutBuilder] function. static Widget defaultLayoutBuilder(Widget currentChild, List previousChildren) { - List children = previousChildren; - if (currentChild != null) - children = children.toList()..add(currentChild); return Stack( - children: children, + children: [ + ...previousChildren, + if (currentChild != null) currentChild, + ], alignment: Alignment.center, ); } diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index ed067902db..f1df322a31 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -5714,17 +5714,13 @@ class _PointerListener extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final List listeners = []; - if (onPointerDown != null) - listeners.add('down'); - if (onPointerMove != null) - listeners.add('move'); - if (onPointerUp != null) - listeners.add('up'); - if (onPointerCancel != null) - listeners.add('cancel'); - if (onPointerSignal != null) - listeners.add('signal'); + final List listeners = [ + if (onPointerDown != null) 'down', + if (onPointerMove != null) 'move', + if (onPointerUp != null) 'up', + if (onPointerCancel != null) 'cancel', + if (onPointerSignal != null) 'signal', + ]; properties.add(IterableProperty('listeners', listeners, ifEmpty: '')); properties.add(EnumProperty('behavior', behavior)); } diff --git a/packages/flutter/lib/src/widgets/dismissible.dart b/packages/flutter/lib/src/widgets/dismissible.dart index 84c21e3943..4333d9ce1a 100644 --- a/packages/flutter/lib/src/widgets/dismissible.dart +++ b/packages/flutter/lib/src/widgets/dismissible.dart @@ -549,22 +549,19 @@ class _DismissibleState extends State with TickerProviderStateMixin ); if (background != null) { - final List children = []; - - if (!_moveAnimation.isDismissed) { - children.add(Positioned.fill( - child: ClipRect( - clipper: _DismissibleClipper( - axis: _directionIsXAxis ? Axis.horizontal : Axis.vertical, - moveAnimation: _moveAnimation, + content = Stack(children: [ + if (!_moveAnimation.isDismissed) + Positioned.fill( + child: ClipRect( + clipper: _DismissibleClipper( + axis: _directionIsXAxis ? Axis.horizontal : Axis.vertical, + moveAnimation: _moveAnimation, + ), + child: background, ), - child: background, ), - )); - } - - children.add(content); - content = Stack(children: children); + content, + ]); } // We are not resizing but we may be being dragging in widget.direction. return GestureDetector( diff --git a/packages/flutter/lib/src/widgets/focus_traversal.dart b/packages/flutter/lib/src/widgets/focus_traversal.dart index f288fd5e86..e063d81a0e 100644 --- a/packages/flutter/lib/src/widgets/focus_traversal.dart +++ b/packages/flutter/lib/src/widgets/focus_traversal.dart @@ -657,10 +657,9 @@ class ReadingOrderTraversalPolicy extends FocusTraversalPolicy with DirectionalF return topmost; } - final List<_SortData> data = <_SortData>[]; - for (FocusNode node in nodes) { - data.add(_SortData(node)); - } + final List<_SortData> data = <_SortData>[ + for (FocusNode node in nodes) _SortData(node), + ]; // Pick the initial widget as the one that is leftmost in the band of the // topmost, or the topmost, if there are no others in its band. diff --git a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart index 670c39a47d..2500e1aae7 100644 --- a/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart @@ -263,15 +263,14 @@ class FixedExtentScrollController extends ScrollController { return; } - final List> futures = >[]; - for (_FixedExtentScrollPosition position in positions) { - futures.add(position.animateTo( - itemIndex * position.itemExtent, - duration: duration, - curve: curve, - )); - } - await Future.wait(futures); + await Future.wait(>[ + for (_FixedExtentScrollPosition position in positions) + position.animateTo( + itemIndex * position.itemExtent, + duration: duration, + curve: curve, + ), + ]); } /// Changes which item index is centered in the controlled scroll view. diff --git a/packages/flutter/lib/src/widgets/navigation_toolbar.dart b/packages/flutter/lib/src/widgets/navigation_toolbar.dart index e1960eaae2..ec684dd568 100644 --- a/packages/flutter/lib/src/widgets/navigation_toolbar.dart +++ b/packages/flutter/lib/src/widgets/navigation_toolbar.dart @@ -61,17 +61,6 @@ class NavigationToolbar extends StatelessWidget { @override Widget build(BuildContext context) { assert(debugCheckHasDirectionality(context)); - final List children = []; - - if (leading != null) - children.add(LayoutId(id: _ToolbarSlot.leading, child: leading)); - - if (middle != null) - children.add(LayoutId(id: _ToolbarSlot.middle, child: middle)); - - if (trailing != null) - children.add(LayoutId(id: _ToolbarSlot.trailing, child: trailing)); - final TextDirection textDirection = Directionality.of(context); return CustomMultiChildLayout( delegate: _ToolbarLayout( @@ -79,7 +68,11 @@ class NavigationToolbar extends StatelessWidget { middleSpacing: middleSpacing, textDirection: textDirection, ), - children: children, + children: [ + if (leading != null) LayoutId(id: _ToolbarSlot.leading, child: leading), + if (middle != null) LayoutId(id: _ToolbarSlot.middle, child: middle), + if (trailing != null) LayoutId(id: _ToolbarSlot.trailing, child: trailing), + ], ); } } diff --git a/packages/flutter/lib/src/widgets/overlay.dart b/packages/flutter/lib/src/widgets/overlay.dart index 55d009471e..c1f1cd37d1 100644 --- a/packages/flutter/lib/src/widgets/overlay.dart +++ b/packages/flutter/lib/src/widgets/overlay.dart @@ -660,10 +660,9 @@ class _RenderTheatre extends RenderBox @override List debugDescribeChildren() { - final List children = []; - - if (child != null) - children.add(child.toDiagnosticsNode(name: 'onstage')); + final List children = [ + if (child != null) child.toDiagnosticsNode(name: 'onstage'), + ]; if (firstChild != null) { RenderBox child = firstChild; diff --git a/packages/flutter/lib/src/widgets/routes.dart b/packages/flutter/lib/src/widgets/routes.dart index 11419ba953..cac5ee2610 100644 --- a/packages/flutter/lib/src/widgets/routes.dart +++ b/packages/flutter/lib/src/widgets/routes.dart @@ -589,11 +589,10 @@ class _ModalScopeState extends State<_ModalScope> { @override void initState() { super.initState(); - final List animations = []; - if (widget.route.animation != null) - animations.add(widget.route.animation); - if (widget.route.secondaryAnimation != null) - animations.add(widget.route.secondaryAnimation); + final List animations = [ + if (widget.route.animation != null) widget.route.animation, + if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation, + ]; _listenable = Listenable.merge(animations); if (widget.route.isCurrent) { widget.route.navigator.focusScopeNode.setFirstFocus(focusScopeNode); diff --git a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart index 1547c3e2f3..f013693010 100644 --- a/packages/flutter/lib/src/widgets/sliver_persistent_header.dart +++ b/packages/flutter/lib/src/widgets/sliver_persistent_header.dart @@ -143,11 +143,10 @@ class SliverPersistentHeader extends StatelessWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('delegate', delegate)); - final List flags = []; - if (pinned) - flags.add('pinned'); - if (floating) - flags.add('floating'); + final List flags = [ + if (pinned) 'pinned', + if (floating) 'floating', + ]; if (flags.isEmpty) flags.add('normal'); properties.add(IterableProperty('mode', flags)); diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index 4624f895be..dcf776428b 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -2267,30 +2267,29 @@ class _WidgetInspectorState extends State @override Widget build(BuildContext context) { - final List children = []; - children.add(GestureDetector( - onTap: _handleTap, - onPanDown: _handlePanDown, - onPanEnd: _handlePanEnd, - onPanUpdate: _handlePanUpdate, - behavior: HitTestBehavior.opaque, - excludeFromSemantics: true, - child: IgnorePointer( - ignoring: isSelectMode, - key: _ignorePointerKey, - ignoringSemantics: false, - child: widget.child, + return Stack(children: [ + GestureDetector( + onTap: _handleTap, + onPanDown: _handlePanDown, + onPanEnd: _handlePanEnd, + onPanUpdate: _handlePanUpdate, + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + child: IgnorePointer( + ignoring: isSelectMode, + key: _ignorePointerKey, + ignoringSemantics: false, + child: widget.child, + ), ), - )); - if (!isSelectMode && widget.selectButtonBuilder != null) { - children.add(Positioned( - left: _kInspectButtonMargin, - bottom: _kInspectButtonMargin, - child: widget.selectButtonBuilder(context, _handleEnableSelect), - )); - } - children.add(_InspectorOverlay(selection: selection)); - return Stack(children: children); + if (!isSelectMode && widget.selectButtonBuilder != null) + Positioned( + left: _kInspectButtonMargin, + bottom: _kInspectButtonMargin, + child: widget.selectButtonBuilder(context, _handleEnableSelect), + ), + _InspectorOverlay(selection: selection), + ]); } } diff --git a/packages/flutter/test/animation/curves_test.dart b/packages/flutter/test/animation/curves_test.dart index 8318a6ac74..e7f6c1d8f7 100644 --- a/packages/flutter/test/animation/curves_test.dart +++ b/packages/flutter/test/animation/curves_test.dart @@ -105,19 +105,19 @@ void main() { }); List estimateBounds(Curve curve) { - final List values = []; - - values.add(curve.transform(0.0)); - values.add(curve.transform(0.1)); - values.add(curve.transform(0.2)); - values.add(curve.transform(0.3)); - values.add(curve.transform(0.4)); - values.add(curve.transform(0.5)); - values.add(curve.transform(0.6)); - values.add(curve.transform(0.7)); - values.add(curve.transform(0.8)); - values.add(curve.transform(0.9)); - values.add(curve.transform(1.0)); + final List values = [ + curve.transform(0.0), + curve.transform(0.1), + curve.transform(0.2), + curve.transform(0.3), + curve.transform(0.4), + curve.transform(0.5), + curve.transform(0.6), + curve.transform(0.7), + curve.transform(0.8), + curve.transform(0.9), + curve.transform(1.0), + ]; return [ values.reduce(math.min), diff --git a/packages/flutter/test/foundation/diagnostics_json_test.dart b/packages/flutter/test/foundation/diagnostics_json_test.dart index e17b15e267..2a2ab55b66 100644 --- a/packages/flutter/test/foundation/diagnostics_json_test.dart +++ b/packages/flutter/test/foundation/diagnostics_json_test.dart @@ -246,16 +246,13 @@ class TestTree extends Object with DiagnosticableTreeMixin { final DiagnosticsTreeStyle style; @override - List debugDescribeChildren() { - final List children = []; - for (TestTree child in this.children) { - children.add(child.toDiagnosticsNode( + List debugDescribeChildren() => [ + for (TestTree child in children) + child.toDiagnosticsNode( name: 'child ${child.name}', style: child.style, - )); - } - return children; - } + ), + ]; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { diff --git a/packages/flutter/test/foundation/diagnostics_test.dart b/packages/flutter/test/foundation/diagnostics_test.dart index e340a946ac..496c998f27 100644 --- a/packages/flutter/test/foundation/diagnostics_test.dart +++ b/packages/flutter/test/foundation/diagnostics_test.dart @@ -22,16 +22,13 @@ class TestTree extends Object with DiagnosticableTreeMixin { final DiagnosticsTreeStyle style; @override - List debugDescribeChildren() { - final List children = []; - for (TestTree child in this.children) { - children.add(child.toDiagnosticsNode( + List debugDescribeChildren() => [ + for (TestTree child in children) + child.toDiagnosticsNode( name: 'child ${child.name}', style: child.style, - )); - } - return children; - } + ), + ]; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { diff --git a/packages/flutter/test/material/dropdown_test.dart b/packages/flutter/test/material/dropdown_test.dart index 7e823ae4dc..90d9f7e46f 100644 --- a/packages/flutter/test/material/dropdown_test.dart +++ b/packages/flutter/test/material/dropdown_test.dart @@ -371,9 +371,9 @@ void main() { testWidgets('Dropdown screen edges', (WidgetTester tester) async { int value = 4; - final List> items = >[]; - for (int i = 0; i < 20; ++i) - items.add(DropdownMenuItem(value: i, child: Text('$i'))); + final List> items = >[ + for (int i = 0; i < 20; ++i) DropdownMenuItem(value: i, child: Text('$i')), + ]; void handleChanged(int newValue) { value = newValue; diff --git a/packages/flutter/test/painting/image_provider_test.dart b/packages/flutter/test/painting/image_provider_test.dart index e485eec365..76b12e012c 100644 --- a/packages/flutter/test/painting/image_provider_test.dart +++ b/packages/flutter/test/painting/image_provider_test.dart @@ -237,11 +237,11 @@ void main() { }); test('Notifies listeners of chunk events', () async { - final List chunks = []; const int chunkSize = 8; - for (int offset = 0; offset < kTransparentImage.length; offset += chunkSize) { - chunks.add(Uint8List.fromList(kTransparentImage.skip(offset).take(chunkSize).toList())); - } + final List chunks = [ + for (int offset = 0; offset < kTransparentImage.length; offset += chunkSize) + Uint8List.fromList(kTransparentImage.skip(offset).take(chunkSize).toList()), + ]; final Completer imageAvailable = Completer(); final MockHttpClientRequest request = MockHttpClientRequest(); final MockHttpClientResponse response = MockHttpClientResponse(); diff --git a/packages/flutter/test/painting/text_painter_rtl_test.dart b/packages/flutter/test/painting/text_painter_rtl_test.dart index e44cfe09b9..fe019620fa 100644 --- a/packages/flutter/test/painting/text_painter_rtl_test.dart +++ b/packages/flutter/test/painting/text_painter_rtl_test.dart @@ -127,10 +127,11 @@ void main() { // The list is currently in the wrong order (so selection boxes will paint in the wrong order). ); - final List> list = >[]; textSpan = painter.text; - for (int index = 0; index < textSpan.text.length; index += 1) - list.add(painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1))); + final List> list = >[ + for (int index = 0; index < textSpan.text.length; index += 1) + painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1)), + ]; expect(list, const >[ [], // U+202E, non-printing Unicode bidi formatting character [TextBox.fromLTRBD(230.0, 0.0, 240.0, 10.0, TextDirection.rtl)], @@ -390,10 +391,11 @@ void main() { skip: skipExpectsWithKnownBugs, // horizontal offsets are one pixel off in places; vertical offsets are good ); - final List> list = >[]; - for (int index = 0; index < 5+4+5; index += 1) - list.add(painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1))); - print(list); + final List> list = >[ + for (int index = 0; index < 5+4+5; index += 1) + painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1)), + ]; + expect(list, const >[ [TextBox.fromLTRBD(0.0, 8.0, 10.0, 18.0, TextDirection.ltr)], [TextBox.fromLTRBD(10.0, 8.0, 20.0, 18.0, TextDirection.ltr)], diff --git a/packages/flutter/test/rendering/mock_canvas.dart b/packages/flutter/test/rendering/mock_canvas.dart index 21163137a2..af1b94b7d2 100644 --- a/packages/flutter/test/rendering/mock_canvas.dart +++ b/packages/flutter/test/rendering/mock_canvas.dart @@ -444,15 +444,14 @@ class _PathMatcher extends Matcher { return false; } final Path path = object; - final List errors = []; - for (Offset offset in includes) { - if (!path.contains(offset)) - errors.add('Offset $offset should be inside the path, but is not.'); - } - for (Offset offset in excludes) { - if (path.contains(offset)) - errors.add('Offset $offset should be outside the path, but is not.'); - } + final List errors = [ + for (Offset offset in includes) + if (!path.contains(offset)) + 'Offset $offset should be inside the path, but is not.', + for (Offset offset in excludes) + if (path.contains(offset)) + 'Offset $offset should be outside the path, but is not.', + ]; if (errors.isEmpty) return true; matchState[this] = 'Not all the given points were inside or outside the path as expected:\n ${errors.join("\n ")}'; @@ -1458,9 +1457,10 @@ class _FunctionPaintPredicate extends _PaintPredicate { @override String toString() { - final List adjectives = []; - for (int index = 0; index < arguments.length; index += 1) - adjectives.add(arguments[index] != null ? _valueName(arguments[index]) : '...'); + final List adjectives = [ + for (int index = 0; index < arguments.length; index += 1) + arguments[index] != null ? _valueName(arguments[index]) : '...', + ]; return '${_symbolName(symbol)}(${adjectives.join(", ")})'; } } diff --git a/packages/flutter/test/rendering/paragraph_test.dart b/packages/flutter/test/rendering/paragraph_test.dart index 7a07bb9f4c..4fa541ab07 100644 --- a/packages/flutter/test/rendering/paragraph_test.dart +++ b/packages/flutter/test/rendering/paragraph_test.dart @@ -338,10 +338,11 @@ void main() { ); // Fake the render boxes that correspond to the WidgetSpans. We use // RenderParagraph to reduce dependencies this test has. - final List renderBoxes = []; - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); + final List renderBoxes = [ + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + ]; final RenderParagraph paragraph = RenderParagraph( text, @@ -380,14 +381,15 @@ void main() { ); // Fake the render boxes that correspond to the WidgetSpans. We use // RenderParagraph to reduce dependencies this test has. - final List renderBoxes = []; - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); - renderBoxes.add(RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr)); + final List renderBoxes = [ + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), + ]; final RenderParagraph paragraph = RenderParagraph( text, diff --git a/packages/flutter/test/semantics/semantics_test.dart b/packages/flutter/test/semantics/semantics_test.dart index cd24659ccc..ca691634e3 100644 --- a/packages/flutter/test/semantics/semantics_test.dart +++ b/packages/flutter/test/semantics/semantics_test.dart @@ -263,10 +263,9 @@ void main() { ]; final List expectedResults = [0, -1, 1, 0]; assert(tests.length == expectedResults.length); - final List results = []; - for (List tuple in tests) { - results.add(tuple[0].compareTo(tuple[1])); - } + final List results = [ + for (List tuple in tests) tuple[0].compareTo(tuple[1]), + ]; expect(results, orderedEquals(expectedResults)); }); @@ -279,10 +278,9 @@ void main() { ]; final List expectedResults = [0, -1, 1, 0]; assert(tests.length == expectedResults.length); - final List results = []; - for (List tuple in tests) { - results.add(tuple[0].compareTo(tuple[1])); - } + final List results = [ + for (List tuple in tests) tuple[0].compareTo(tuple[1]), + ]; expect(results, orderedEquals(expectedResults)); }); diff --git a/packages/flutter/test/widgets/custom_painter_test.dart b/packages/flutter/test/widgets/custom_painter_test.dart index 9294acb6f4..30ba455655 100644 --- a/packages/flutter/test/widgets/custom_painter_test.dart +++ b/packages/flutter/test/widgets/custom_painter_test.dart @@ -708,21 +708,17 @@ class _DiffTester { final SemanticsTester semanticsTester = SemanticsTester(tester); TestSemantics createExpectations(List labels) { - final List children = []; - for (String label in labels) { - children.add( - TestSemantics( - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - label: label, - ), - ); - } - return TestSemantics.root( children: [ TestSemantics.rootChild( rect: TestSemantics.fullScreen, - children: children, + children: [ + for (String label in labels) + TestSemantics( + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + label: label, + ), + ], ), ], ); diff --git a/packages/flutter/test/widgets/reparent_state_harder_test.dart b/packages/flutter/test/widgets/reparent_state_harder_test.dart index 64bf479e0f..9d9e7a8bbf 100644 --- a/packages/flutter/test/widgets/reparent_state_harder_test.dart +++ b/packages/flutter/test/widgets/reparent_state_harder_test.dart @@ -29,17 +29,17 @@ class OrderSwitcherState extends State { @override Widget build(BuildContext context) { - final List children = []; - if (_aFirst) { - children.add(KeyedSubtree(child: widget.a)); - children.add(widget.b); - } else { - children.add(KeyedSubtree(child: widget.b)); - children.add(widget.a); - } return Stack( textDirection: TextDirection.ltr, - children: children, + children: _aFirst + ? [ + KeyedSubtree(child: widget.a), + widget.b, + ] + : [ + KeyedSubtree(child: widget.b), + widget.a + ], ); } } diff --git a/packages/flutter/test/widgets/scrollable_animations_test.dart b/packages/flutter/test/widgets/scrollable_animations_test.dart index 1909f38964..109fb4194d 100644 --- a/packages/flutter/test/widgets/scrollable_animations_test.dart +++ b/packages/flutter/test/widgets/scrollable_animations_test.dart @@ -8,15 +8,12 @@ import 'package:flutter/widgets.dart'; void main() { testWidgets('Does not animate if already at target position', (WidgetTester tester) async { - final List textWidgets = []; - for (int i = 0; i < 80; i++) - textWidgets.add(Text('$i', textDirection: TextDirection.ltr)); final ScrollController controller = ScrollController(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( - children: textWidgets, + children: List.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), controller: controller, ), ), @@ -31,15 +28,12 @@ void main() { }); testWidgets('Does not animate if already at target position within tolerance', (WidgetTester tester) async { - final List textWidgets = []; - for (int i = 0; i < 80; i++) - textWidgets.add(Text('$i', textDirection: TextDirection.ltr)); final ScrollController controller = ScrollController(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( - children: textWidgets, + children: List.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), controller: controller, ), ), @@ -57,15 +51,12 @@ void main() { }); testWidgets('Animates if going to a position outside of tolerance', (WidgetTester tester) async { - final List textWidgets = []; - for (int i = 0; i < 80; i++) - textWidgets.add(Text('$i', textDirection: TextDirection.ltr)); final ScrollController controller = ScrollController(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( - children: textWidgets, + children: List.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), controller: controller, ), ), diff --git a/packages/flutter/test/widgets/scrollable_dispose_test.dart b/packages/flutter/test/widgets/scrollable_dispose_test.dart index e0d01ffa2c..9eeb416358 100644 --- a/packages/flutter/test/widgets/scrollable_dispose_test.dart +++ b/packages/flutter/test/widgets/scrollable_dispose_test.dart @@ -11,14 +11,11 @@ import 'test_widgets.dart'; void main() { testWidgets('simultaneously dispose a widget and end the scroll animation', (WidgetTester tester) async { - final List textWidgets = []; - for (int i = 0; i < 250; i++) - textWidgets.add(Text('$i')); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: FlipWidget( - left: ListView(children: textWidgets), + left: ListView(children: List.generate(250, (int i) => Text('$i'))), right: Container(), ), ), diff --git a/packages/flutter/test/widgets/scrollable_fling_test.dart b/packages/flutter/test/widgets/scrollable_fling_test.dart index 6e92cce8a1..3c439dbfff 100644 --- a/packages/flutter/test/widgets/scrollable_fling_test.dart +++ b/packages/flutter/test/widgets/scrollable_fling_test.dart @@ -59,14 +59,16 @@ void main() { testWidgets('fling and tap to stop', (WidgetTester tester) async { final List log = []; - - final List textWidgets = []; - for (int i = 0; i < 250; i += 1) - textWidgets.add(GestureDetector(onTap: () { log.add('tap $i'); }, child: Text('$i', style: testFont))); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView(children: textWidgets, dragStartBehavior: DragStartBehavior.down), + child: ListView( + dragStartBehavior: DragStartBehavior.down, + children: List.generate(250, (int i) => GestureDetector( + onTap: () { log.add('tap $i'); }, + child: Text('$i', style: testFont), + )), + ), ), ); @@ -87,14 +89,16 @@ void main() { testWidgets('fling and wait and tap', (WidgetTester tester) async { final List log = []; - - final List textWidgets = []; - for (int i = 0; i < 250; i += 1) - textWidgets.add(GestureDetector(onTap: () { log.add('tap $i'); }, child: Text('$i', style: testFont))); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView(children: textWidgets, dragStartBehavior: DragStartBehavior.down), + child: ListView( + dragStartBehavior: DragStartBehavior.down, + children: List.generate(250, (int i) => GestureDetector( + onTap: () { log.add('tap $i'); }, + child: Text('$i', style: testFont), + )), + ), ), ); diff --git a/packages/flutter/test/widgets/scrollable_semantics_test.dart b/packages/flutter/test/widgets/scrollable_semantics_test.dart index c5e61d709d..fcfa818a44 100644 --- a/packages/flutter/test/widgets/scrollable_semantics_test.dart +++ b/packages/flutter/test/widgets/scrollable_semantics_test.dart @@ -21,14 +21,10 @@ void main() { testWidgets('scrollable exposes the correct semantic actions', (WidgetTester tester) async { semantics = SemanticsTester(tester); - - final List textWidgets = []; - for (int i = 0; i < 80; i++) - textWidgets.add(Text('$i')); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView(children: textWidgets), + child: ListView(children: List.generate(80, (int i) => Text('$i'))), ), ); @@ -54,12 +50,12 @@ void main() { const double kItemHeight = 40.0; - final List containers = []; - for (int i = 0; i < 80; i++) - containers.add(MergeSemantics(child: Container( + final List containers = List.generate(80, (int i) => MergeSemantics( + child: Container( height: kItemHeight, child: Text('container $i', textDirection: TextDirection.ltr), - ))); + ), + )); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, @@ -93,12 +89,12 @@ void main() { const double kItemHeight = 100.0; const double kExpandedAppBarHeight = 56.0; - final List containers = []; - for (int i = 0; i < 80; i++) - containers.add(MergeSemantics(child: Container( + final List containers = List.generate(80, (int i) => MergeSemantics( + child: Container( height: kItemHeight, child: Text('container $i'), - ))); + ), + )); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, @@ -219,12 +215,9 @@ void main() { testWidgets('correct scrollProgress', (WidgetTester tester) async { semantics = SemanticsTester(tester); - final List textWidgets = []; - for (int i = 0; i < 80; i++) - textWidgets.add(Text('$i')); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, - child: ListView(children: textWidgets), + child: ListView(children: List.generate(80, (int i) => Text('$i'))), )); expect(semantics, includesNodeWith( @@ -315,12 +308,10 @@ void main() { testWidgets('Semantics tree is populated mid-scroll', (WidgetTester tester) async { semantics = SemanticsTester(tester); - final List children = []; - for (int i = 0; i < 80; i++) - children.add(Container( - child: Text('Item $i'), - height: 40.0, - )); + final List children = List.generate(80, (int i) => Container( + child: Text('Item $i'), + height: 40.0, + )); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, diff --git a/packages/flutter/test/widgets/semantics_tester.dart b/packages/flutter/test/widgets/semantics_tester.dart index 151a6eb131..cacdbf09c3 100644 --- a/packages/flutter/test/widgets/semantics_tester.dart +++ b/packages/flutter/test/widgets/semantics_tester.dart @@ -751,25 +751,17 @@ class _IncludesNodeWith extends Matcher { } String get _configAsString { - final List strings = []; - if (label != null) - strings.add('label "$label"'); - if (value != null) - strings.add('value "$value"'); - if (hint != null) - strings.add('hint "$hint"'); - if (textDirection != null) - strings.add(' (${describeEnum(textDirection)})'); - if (actions != null) - strings.add('actions "${actions.join(', ')}"'); - if (flags != null) - strings.add('flags "${flags.join(', ')}"'); - if (scrollPosition != null) - strings.add('scrollPosition "$scrollPosition"'); - if (scrollExtentMax != null) - strings.add('scrollExtentMax "$scrollExtentMax"'); - if (scrollExtentMin != null) - strings.add('scrollExtentMin "$scrollExtentMin"'); + final List strings = [ + if (label != null) 'label "$label"', + if (value != null) 'value "$value"', + if (hint != null) 'hint "$hint"', + if (textDirection != null) ' (${describeEnum(textDirection)})', + if (actions != null) 'actions "${actions.join(', ')}"', + if (flags != null) 'flags "${flags.join(', ')}"', + if (scrollPosition != null) 'scrollPosition "$scrollPosition"', + if (scrollExtentMax != null) 'scrollExtentMax "$scrollExtentMax"', + if (scrollExtentMin != null) 'scrollExtentMin "$scrollExtentMin"', + ]; return strings.join(', '); } } diff --git a/packages/flutter_driver/lib/src/driver/driver.dart b/packages/flutter_driver/lib/src/driver/driver.dart index 8ad2d7899a..6913720886 100644 --- a/packages/flutter_driver/lib/src/driver/driver.dart +++ b/packages/flutter_driver/lib/src/driver/driver.dart @@ -1123,12 +1123,11 @@ void _unhandledJsonRpcError(dynamic error, dynamic stack) { String _getWebSocketUrl(String url) { Uri uri = Uri.parse(url); - final List pathSegments = []; - // If there's an authentication code (default), we need to add it to our path. - if (uri.pathSegments.isNotEmpty) { - pathSegments.add(uri.pathSegments.first); - } - pathSegments.add('ws'); + final List pathSegments = [ + // If there's an authentication code (default), we need to add it to our path. + if (uri.pathSegments.isNotEmpty) uri.pathSegments.first, + 'ws', + ]; if (uri.scheme == 'http') uri = uri.replace(scheme: 'ws', pathSegments: pathSegments); return uri.toString(); diff --git a/packages/flutter_driver/pubspec.yaml b/packages/flutter_driver/pubspec.yaml index deeef23d96..c52c38319b 100644 --- a/packages/flutter_driver/pubspec.yaml +++ b/packages/flutter_driver/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.0.0-dev.68.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: file: 5.0.10 diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart index 9f33295997..a5fc8c1d74 100644 --- a/packages/flutter_test/lib/src/matchers.dart +++ b/packages/flutter_test/lib/src/matchers.dart @@ -482,93 +482,53 @@ Matcher matchesSemantics({ List customActions, List children, }) { - final List flags = []; - if (hasCheckedState) - flags.add(SemanticsFlag.hasCheckedState); - if (isChecked) - flags.add(SemanticsFlag.isChecked); - if (isSelected) - flags.add(SemanticsFlag.isSelected); - if (isButton) - flags.add(SemanticsFlag.isButton); - if (isTextField) - flags.add(SemanticsFlag.isTextField); - if (isReadOnly) - flags.add(SemanticsFlag.isReadOnly); - if (isFocused) - flags.add(SemanticsFlag.isFocused); - if (hasEnabledState) - flags.add(SemanticsFlag.hasEnabledState); - if (isEnabled) - flags.add(SemanticsFlag.isEnabled); - if (isInMutuallyExclusiveGroup) - flags.add(SemanticsFlag.isInMutuallyExclusiveGroup); - if (isHeader) - flags.add(SemanticsFlag.isHeader); - if (isObscured) - flags.add(SemanticsFlag.isObscured); - if (isMultiline) - flags.add(SemanticsFlag.isMultiline); - if (namesRoute) - flags.add(SemanticsFlag.namesRoute); - if (scopesRoute) - flags.add(SemanticsFlag.scopesRoute); - if (isHidden) - flags.add(SemanticsFlag.isHidden); - if (isImage) - flags.add(SemanticsFlag.isImage); - if (isLiveRegion) - flags.add(SemanticsFlag.isLiveRegion); - if (hasToggledState) - flags.add(SemanticsFlag.hasToggledState); - if (isToggled) - flags.add(SemanticsFlag.isToggled); - if (hasImplicitScrolling) - flags.add(SemanticsFlag.hasImplicitScrolling); + final List flags = [ + if (hasCheckedState) SemanticsFlag.hasCheckedState, + if (isChecked) SemanticsFlag.isChecked, + if (isSelected) SemanticsFlag.isSelected, + if (isButton) SemanticsFlag.isButton, + if (isTextField) SemanticsFlag.isTextField, + if (isReadOnly) SemanticsFlag.isReadOnly, + if (isFocused) SemanticsFlag.isFocused, + if (hasEnabledState) SemanticsFlag.hasEnabledState, + if (isEnabled) SemanticsFlag.isEnabled, + if (isInMutuallyExclusiveGroup) SemanticsFlag.isInMutuallyExclusiveGroup, + if (isHeader) SemanticsFlag.isHeader, + if (isObscured) SemanticsFlag.isObscured, + if (isMultiline) SemanticsFlag.isMultiline, + if (namesRoute) SemanticsFlag.namesRoute, + if (scopesRoute) SemanticsFlag.scopesRoute, + if (isHidden) SemanticsFlag.isHidden, + if (isImage) SemanticsFlag.isImage, + if (isLiveRegion) SemanticsFlag.isLiveRegion, + if (hasToggledState) SemanticsFlag.hasToggledState, + if (isToggled) SemanticsFlag.isToggled, + if (hasImplicitScrolling) SemanticsFlag.hasImplicitScrolling, + ]; - final List actions = []; - if (hasTapAction) - actions.add(SemanticsAction.tap); - if (hasLongPressAction) - actions.add(SemanticsAction.longPress); - if (hasScrollLeftAction) - actions.add(SemanticsAction.scrollLeft); - if (hasScrollRightAction) - actions.add(SemanticsAction.scrollRight); - if (hasScrollUpAction) - actions.add(SemanticsAction.scrollUp); - if (hasScrollDownAction) - actions.add(SemanticsAction.scrollDown); - if (hasIncreaseAction) - actions.add(SemanticsAction.increase); - if (hasDecreaseAction) - actions.add(SemanticsAction.decrease); - if (hasShowOnScreenAction) - actions.add(SemanticsAction.showOnScreen); - if (hasMoveCursorForwardByCharacterAction) - actions.add(SemanticsAction.moveCursorForwardByCharacter); - if (hasMoveCursorBackwardByCharacterAction) - actions.add(SemanticsAction.moveCursorBackwardByCharacter); - if (hasSetSelectionAction) - actions.add(SemanticsAction.setSelection); - if (hasCopyAction) - actions.add(SemanticsAction.copy); - if (hasCutAction) - actions.add(SemanticsAction.cut); - if (hasPasteAction) - actions.add(SemanticsAction.paste); - if (hasDidGainAccessibilityFocusAction) - actions.add(SemanticsAction.didGainAccessibilityFocus); - if (hasDidLoseAccessibilityFocusAction) - actions.add(SemanticsAction.didLoseAccessibilityFocus); - if (customActions != null && customActions.isNotEmpty) - actions.add(SemanticsAction.customAction); - if (hasDismissAction) - actions.add(SemanticsAction.dismiss); - if (hasMoveCursorForwardByWordAction) - actions.add(SemanticsAction.moveCursorForwardByWord); - if (hasMoveCursorBackwardByWordAction) - actions.add(SemanticsAction.moveCursorBackwardByWord); + final List actions = [ + if (hasTapAction) SemanticsAction.tap, + if (hasLongPressAction) SemanticsAction.longPress, + if (hasScrollLeftAction) SemanticsAction.scrollLeft, + if (hasScrollRightAction) SemanticsAction.scrollRight, + if (hasScrollUpAction) SemanticsAction.scrollUp, + if (hasScrollDownAction) SemanticsAction.scrollDown, + if (hasIncreaseAction) SemanticsAction.increase, + if (hasDecreaseAction) SemanticsAction.decrease, + if (hasShowOnScreenAction) SemanticsAction.showOnScreen, + if (hasMoveCursorForwardByCharacterAction) SemanticsAction.moveCursorForwardByCharacter, + if (hasMoveCursorBackwardByCharacterAction) SemanticsAction.moveCursorBackwardByCharacter, + if (hasSetSelectionAction) SemanticsAction.setSelection, + if (hasCopyAction) SemanticsAction.copy, + if (hasCutAction) SemanticsAction.cut, + if (hasPasteAction) SemanticsAction.paste, + if (hasDidGainAccessibilityFocusAction) SemanticsAction.didGainAccessibilityFocus, + if (hasDidLoseAccessibilityFocusAction) SemanticsAction.didLoseAccessibilityFocus, + if (customActions != null && customActions.isNotEmpty) SemanticsAction.customAction, + if (hasDismissAction) SemanticsAction.dismiss, + if (hasMoveCursorForwardByWordAction) SemanticsAction.moveCursorForwardByWord, + if (hasMoveCursorBackwardByWordAction) SemanticsAction.moveCursorBackwardByWord, + ]; SemanticsHintOverrides hintOverrides; if (onTapHint != null || onLongPressHint != null) hintOverrides = SemanticsHintOverrides( @@ -1883,11 +1843,11 @@ class _MatchesSemanticsData extends Matcher { for (SemanticsAction action in actions) actionBits |= action.index; if (actionBits != data.actions) { - final List actionSummary = []; - for (SemanticsAction action in SemanticsAction.values.values) { - if ((data.actions & action.index) != 0) - actionSummary.add(describeEnum(action)); - } + final List actionSummary = [ + for (SemanticsAction action in SemanticsAction.values.values) + if ((data.actions & action.index) != 0) + describeEnum(action), + ]; return failWithDescription(matchState, 'actions were: $actionSummary'); } } @@ -1917,11 +1877,11 @@ class _MatchesSemanticsData extends Matcher { for (SemanticsFlag flag in flags) flagBits |= flag.index; if (flagBits != data.flags) { - final List flagSummary = []; - for (SemanticsFlag flag in SemanticsFlag.values.values) { - if ((data.flags & flag.index) != 0) - flagSummary.add(describeEnum(flag)); - } + final List flagSummary = [ + for (SemanticsFlag flag in SemanticsFlag.values.values) + if ((data.flags & flag.index) != 0) + describeEnum(flag), + ]; return failWithDescription(matchState, 'flags were: $flagSummary'); } } diff --git a/packages/flutter_test/lib/src/test_async_utils.dart b/packages/flutter_test/lib/src/test_async_utils.dart index 36fe871d80..4ca0b3c383 100644 --- a/packages/flutter_test/lib/src/test_async_utils.dart +++ b/packages/flutter_test/lib/src/test_async_utils.dart @@ -185,9 +185,10 @@ class TestAsyncUtils { assert(candidateScope.zone != null); } while (candidateScope.zone != zone); assert(scope != null); - final List information = []; - information.add(ErrorSummary('Guarded function conflict.')); - information.add(ErrorHint('You must use "await" with all Future-returning test APIs.')); + final List information = [ + ErrorSummary('Guarded function conflict.'), + ErrorHint('You must use "await" with all Future-returning test APIs.'), + ]; final _StackEntry originalGuarder = _findResponsibleMethod(scope.creationStack, 'guard', information); final _StackEntry collidingGuarder = _findResponsibleMethod(StackTrace.current, 'guardSync', information); if (originalGuarder != null && collidingGuarder != null) { diff --git a/packages/flutter_tools/lib/src/android/android_sdk.dart b/packages/flutter_tools/lib/src/android/android_sdk.dart index cd04804893..b84c89d92e 100644 --- a/packages/flutter_tools/lib/src/android/android_sdk.dart +++ b/packages/flutter_tools/lib/src/android/android_sdk.dart @@ -73,11 +73,10 @@ String getAvdPath() { final List searchPaths = [ platform.environment['ANDROID_AVD_HOME'], + if (platform.environment['HOME'] != null) + fs.path.join(platform.environment['HOME'], '.android', 'avd'), ]; - if (platform.environment['HOME'] != null) { - searchPaths.add(fs.path.join(platform.environment['HOME'], '.android', 'avd')); - } if (platform.isWindows) { final String homeDrive = platform.environment['HOMEDRIVE']; diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index 180312e32a..84523c3a32 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -236,13 +236,13 @@ Future _readGradleProject({bool isLibrary = false}) async { // flavors and build types defined in the project. If gradle fails, then check if the failure is due to t try { final RunResult propertiesRunResult = await processUtils.run( - [gradlew, isLibrary ? 'properties' : 'app:properties'], + [gradlew, if (isLibrary) 'properties' else 'app:properties'], throwOnError: true, workingDirectory: hostAppGradleRoot.path, environment: _gradleEnv, ); final RunResult tasksRunResult = await processUtils.run( - [gradlew, isLibrary ? 'tasks': 'app:tasks', '--all', '--console=auto'], + [gradlew, if (isLibrary) 'tasks' else 'app:tasks', '--all', '--console=auto'], throwOnError: true, workingDirectory: hostAppGradleRoot.path, environment: _gradleEnv, diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart index 0e066e4929..ad312dc77b 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart @@ -418,11 +418,10 @@ DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) { ..sort(_byBasename); for (_Asset main in sortedKeys) { - final List variants = []; - for (_Asset variant in assetVariants[main]) { - variants.add(variant.entryUri.path); - } - jsonObject[main.entryUri.path] = variants; + jsonObject[main.entryUri.path] = [ + for (_Asset variant in assetVariants[main]) + variant.entryUri.path, + ]; } return DevFSStringContent(json.encode(jsonObject)); } diff --git a/packages/flutter_tools/lib/src/base/os.dart b/packages/flutter_tools/lib/src/base/os.dart index c624aadc1a..56b719b67b 100644 --- a/packages/flutter_tools/lib/src/base/os.dart +++ b/packages/flutter_tools/lib/src/base/os.dart @@ -142,11 +142,11 @@ class _PosixUtils extends OperatingSystemUtils { @override List _which(String execName, { bool all = false }) { - final List command = ['which']; - if (all) { - command.add('-a'); - } - command.add(execName); + final List command = [ + 'which', + if (all) '-a', + execName, + ]; final ProcessResult result = processManager.runSync(command); if (result.exitCode != 0) { return const []; diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 0da7ca3060..b79efb64ac 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -191,7 +191,7 @@ class CreateCommand extends FlutterCommand { } bool exists(List path) { - return fs.directory(fs.path.joinAll([projectDir.absolute.path] + path)).existsSync(); + return fs.directory(fs.path.joinAll([projectDir.absolute.path, ...path])).existsSync(); } // If it exists, the project type in the metadata is definitive. diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index afc49ce0be..1dd4954bd7 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -705,15 +705,11 @@ class DeviceDomain extends Domain { /// Return a list of the current devices, with each device represented as a map /// of properties (id, name, platform, ...). Future>> getDevices([ Map args ]) async { - final List> devicesInfo = >[]; - - for (PollingDeviceDiscovery discoverer in _discoverers) { - for (Device device in await discoverer.devices) { - devicesInfo.add(await _deviceToMap(device)); - } - } - - return devicesInfo; + return >[ + for (PollingDeviceDiscovery discoverer in _discoverers) + for (Device device in await discoverer.devices) + await _deviceToMap(device), + ]; } /// Enable device events. diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 44d20cfd61..de3f38f3c4 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -225,14 +225,12 @@ class RunCommand extends RunCommandBase { final String modeName = getBuildInfo().modeName; final AndroidProject androidProject = FlutterProject.current().android; final IosProject iosProject = FlutterProject.current().ios; - final List hostLanguage = []; - - if (androidProject != null && androidProject.existsSync()) { - hostLanguage.add(androidProject.isKotlin ? 'kotlin' : 'java'); - } - if (iosProject != null && iosProject.exists) { - hostLanguage.add(await iosProject.isSwift ? 'swift' : 'objc'); - } + final List hostLanguage = [ + if (androidProject != null && androidProject.existsSync()) + if (androidProject.isKotlin) 'kotlin' else 'java', + if (iosProject != null && iosProject.exists) + if (await iosProject.isSwift) 'swift' else 'objc', + ]; return { CustomDimensions.commandRunIsEmulator: '$isEmulator', @@ -400,22 +398,21 @@ class RunCommand extends RunCommandBase { argResults[FlutterOptions.kEnableExperiment].isNotEmpty) { expFlags = argResults[FlutterOptions.kEnableExperiment]; } - final List flutterDevices = []; final FlutterProject flutterProject = FlutterProject.current(); - for (Device device in devices) { - final FlutterDevice flutterDevice = await FlutterDevice.create( - device, - flutterProject: flutterProject, - trackWidgetCreation: argResults['track-widget-creation'], - fileSystemRoots: argResults['filesystem-root'], - fileSystemScheme: argResults['filesystem-scheme'], - viewFilter: argResults['isolate-filter'], - experimentalFlags: expFlags, - target: argResults['target'], - buildMode: getBuildMode(), - ); - flutterDevices.add(flutterDevice); - } + final List flutterDevices = [ + for (Device device in devices) + await FlutterDevice.create( + device, + flutterProject: flutterProject, + trackWidgetCreation: argResults['track-widget-creation'], + fileSystemRoots: argResults['filesystem-root'], + fileSystemScheme: argResults['filesystem-scheme'], + viewFilter: argResults['isolate-filter'], + experimentalFlags: expFlags, + target: argResults['target'], + buildMode: getBuildMode(), + ), + ]; // Only support "web mode" with a single web device due to resident runner // refactoring required otherwise. final bool webMode = featureFlags.isWebEnabled && @@ -490,12 +487,16 @@ class RunCommand extends RunCommandBase { return FlutterCommandResult( ExitStatus.success, timingLabelParts: [ - hotMode ? 'hot' : 'cold', + if (hotMode) 'hot' else 'cold', getModeName(getBuildMode()), - devices.length == 1 - ? getNameForTargetPlatform(await devices[0].targetPlatform) - : 'multiple', - devices.length == 1 && await devices[0].isLocalEmulator ? 'emulator' : null, + if (devices.length == 1) + getNameForTargetPlatform(await devices[0].targetPlatform) + else + 'multiple', + if (devices.length == 1 && await devices[0].isLocalEmulator) + 'emulator' + else + null, ], endTimeOverride: appStartedTime, ); diff --git a/packages/flutter_tools/lib/src/compile.dart b/packages/flutter_tools/lib/src/compile.dart index 3b5258bdf7..fff12c13dd 100644 --- a/packages/flutter_tools/lib/src/compile.dart +++ b/packages/flutter_tools/lib/src/compile.dart @@ -270,6 +270,10 @@ class KernelCompiler { if (!processManager.canRun(engineDartPath)) { throwToolExit('Unable to find Dart binary at $engineDartPath'); } + Uri mainUri; + if (packagesPath != null) { + mainUri = PackageUriMapper.findUri(mainPath, packagesPath, fileSystemScheme, fileSystemRoots); + } final List command = [ engineDartPath, frontendServer, @@ -277,55 +281,50 @@ class KernelCompiler { sdkRoot, '--strong', '--target=$targetModel', + if (trackWidgetCreation) '--track-widget-creation', + if (!linkPlatformKernelIn) '--no-link-platform', + if (aot) ...[ + '--aot', + '--tfa', + ], + // If we're not targeting product (release) mode and we're still aot, then + // target profile mode. + if (targetProductVm) + '-Ddart.vm.product=true' + else if (aot) + '-Ddart.vm.profile=true', + if (packagesPath != null) ...[ + '--packages', + packagesPath, + ], + if (outputFilePath != null) ...[ + '--output-dill', + outputFilePath, + ], + if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) ...[ + '--depfile', + depFilePath, + ], + if (fileSystemRoots != null) + for (String root in fileSystemRoots) ...[ + '--filesystem-root', + root, + ], + if (fileSystemScheme != null) ...[ + '--filesystem-scheme', + fileSystemScheme, + ], + if (initializeFromDill != null) ...[ + '--initialize-from-dill', + initializeFromDill, + ], + if (platformDill != null) ...[ + '--platform', + platformDill, + ], + ...?extraFrontEndOptions, + mainUri?.toString() ?? mainPath, ]; - if (trackWidgetCreation) { - command.add('--track-widget-creation'); - } - if (!linkPlatformKernelIn) { - command.add('--no-link-platform'); - } - if (aot) { - command.add('--aot'); - command.add('--tfa'); - } - // If we're not targeting product (release) mode and we're still aot, then - // target profile mode. - if (targetProductVm) { - command.add('-Ddart.vm.product=true'); - } else if (aot) { - command.add('-Ddart.vm.profile=true'); - } - Uri mainUri; - if (packagesPath != null) { - command.addAll(['--packages', packagesPath]); - mainUri = PackageUriMapper.findUri(mainPath, packagesPath, fileSystemScheme, fileSystemRoots); - } - if (outputFilePath != null) { - command.addAll(['--output-dill', outputFilePath]); - } - if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) { - command.addAll(['--depfile', depFilePath]); - } - if (fileSystemRoots != null) { - for (String root in fileSystemRoots) { - command.addAll(['--filesystem-root', root]); - } - } - if (fileSystemScheme != null) { - command.addAll(['--filesystem-scheme', fileSystemScheme]); - } - if (initializeFromDill != null) { - command.addAll(['--initialize-from-dill', initializeFromDill]); - } - if (platformDill != null) { - command.addAll([ '--platform', platformDill]); - } - - if (extraFrontEndOptions != null) { - command.addAll(extraFrontEndOptions); - } - - command.add(mainUri?.toString() ?? mainPath); printTrace(command.join(' ')); final Process server = await processManager @@ -562,36 +561,35 @@ class ResidentCompiler { '--incremental', '--strong', '--target=$_targetModel', + if (outputPath != null) ...[ + '--output-dill', + outputPath, + ], + if (packagesFilePath != null) ...[ + '--packages', + packagesFilePath, + ] else if (_packagesPath != null) ...[ + '--packages', + _packagesPath, + ], + if (_trackWidgetCreation) '--track-widget-creation', + if (_fileSystemRoots != null) + for (String root in _fileSystemRoots) ...[ + '--filesystem-root', + root, + ], + if (_fileSystemScheme != null) ...[ + '--filesystem-scheme', + _fileSystemScheme, + ], + if (_initializeFromDill != null) ...[ + '--initialize-from-dill', + _initializeFromDill, + ], + if (_unsafePackageSerialization == true) '--unsafe-package-serialization', + if ((_experimentalFlags != null) && _experimentalFlags.isNotEmpty) + '--enable-experiment=${_experimentalFlags.join(',')}', ]; - if (outputPath != null) { - command.addAll(['--output-dill', outputPath]); - } - if (packagesFilePath != null) { - command.addAll(['--packages', packagesFilePath]); - } else if (_packagesPath != null) { - command.addAll(['--packages', _packagesPath]); - } - if (_trackWidgetCreation) { - command.add('--track-widget-creation'); - } - if (_fileSystemRoots != null) { - for (String root in _fileSystemRoots) { - command.addAll(['--filesystem-root', root]); - } - } - if (_fileSystemScheme != null) { - command.addAll(['--filesystem-scheme', _fileSystemScheme]); - } - if (_initializeFromDill != null) { - command.addAll(['--initialize-from-dill', _initializeFromDill]); - } - if (_unsafePackageSerialization == true) { - command.add('--unsafe-package-serialization'); - } - if ((_experimentalFlags != null) && _experimentalFlags.isNotEmpty) { - final String expFlags = _experimentalFlags.join(','); - command.add('--enable-experiment=$expFlags'); - } printTrace(command.join(' ')); _server = await processManager.start(command); _server.stdout diff --git a/packages/flutter_tools/lib/src/doctor.dart b/packages/flutter_tools/lib/src/doctor.dart index 3fe5dd392a..35e7d54f7e 100644 --- a/packages/flutter_tools/lib/src/doctor.dart +++ b/packages/flutter_tools/lib/src/doctor.dart @@ -147,22 +147,22 @@ class Doctor { /// Return a list of [ValidatorTask] objects and starts validation on all /// objects in [validators]. - List startValidatorTasks() { - final List tasks = []; - for (DoctorValidator validator in validators) { - // We use an asyncGuard() here to be absolutely certain that - // DoctorValidators do not result in an uncaught exception. Since the - // Future returned by the asyncGuard() is not awaited, we pass an - // onError callback to it and translate errors into ValidationResults. - final Future result = - asyncGuard(validator.validate, - onError: (Object exception, StackTrace stackTrace) { - return ValidationResult.crash(exception, stackTrace); - }); - tasks.add(ValidatorTask(validator, result)); - } - return tasks; - } + List startValidatorTasks() => [ + for (DoctorValidator validator in validators) + ValidatorTask( + validator, + // We use an asyncGuard() here to be absolutely certain that + // DoctorValidators do not result in an uncaught exception. Since the + // Future returned by the asyncGuard() is not awaited, we pass an + // onError callback to it and translate errors into ValidationResults. + asyncGuard( + validator.validate, + onError: (Object exception, StackTrace stackTrace) { + return ValidationResult.crash(exception, stackTrace); + }, + ), + ), + ]; List get workflows { return DoctorValidatorsProvider.instance.workflows; @@ -398,12 +398,13 @@ class GroupedValidator extends DoctorValidator { @override Future validate() async { - final List tasks = []; - for (DoctorValidator validator in subValidators) { - final Future result = - asyncGuard(() => validator.validate()); - tasks.add(ValidatorTask(validator, result)); - } + final List tasks = [ + for (DoctorValidator validator in subValidators) + ValidatorTask( + validator, + asyncGuard(() => validator.validate()), + ), + ]; final List results = []; for (ValidatorTask subValidator in tasks) { diff --git a/packages/flutter_tools/lib/src/emulator.dart b/packages/flutter_tools/lib/src/emulator.dart index 879641e809..5d7fb501ec 100644 --- a/packages/flutter_tools/lib/src/emulator.dart +++ b/packages/flutter_tools/lib/src/emulator.dart @@ -249,15 +249,15 @@ abstract class Emulator { } // Extract emulators information - final List> table = >[]; - for (Emulator emulator in emulators) { - table.add([ - emulator.id ?? '', - emulator.name ?? '', - emulator.manufacturer ?? '', - emulator.platformType?.toString() ?? '', - ]); - } + final List> table = >[ + for (Emulator emulator in emulators) + [ + emulator.id ?? '', + emulator.name ?? '', + emulator.manufacturer ?? '', + emulator.platformType?.toString() ?? '', + ], + ]; // Calculate column widths final List indices = List.generate(table[0].length - 1, (int i) => i); diff --git a/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart b/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart index 03fca09351..2834983324 100644 --- a/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart +++ b/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart @@ -151,7 +151,7 @@ class FuchsiaPM { if (fuchsiaArtifacts.pm == null) { throwToolExit('Fuchsia pm tool not found'); } - final List command = [fuchsiaArtifacts.pm.path] + args; + final List command = [fuchsiaArtifacts.pm.path, ...args]; final RunResult result = await processUtils.run(command); return result.exitCode == 0; } diff --git a/packages/flutter_tools/lib/src/ios/devices.dart b/packages/flutter_tools/lib/src/ios/devices.dart index 803e416a13..883d35fce1 100644 --- a/packages/flutter_tools/lib/src/ios/devices.dart +++ b/packages/flutter_tools/lib/src/ios/devices.dart @@ -47,11 +47,11 @@ class IOSDeploy { bundlePath, '--no-wifi', '--justlaunch', + if (launchArguments.isNotEmpty) ...[ + '--args', + '${launchArguments.join(" ")}', + ], ]; - if (launchArguments.isNotEmpty) { - launchCommand.add('--args'); - launchCommand.add('${launchArguments.join(" ")}'); - } // Push /usr/bin to the front of PATH to pick up default system python, package 'six'. // @@ -303,59 +303,29 @@ class IOSDevice extends Device { } // Step 3: Attempt to install the application on the device. - final List launchArguments = ['--enable-dart-profiling']; - - if (debuggingOptions.startPaused) { - launchArguments.add('--start-paused'); - } - - if (debuggingOptions.disableServiceAuthCodes) { - launchArguments.add('--disable-service-auth-codes'); - } - - if (debuggingOptions.dartFlags.isNotEmpty) { - final String dartFlags = debuggingOptions.dartFlags; - launchArguments.add('--dart-flags="$dartFlags"'); - } - - if (debuggingOptions.useTestFonts) { - launchArguments.add('--use-test-fonts'); - } - - // "--enable-checked-mode" and "--verify-entry-points" should always be - // passed when we launch debug build via "ios-deploy". However, we don't - // pass them if a certain environment variable is set to enable the - // "system_debug_ios" integration test in the CI, which simulates a - // home-screen launch. - if (debuggingOptions.debuggingEnabled && - platform.environment['FLUTTER_TOOLS_DEBUG_WITHOUT_CHECKED_MODE'] != 'true') { - launchArguments.add('--enable-checked-mode'); - launchArguments.add('--verify-entry-points'); - } - - if (debuggingOptions.enableSoftwareRendering) { - launchArguments.add('--enable-software-rendering'); - } - - if (debuggingOptions.skiaDeterministicRendering) { - launchArguments.add('--skia-deterministic-rendering'); - } - - if (debuggingOptions.traceSkia) { - launchArguments.add('--trace-skia'); - } - - if (debuggingOptions.dumpSkpOnShaderCompilation) { - launchArguments.add('--dump-skp-on-shader-compilation'); - } - - if (debuggingOptions.verboseSystemLogs) { - launchArguments.add('--verbose-logging'); - } - - if (platformArgs['trace-startup'] ?? false) { - launchArguments.add('--trace-startup'); - } + final List launchArguments = [ + '--enable-dart-profiling', + if (debuggingOptions.startPaused) '--start-paused', + if (debuggingOptions.disableServiceAuthCodes) '--disable-service-auth-codes', + if (debuggingOptions.dartFlags.isNotEmpty) '--dart-flags="${debuggingOptions.dartFlags}"', + if (debuggingOptions.useTestFonts) '--use-test-fonts', + // "--enable-checked-mode" and "--verify-entry-points" should always be + // passed when we launch debug build via "ios-deploy". However, we don't + // pass them if a certain environment variable is set to enable the + // "system_debug_ios" integration test in the CI, which simulates a + // home-screen launch. + if (debuggingOptions.debuggingEnabled && + platform.environment['FLUTTER_TOOLS_DEBUG_WITHOUT_CHECKED_MODE'] != 'true') ...[ + '--enable-checked-mode', + '--verify-entry-points', + ], + if (debuggingOptions.enableSoftwareRendering) '--enable-software-rendering', + if (debuggingOptions.skiaDeterministicRendering) '--skia-deterministic-rendering', + if (debuggingOptions.traceSkia) '--trace-skia', + if (debuggingOptions.dumpSkpOnShaderCompilation) '--dump-skp-on-shader-compilation', + if (debuggingOptions.verboseSystemLogs) '--verbose-logging', + if (platformArgs['trace-startup'] ?? false) '--trace-startup', + ]; final Status installStatus = logger.startProgress( 'Installing and launching...', diff --git a/packages/flutter_tools/lib/src/ios/ios_emulators.dart b/packages/flutter_tools/lib/src/ios/ios_emulators.dart index 48d40ee7a8..381057c23a 100644 --- a/packages/flutter_tools/lib/src/ios/ios_emulators.dart +++ b/packages/flutter_tools/lib/src/ios/ios_emulators.dart @@ -42,10 +42,12 @@ class IOSEmulator extends Emulator { @override Future launch() async { Future launchSimulator(List additionalArgs) async { - final List args = ['open'] - .followedBy(additionalArgs) - .followedBy(['-a', xcode.getSimulatorPath()]) - .toList(); + final List args = [ + 'open', + ...additionalArgs, + '-a', + xcode.getSimulatorPath(), + ]; final RunResult launchResult = await processUtils.run(args); if (launchResult.exitCode != 0) { diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index 073716a734..8cb5a1e1b3 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -361,30 +361,20 @@ class IOSSimulator extends Device { } // Prepare launch arguments. - final List args = ['--enable-dart-profiling']; - - if (debuggingOptions.debuggingEnabled) { - if (debuggingOptions.buildInfo.isDebug) { - args.addAll([ + final List args = [ + '--enable-dart-profiling', + if (debuggingOptions.debuggingEnabled) ...[ + if (debuggingOptions.buildInfo.isDebug) ...[ '--enable-checked-mode', '--verify-entry-points', - ]); - } - if (debuggingOptions.startPaused) { - args.add('--start-paused'); - } - if (debuggingOptions.disableServiceAuthCodes) { - args.add('--disable-service-auth-codes'); - } - if (debuggingOptions.skiaDeterministicRendering) { - args.add('--skia-deterministic-rendering'); - } - if (debuggingOptions.useTestFonts) { - args.add('--use-test-fonts'); - } - final int observatoryPort = debuggingOptions.observatoryPort ?? 0; - args.add('--observatory-port=$observatoryPort'); - } + ], + if (debuggingOptions.startPaused) '--start-paused', + if (debuggingOptions.disableServiceAuthCodes) '--disable-service-auth-codes', + if (debuggingOptions.skiaDeterministicRendering) '--skia-deterministic-rendering', + if (debuggingOptions.useTestFonts) '--use-test-fonts', + '--observatory-port=${debuggingOptions.observatoryPort ?? 0}', + ] + ]; ProtocolDiscovery observatoryDiscovery; if (debuggingOptions.debuggingEnabled) { diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index 9a9b489b92..bec7601e1f 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -137,10 +137,9 @@ class FlutterDevice { if (vmServices == null || vmServices.isEmpty) { return Future.value(null); } - final List> futures = >[]; - for (VMService service in vmServices) { - futures.add(service.vm.refreshViews(waitForViews: true)); - } + final List> futures = >[ + for (VMService service in vmServices) service.vm.refreshViews(waitForViews: true), + ]; await Future.wait(futures); } @@ -221,16 +220,14 @@ class FlutterDevice { }) { final Uri deviceEntryUri = devFS.baseUri.resolveUri(fs.path.toUri(entryPath)); final Uri devicePackagesUri = devFS.baseUri.resolve('.packages'); - final List>> reports = >>[]; - for (FlutterView view in views) { - final Future> report = view.uiIsolate.reloadSources( - pause: pause, - rootLibUri: deviceEntryUri, - packagesUri: devicePackagesUri, - ); - reports.add(report); - } - return reports; + return >>[ + for (FlutterView view in views) + view.uiIsolate.reloadSources( + pause: pause, + rootLibUri: deviceEntryUri, + packagesUri: devicePackagesUri, + ), + ]; } Future resetAssetDirectory() async { @@ -656,10 +653,9 @@ abstract class ResidentRunner { } Future refreshViews() async { - final List> futures = >[]; - for (FlutterDevice device in flutterDevices) { - futures.add(device.refreshViews()); - } + final List> futures = >[ + for (FlutterDevice device in flutterDevices) device.refreshViews(), + ]; await Future.wait(futures); } @@ -893,10 +889,9 @@ abstract class ResidentRunner { } Future exitApp() async { - final List> futures = >[]; - for (FlutterDevice device in flutterDevices) { - futures.add(device.exitApps()); - } + final List> futures = >[ + for (FlutterDevice device in flutterDevices) device.exitApps(), + ]; await Future.wait(futures); appFinished(); } diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index c577ec29ce..eef1140ca2 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -272,16 +272,14 @@ class HotRunner extends ResidentRunner { Future> _initDevFS() async { final String fsName = fs.path.basename(projectRootPath); - final List devFSUris = []; - for (FlutterDevice device in flutterDevices) { - final Uri uri = await device.setupDevFS( - fsName, - fs.directory(projectRootPath), - packagesFilePath: packagesFilePath, - ); - devFSUris.add(uri); - } - return devFSUris; + return [ + for (FlutterDevice device in flutterDevices) + await device.setupDevFS( + fsName, + fs.directory(projectRootPath), + packagesFilePath: packagesFilePath, + ), + ]; } Future _updateDevFS({ bool fullRestart = false }) async { @@ -350,10 +348,9 @@ class HotRunner extends ResidentRunner { Uri packagesUri, Uri assetsDirectoryUri, ) { - final List> futures = >[]; - for (FlutterView view in device.views) { - futures.add(view.runFromSource(entryUri, packagesUri, assetsDirectoryUri)); - } + final List> futures = >[ + for (FlutterView view in device.views) view.runFromSource(entryUri, packagesUri, assetsDirectoryUri), + ]; final Completer completer = Completer(); Future.wait(futures).whenComplete(() { completer.complete(null); }); return completer.future; @@ -833,18 +830,18 @@ class HotRunner extends ResidentRunner { assert(reassembleViews.isNotEmpty); printTrace('Reassembling application'); bool failedReassemble = false; - final List> futures = >[]; - for (FlutterView view in reassembleViews) { - futures.add(() async { - try { - await view.uiIsolate.flutterReassemble(); - } catch (error) { - failedReassemble = true; - printError('Reassembling ${view.uiIsolate.name} failed: $error'); - return; - } - }()); - } + final List> futures = >[ + for (FlutterView view in reassembleViews) + () async { + try { + await view.uiIsolate.flutterReassemble(); + } catch (error) { + failedReassemble = true; + printError('Reassembling ${view.uiIsolate.name} failed: $error'); + return; + } + }(), + ]; final Future reassembleFuture = Future.wait(futures).then((List values) { }); await reassembleFuture.timeout( const Duration(seconds: 2), diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index 10d1368d6e..a8b55fdf33 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -813,38 +813,26 @@ class FlutterPlatform extends PlatformPlugin { }) { assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable. assert(!startPaused || enableObservatory); - final List command = [executable]; - if (enableObservatory) { - // Some systems drive the _FlutterPlatform class in an unusual way, where - // only one test file is processed at a time, and the operating - // environment hands out specific ports ahead of time in a cooperative - // manner, where we're only allowed to open ports that were given to us in - // advance like this. For those esoteric systems, we have this feature - // whereby you can create _FlutterPlatform with a pair of ports. - // - // I mention this only so that you won't be tempted, as I was, to apply - // the obvious simplification to this code and remove this entire feature. - if (observatoryPort != null) { - command.add('--observatory-port=$observatoryPort'); - } - if (startPaused) { - command.add('--start-paused'); - } - if (disableServiceAuthCodes) { - command.add('--disable-service-auth-codes'); - } - } else { - command.add('--disable-observatory'); - } - if (host.type == InternetAddressType.IPv6) { - command.add('--ipv6'); - } - - if (icudtlPath != null) { - command.add('--icu-data-file-path=$icudtlPath'); - } - - command.addAll([ + final List command = [ + executable, + if (enableObservatory) ...[ + // Some systems drive the _FlutterPlatform class in an unusual way, where + // only one test file is processed at a time, and the operating + // environment hands out specific ports ahead of time in a cooperative + // manner, where we're only allowed to open ports that were given to us in + // advance like this. For those esoteric systems, we have this feature + // whereby you can create _FlutterPlatform with a pair of ports. + // + // I mention this only so that you won't be tempted, as I was, to apply + // the obvious simplification to this code and remove this entire feature. + if (observatoryPort != null) '--observatory-port=$observatoryPort', + if (startPaused) '--start-paused', + if (disableServiceAuthCodes) '--disable-service-auth-codes', + ] + else + '--disable-observatory', + if (host.type == InternetAddressType.IPv6) '--ipv6', + if (icudtlPath != null) '--icu-data-file-path=$icudtlPath', '--enable-checked-mode', '--verify-entry-points', '--enable-software-rendering', @@ -854,7 +842,8 @@ class FlutterPlatform extends PlatformPlugin { '--use-test-fonts', '--packages=$packages', testPath, - ]); + ]; + printTrace(command.join(' ')); // If the FLUTTER_TEST environment variable has been set, then pass it on // for package:flutter_test to handle the value. @@ -869,11 +858,9 @@ class FlutterPlatform extends PlatformPlugin { 'FONTCONFIG_FILE': _fontConfigFile.path, 'SERVER_PORT': serverPort.toString(), 'APP_NAME': flutterProject?.manifest?.appName ?? '', + if (buildTestAssets) + 'UNIT_TEST_ASSETS': fs.path.join(flutterProject?.directory?.path ?? '', 'build', 'unit_test_assets'), }; - if (buildTestAssets) { - environment['UNIT_TEST_ASSETS'] = fs.path.join( - flutterProject?.directory?.path ?? '', 'build', 'unit_test_assets'); - } return processManager.start(command, environment: environment); } diff --git a/packages/flutter_tools/lib/src/web/web_validator.dart b/packages/flutter_tools/lib/src/web/web_validator.dart index 3871d6d2da..a5f03d678d 100644 --- a/packages/flutter_tools/lib/src/web/web_validator.dart +++ b/packages/flutter_tools/lib/src/web/web_validator.dart @@ -15,20 +15,18 @@ class WebValidator extends DoctorValidator { Future validate() async { final String chrome = findChromeExecutable(); final bool canRunChrome = canFindChrome(); - final List messages = []; - if (platform.environment.containsKey(kChromeEnvironment)) { - if (!canRunChrome) { - messages.add(ValidationMessage.hint('$chrome is not executable.')); - } else { - messages.add(ValidationMessage('$kChromeEnvironment = $chrome')); - } - } else { - if (!canRunChrome) { - messages.add(ValidationMessage.hint('$kChromeEnvironment not set')); - } else { - messages.add(ValidationMessage('Chrome at $chrome')); - } - } + final List messages = [ + if (platform.environment.containsKey(kChromeEnvironment)) + if (!canRunChrome) + ValidationMessage.hint('$chrome is not executable.') + else + ValidationMessage('$kChromeEnvironment = $chrome') + else + if (!canRunChrome) + ValidationMessage.hint('$kChromeEnvironment not set') + else + ValidationMessage('Chrome at $chrome'), + ]; if (!canRunChrome) { return ValidationResult( ValidationType.missing, diff --git a/packages/flutter_tools/test/general.shard/commands/create_test.dart b/packages/flutter_tools/test/general.shard/commands/create_test.dart index d1b896a6e9..245d2cb15d 100644 --- a/packages/flutter_tools/test/general.shard/commands/create_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/create_test.dart @@ -1134,17 +1134,14 @@ Future _createProject( return fs.typeSync(fullPath) != FileSystemEntityType.notFound; } - final List failures = []; - for (String path in expectedPaths) { - if (!pathExists(path)) { - failures.add('Path "$path" does not exist.'); - } - } - for (String path in unexpectedPaths) { - if (pathExists(path)) { - failures.add('Path "$path" exists when it shouldn\'t.'); - } - } + final List failures = [ + for (String path in expectedPaths) + if (!pathExists(path)) + 'Path "$path" does not exist.', + for (String path in unexpectedPaths) + if (pathExists(path)) + 'Path "$path" exists when it shouldn\'t.', + ]; expect(failures, isEmpty, reason: failures.join('\n')); } diff --git a/packages/flutter_tools/test/general.shard/commands/doctor_test.dart b/packages/flutter_tools/test/general.shard/commands/doctor_test.dart index c01fe28b6b..12db20eb83 100644 --- a/packages/flutter_tools/test/general.shard/commands/doctor_test.dart +++ b/packages/flutter_tools/test/general.shard/commands/doctor_test.dart @@ -653,9 +653,10 @@ class PassingValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage('A helpful message')); - messages.add(ValidationMessage('A second, somewhat longer helpful message')); + final List messages = [ + ValidationMessage('A helpful message'), + ValidationMessage('A second, somewhat longer helpful message'), + ]; return ValidationResult(ValidationType.installed, messages, statusInfo: 'with statusInfo'); } } @@ -665,10 +666,11 @@ class MissingValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.error('A useful error message')); - messages.add(ValidationMessage('A message that is not an error')); - messages.add(ValidationMessage.hint('A hint message')); + final List messages = [ + ValidationMessage.error('A useful error message'), + ValidationMessage('A message that is not an error'), + ValidationMessage.hint('A hint message'), + ]; return ValidationResult(ValidationType.missing, messages); } } @@ -678,10 +680,11 @@ class NotAvailableValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.error('A useful error message')); - messages.add(ValidationMessage('A message that is not an error')); - messages.add(ValidationMessage.hint('A hint message')); + final List messages = [ + ValidationMessage.error('A useful error message'), + ValidationMessage('A message that is not an error'), + ValidationMessage.hint('A hint message'), + ]; return ValidationResult(ValidationType.notAvailable, messages); } } @@ -691,10 +694,11 @@ class PartialValidatorWithErrors extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.error('An error message indicating partial installation')); - messages.add(ValidationMessage.hint('Maybe a hint will help the user')); - messages.add(ValidationMessage('An extra message with some verbose details')); + final List messages = [ + ValidationMessage.error('An error message indicating partial installation'), + ValidationMessage.hint('Maybe a hint will help the user'), + ValidationMessage('An extra message with some verbose details'), + ]; return ValidationResult(ValidationType.partial, messages); } } @@ -704,9 +708,10 @@ class PartialValidatorWithHintsOnly extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.hint('There is a hint here')); - messages.add(ValidationMessage('But there is no error')); + final List messages = [ + ValidationMessage.hint('There is a hint here'), + ValidationMessage('But there is no error'), + ]; return ValidationResult(ValidationType.partial, messages); } } @@ -744,15 +749,13 @@ class FakeDoctor extends Doctor { @override List get validators { - if (_validators == null) { - _validators = []; - _validators.add(PassingValidator('Passing Validator')); - _validators.add(MissingValidator()); - _validators.add(NotAvailableValidator()); - _validators.add(PartialValidatorWithHintsOnly()); - _validators.add(PartialValidatorWithErrors()); - } - return _validators; + return _validators ??= [ + PassingValidator('Passing Validator'), + MissingValidator(), + NotAvailableValidator(), + PartialValidatorWithHintsOnly(), + PartialValidatorWithErrors(), + ]; } } @@ -761,14 +764,12 @@ class FakePassingDoctor extends Doctor { List _validators; @override List get validators { - if (_validators == null) { - _validators = []; - _validators.add(PassingValidator('Passing Validator')); - _validators.add(PartialValidatorWithHintsOnly()); - _validators.add(PartialValidatorWithErrors()); - _validators.add(PassingValidator('Another Passing Validator')); - } - return _validators; + return _validators ??= [ + PassingValidator('Passing Validator'), + PartialValidatorWithHintsOnly(), + PartialValidatorWithErrors(), + PassingValidator('Another Passing Validator'), + ]; } } @@ -778,11 +779,9 @@ class FakeSinglePassingDoctor extends Doctor { List _validators; @override List get validators { - if (_validators == null) { - _validators = []; - _validators.add(PartialValidatorWithHintsOnly()); - } - return _validators; + return _validators ??= [ + PartialValidatorWithHintsOnly(), + ]; } } @@ -791,14 +790,12 @@ class FakeQuietDoctor extends Doctor { List _validators; @override List get validators { - if (_validators == null) { - _validators = []; - _validators.add(PassingValidator('Passing Validator')); - _validators.add(PassingValidator('Another Passing Validator')); - _validators.add(PassingValidator('Validators are fun')); - _validators.add(PassingValidator('Four score and seven validators ago')); - } - return _validators; + return _validators ??= [ + PassingValidator('Passing Validator'), + PassingValidator('Another Passing Validator'), + PassingValidator('Validators are fun'), + PassingValidator('Four score and seven validators ago'), + ]; } } @@ -861,8 +858,9 @@ class PassingGroupedValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage('A helpful message')); + final List messages = [ + ValidationMessage('A helpful message'), + ]; return ValidationResult(ValidationType.installed, messages); } } @@ -872,8 +870,9 @@ class MissingGroupedValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.error('A useful error message')); + final List messages = [ + ValidationMessage.error('A useful error message'), + ]; return ValidationResult(ValidationType.missing, messages); } } @@ -883,8 +882,9 @@ class PartialGroupedValidator extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage.error('An error message for partial installation')); + final List messages = [ + ValidationMessage.error('An error message for partial installation'), + ]; return ValidationResult(ValidationType.partial, messages); } } @@ -894,8 +894,9 @@ class PassingGroupedValidatorWithStatus extends DoctorValidator { @override Future validate() async { - final List messages = []; - messages.add(ValidationMessage('A different message')); + final List messages = [ + ValidationMessage('A different message'), + ]; return ValidationResult(ValidationType.installed, messages, statusInfo: 'A status message'); } } @@ -905,18 +906,16 @@ class FakeGroupedDoctor extends Doctor { List _validators; @override List get validators { - if (_validators == null) { - _validators = []; - _validators.add(GroupedValidator([ + return _validators ??= [ + GroupedValidator([ PassingGroupedValidator('Category 1'), PassingGroupedValidator('Category 1'), - ])); - _validators.add(GroupedValidator([ + ]), + GroupedValidator([ PassingGroupedValidator('Category 2'), MissingGroupedValidator('Category 2'), - ])); - } - return _validators; + ]), + ]; } } @@ -924,12 +923,12 @@ class FakeGroupedDoctorWithStatus extends Doctor { List _validators; @override List get validators { - _validators ??= [ + return _validators ??= [ GroupedValidator([ PassingGroupedValidator('First validator title'), PassingGroupedValidatorWithStatus('Second validator title'), - ])]; - return _validators; + ]), + ]; } } @@ -937,8 +936,9 @@ class FlutterValidatorDoctor extends Doctor { List _validators; @override List get validators { - _validators ??= [FlutterValidator()]; - return _validators; + return _validators ??= [ + FlutterValidator(), + ]; } } 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 58a3b235f9..fddcd954e3 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 @@ -87,7 +87,7 @@ class SshCommandRunner { if (sshConfigPath != null) ...['-F', sshConfigPath], if (isIpV6Address(address)) - ...['-6', interface.isEmpty ? address : '$address%$interface'] + ...['-6', if (interface.isEmpty) address else '$address%$interface'] else address, command,