From 2e748e8598b3169d5d186b8a4d02e603b62653d0 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 15 Apr 2024 11:06:07 -0500 Subject: [PATCH] Implementing control flow collections (#146601) This pull request aims for improved readability, based on issue #146600. ```dart // before Set _distinctVisibleColors() { final Set distinctVisibleColors = {}; if (top.style != BorderStyle.none) { distinctVisibleColors.add(top.color); } if (right.style != BorderStyle.none) { distinctVisibleColors.add(right.color); } if (bottom.style != BorderStyle.none) { distinctVisibleColors.add(bottom.color); } if (left.style != BorderStyle.none) { distinctVisibleColors.add(left.color); } return distinctVisibleColors; } // after Set _distinctVisibleColors() { return { if (top.style != BorderStyle.none) top.color, if (right.style != BorderStyle.none) right.color, if (bottom.style != BorderStyle.none) bottom.color, if (left.style != BorderStyle.none) left.color, }; } ``` Most of the repo should be covered in this PR (aside from `flutter_tools/`, since there was a lot going on in there). --- .../lib/main.dart | 38 ++++++---------- .../run_verify_binaries_codesigned_tests.dart | 33 ++++++-------- dev/bots/test.dart | 28 +++++------- dev/conductor/core/lib/src/next.dart | 20 ++++----- dev/conductor/core/lib/src/repository.dart | 14 +++--- dev/devicelab/lib/tasks/microbenchmarks.dart | 2 +- .../lib/src/common.dart | 13 +++--- .../lib/demo/calculator/logic.dart | 6 +-- .../cupertino_search_text_field_demo.dart | 14 +++--- .../lib/demos/material/data_table_demo.dart | 12 ++--- dev/tools/examples_smoke_test.dart | 23 +++++----- dev/tools/update_icons.dart | 13 ++---- .../flutter/lib/src/cupertino/dialog.dart | 15 ++----- .../flutter/lib/src/foundation/timeline.dart | 25 ++++------- .../flutter/lib/src/material/menu_anchor.dart | 45 +++++++------------ .../lib/src/material/navigation_drawer.dart | 14 +++--- .../flutter/lib/src/painting/box_border.dart | 41 +++++------------ packages/flutter/lib/src/rendering/table.dart | 22 ++++----- .../flutter/lib/src/services/binding.dart | 23 ++++------ .../lib/src/services/hardware_keyboard.dart | 15 +++---- .../flutter/lib/src/services/spell_check.dart | 19 +++----- .../flutter/lib/src/services/text_input.dart | 11 ++--- packages/flutter/lib/src/widgets/basic.dart | 25 ++++------- .../flutter/lib/src/widgets/drag_target.dart | 17 +++---- .../lib/src/widgets/focus_manager.dart | 44 +++++++----------- .../flutter/lib/src/widgets/framework.dart | 26 +++++------ .../lib/src/widgets/platform_menu_bar.dart | 22 +++------ .../lib/src/widgets/scroll_position.dart | 11 ++--- .../flutter/lib/src/widgets/scrollable.dart | 33 +++++++------- .../lib/src/widgets/selectable_region.dart | 11 ++--- .../flutter/lib/src/widgets/tap_region.dart | 31 +++++-------- packages/flutter/lib/src/widgets/view.dart | 19 ++++---- .../lib/src/widgets/widget_inspector.dart | 33 ++++---------- .../text_selection_toolbar_test.dart | 7 +-- .../spell_check_suggestions_toolbar_test.dart | 19 +++----- .../flutter/test/widgets/slivers_test.dart | 12 ++--- packages/integration_test/lib/common.dart | 14 ++---- 37 files changed, 276 insertions(+), 494 deletions(-) diff --git a/dev/benchmarks/platform_channels_benchmarks/lib/main.dart b/dev/benchmarks/platform_channels_benchmarks/lib/main.dart index 3876d6e1991b..2b43fea20ad9 100644 --- a/dev/benchmarks/platform_channels_benchmarks/lib/main.dart +++ b/dev/benchmarks/platform_channels_benchmarks/lib/main.dart @@ -11,30 +11,20 @@ import 'package:flutter/services.dart'; import 'package:microbenchmarks/common.dart'; List _makeTestBuffer(int size) { - final List answer = []; - for (int i = 0; i < size; ++i) { - switch (i % 9) { - case 0: - answer.add(1); - case 1: - answer.add(math.pow(2, 65)); - case 2: - answer.add(1234.0); - case 3: - answer.add(null); - case 4: - answer.add([1234]); - case 5: - answer.add({'hello': 1234}); - case 6: - answer.add('this is a test'); - case 7: - answer.add(true); - case 8: - answer.add(Uint8List(64)); - } - } - return answer; + return [ + for (int i = 0; i < size; i++) + switch (i % 9) { + 0 => 1, + 1 => math.pow(2, 65), + 2 => 1234.0, + 3 => null, + 4 => [1234], + 5 => {'hello': 1234}, + 6 => 'this is a test', + 7 => true, + _ => Uint8List(64), + }, + ]; } Future _runBasicStandardSmall( diff --git a/dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart b/dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart index 91c96f1b33df..4c4534a8f759 100644 --- a/dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart +++ b/dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart @@ -139,28 +139,21 @@ Future verifyExist( String flutterRoot, {@visibleForTesting ProcessManager processManager = const LocalProcessManager() }) async { - final Set foundFiles = {}; - final String cacheDirectory = path.join(flutterRoot, 'bin', 'cache'); - - for (final String binaryPath - in await findBinaryPaths(cacheDirectory, processManager: processManager)) { - if (binariesWithEntitlements(flutterRoot).contains(binaryPath)) { - foundFiles.add(binaryPath); - } else if (binariesWithoutEntitlements(flutterRoot).contains(binaryPath)) { - foundFiles.add(binaryPath); - } else { - throw Exception( - 'Found unexpected binary in cache: $binaryPath'); - } - } - + final List binaryPaths = await findBinaryPaths( + path.join(flutterRoot, 'bin', 'cache'), + processManager: processManager, + ); final List allExpectedFiles = binariesWithEntitlements(flutterRoot) + binariesWithoutEntitlements(flutterRoot); + final Set foundFiles = { + for (final String binaryPath in binaryPaths) + if (allExpectedFiles.contains(binaryPath)) binaryPath + else throw Exception('Found unexpected binary in cache: $binaryPath'), + }; + if (foundFiles.length < allExpectedFiles.length) { - final List unfoundFiles = allExpectedFiles - .where( - (String file) => !foundFiles.contains(file), - ) - .toList(); + final List unfoundFiles = [ + for (final String file in allExpectedFiles) if (!foundFiles.contains(file)) file, + ]; print( 'Expected binaries not found in cache:\n\n${unfoundFiles.join('\n')}\n\n' 'If this commit is removing binaries from the cache, this test should be fixed by\n' diff --git a/dev/bots/test.dart b/dev/bots/test.dart index cb1dab7cd9d4..cf4cac0f0829 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -913,18 +913,14 @@ Future _runFrameworkTests() async { final Uint8List libappBytes = libapp.content as Uint8List; // bytes decompressed here final String libappStrings = utf8.decode(libappBytes, allowMalformed: true); await runCommand(flutter, ['clean'], workingDirectory: tracingDirectory); - final List results = []; - for (final String pattern in allowed) { - if (!libappStrings.contains(pattern)) { - results.add('When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.'); - } - } - for (final String pattern in disallowed) { - if (libappStrings.contains(pattern)) { - results.add('When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.'); - } - } - return results; + return [ + for (final String pattern in allowed) + if (!libappStrings.contains(pattern)) + 'When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.', + for (final String pattern in disallowed) + if (libappStrings.contains(pattern)) + 'When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.', + ]; } catch (error, stackTrace) { return [ error.toString(), @@ -1332,11 +1328,9 @@ Future _runDartTest(String workingDirectory, { if (collectMetrics) { try { - final List testList = []; - final Map allTestSpecs = test.allTestSpecs; - for (final TestSpecs testSpecs in allTestSpecs.values) { - testList.add(testSpecs.toJson()); - } + final List testList = [ + for (final TestSpecs testSpecs in test.allTestSpecs.values) testSpecs.toJson(), + ]; if (testList.isNotEmpty) { final String testJson = json.encode(testList); final File testResults = fileSystem.file( diff --git a/dev/conductor/core/lib/src/next.dart b/dev/conductor/core/lib/src/next.dart index 1b5669dcc0f8..4c0552c85201 100644 --- a/dev/conductor/core/lib/src/next.dart +++ b/dev/conductor/core/lib/src/next.dart @@ -110,12 +110,10 @@ class NextContext extends Context { break; } - final List unappliedCherrypicks = []; - for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) { - if (!finishedStates.contains(cherrypick.state)) { - unappliedCherrypicks.add(cherrypick); - } - } + final List unappliedCherrypicks = [ + for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) + if (!finishedStates.contains(cherrypick.state)) cherrypick, + ]; if (unappliedCherrypicks.isEmpty) { stdio.printStatus('All engine cherrypicks have been auto-applied by the conductor.\n'); @@ -206,12 +204,10 @@ class NextContext extends Context { ); } - final List unappliedCherrypicks = []; - for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) { - if (!finishedStates.contains(cherrypick.state)) { - unappliedCherrypicks.add(cherrypick); - } - } + final List unappliedCherrypicks = [ + for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) + if (!finishedStates.contains(cherrypick.state)) cherrypick, + ]; if (state.framework.cherrypicks.isEmpty) { stdio.printStatus( diff --git a/dev/conductor/core/lib/src/repository.dart b/dev/conductor/core/lib/src/repository.dart index 26d7514cc60b..87c001735d85 100644 --- a/dev/conductor/core/lib/src/repository.dart +++ b/dev/conductor/core/lib/src/repository.dart @@ -183,15 +183,11 @@ abstract class Repository { workingDirectory: (await checkoutDirectory).path, ); - final List remoteBranches = []; - for (final String line in output.split('\n')) { - final RegExpMatch? match = _lsRemotePattern.firstMatch(line); - if (match != null) { - remoteBranches.add(match.group(1)!); - } - } - - return remoteBranches; + return [ + for (final String line in output.split('\n')) + if (_lsRemotePattern.firstMatch(line) case final RegExpMatch match) + match.group(1)!, + ]; } /// Ensure the repository is cloned to disk and initialized with proper state. diff --git a/dev/devicelab/lib/tasks/microbenchmarks.dart b/dev/devicelab/lib/tasks/microbenchmarks.dart index 8b7a659a3454..aa38ab9a575c 100644 --- a/dev/devicelab/lib/tasks/microbenchmarks.dart +++ b/dev/devicelab/lib/tasks/microbenchmarks.dart @@ -39,8 +39,8 @@ TaskFunction createMicrobenchmarkTask({ if (enableImpeller != null && !enableImpeller) '--no-enable-impeller', '-d', device.deviceId, + benchmarkPath, ]; - options.add(benchmarkPath); return startFlutter( 'run', options: options, 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 fa9e3f5091f9..4af33282ef47 100644 --- a/dev/integration_tests/android_semantics_testing/lib/src/common.dart +++ b/dev/integration_tests/android_semantics_testing/lib/src/common.dart @@ -154,14 +154,11 @@ class AndroidSemanticsNode { if (actions == null) { return const []; } - final List convertedActions = []; - for (final int id in actions) { - final AndroidSemanticsAction? action = AndroidSemanticsAction.deserialize(id); - if (action != null) { - convertedActions.add(action); - } - } - return convertedActions; + return [ + for (final int id in actions) + if (AndroidSemanticsAction.deserialize(id) case final AndroidSemanticsAction action) + action, + ]; } @override diff --git a/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart b/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart index ab409254339e..a90c12869b3a 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart @@ -121,10 +121,8 @@ class CalcExpression { : this([], ExpressionState.Start); CalcExpression.result(FloatToken result) - : _list = [], - state = ExpressionState.Result { - _list.add(result); - } + : _list = [result], + state = ExpressionState.Result; /// The tokens comprising the expression. final List _list; diff --git a/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart b/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart index 611b749c02e9..800af1668d5b 100644 --- a/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart +++ b/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart @@ -84,15 +84,11 @@ class _CupertinoSearchTextFieldDemoState Widget _buildPlatformList() { if (_searchPlatform.isNotEmpty) { - final List tempList = []; - for (int i = 0; i < filteredPlatforms.length; i++) { - if (filteredPlatforms[i] - .toLowerCase() - .contains(_searchPlatform.toLowerCase())) { - tempList.add(filteredPlatforms[i]); - } - } - filteredPlatforms = tempList; + final String search = _searchPlatform.toLowerCase(); + filteredPlatforms = [ + for (final String platform in filteredPlatforms) + if (platform.toLowerCase().contains(search)) platform + ]; } return ListView.builder( itemCount: filteredPlatforms.length, diff --git a/dev/integration_tests/new_gallery/lib/demos/material/data_table_demo.dart b/dev/integration_tests/new_gallery/lib/demos/material/data_table_demo.dart index d88ca630c430..ad4c46e6de30 100644 --- a/dev/integration_tests/new_gallery/lib/demos/material/data_table_demo.dart +++ b/dev/integration_tests/new_gallery/lib/demos/material/data_table_demo.dart @@ -26,14 +26,10 @@ class _RestorableDessertSelections extends RestorableProperty> { /// Takes a list of [_Dessert]s and saves the row indices of selected rows /// into a [Set]. void setDessertSelections(List<_Dessert> desserts) { - final Set updatedSet = {}; - for (int i = 0; i < desserts.length; i += 1) { - final _Dessert dessert = desserts[i]; - if (dessert.selected) { - updatedSet.add(i); - } - } - _dessertSelections = updatedSet; + _dessertSelections = { + for (final (int i, _Dessert dessert) in desserts.indexed) + if (dessert.selected) i, + }; notifyListeners(); } diff --git a/dev/tools/examples_smoke_test.dart b/dev/tools/examples_smoke_test.dart index 84660fda3873..8eff94d1b927 100644 --- a/dev/tools/examples_smoke_test.dart +++ b/dev/tools/examples_smoke_test.dart @@ -116,19 +116,18 @@ Future generateTest(Directory apiDir) async { }); // Collect the examples, and import them all as separate symbols. - final List imports = []; - imports.add('''import 'package:flutter/widgets.dart';'''); - imports.add('''import 'package:flutter/scheduler.dart';'''); - imports.add('''import 'package:flutter_test/flutter_test.dart';'''); - imports.add('''import 'package:integration_test/integration_test.dart';'''); - final List infoList = []; - for (final File example in examples) { - final ExampleInfo info = ExampleInfo(example, examplesLibDir); - infoList.add(info); - imports.add('''import 'package:flutter_api_samples/${info.importPath}' as ${info.importName};'''); - } - imports.sort(); + final List infoList = [ + for (final File example in examples) ExampleInfo(example, examplesLibDir), + ]; infoList.sort((ExampleInfo a, ExampleInfo b) => a.importPath.compareTo(b.importPath)); + final List imports = [ + "import 'package:flutter/widgets.dart';", + "import 'package:flutter/scheduler.dart';", + "import 'package:flutter_test/flutter_test.dart';", + "import 'package:integration_test/integration_test.dart';", + for (final ExampleInfo info in infoList) + "import 'package:flutter_api_samples/${info.importPath}' as ${info.importName};" + ]..sort(); final StringBuffer buffer = StringBuffer(); buffer.writeln('// Temporary generated file. Do not commit.'); diff --git a/dev/tools/update_icons.dart b/dev/tools/update_icons.dart index 9d56f540ba95..1007f722407f 100644 --- a/dev/tools/update_icons.dart +++ b/dev/tools/update_icons.dart @@ -388,15 +388,10 @@ bool testIsSuperset(Map newCodepoints, Map oldCo @visibleForTesting bool testIsStable(Map newCodepoints, Map oldCodepoints) { final int oldCodepointsCount = oldCodepoints.length; - final List unstable = []; - - oldCodepoints.forEach((String key, String value) { - if (newCodepoints.containsKey(key)) { - if (value != newCodepoints[key]) { - unstable.add(key); - } - } - }); + final List unstable = [ + for (final MapEntry(:String key, :String value) in oldCodepoints.entries) + if (newCodepoints.containsKey(key) && value != newCodepoints[key]) key, + ]; if (unstable.isNotEmpty) { stderr.writeln('❌ out of $oldCodepointsCount existing codepoints, ${unstable.length} were unstable: $unstable'); diff --git a/packages/flutter/lib/src/cupertino/dialog.dart b/packages/flutter/lib/src/cupertino/dialog.dart index bcbf5cd7e991..8094248164fa 100644 --- a/packages/flutter/lib/src/cupertino/dialog.dart +++ b/packages/flutter/lib/src/cupertino/dialog.dart @@ -1485,22 +1485,15 @@ class _CupertinoAlertActionSection extends StatelessWidget { @override Widget build(BuildContext context) { - - final List interactiveButtons = []; - for (int i = 0; i < children.length; i += 1) { - interactiveButtons.add( - _PressableActionButton( - child: children[i], - ), - ); - } - return CupertinoScrollbar( controller: scrollController, child: SingleChildScrollView( controller: scrollController, child: _CupertinoDialogActionsRenderWidget( - actionButtons: interactiveButtons, + actionButtons: [ + for (final Widget child in children) + _PressableActionButton(child: child), + ], dividerThickness: _kDividerThickness, hasCancelButton: hasCancelButton, isActionSheet: isActionSheet, diff --git a/packages/flutter/lib/src/foundation/timeline.dart b/packages/flutter/lib/src/foundation/timeline.dart index 0f71c362a4e3..f5b2c72a091b 100644 --- a/packages/flutter/lib/src/foundation/timeline.dart +++ b/packages/flutter/lib/src/foundation/timeline.dart @@ -311,12 +311,10 @@ final class _Float64ListChain { /// are read back, they do not affect the timings of the work being /// benchmarked. List extractElements() { - final List result = []; - _chain.forEach(result.addAll); - for (int i = 0; i < _pointer; i++) { - result.add(_slice[i]); - } - return result; + return [ + for (final Float64List list in _chain) ...list, + for (int i = 0; i < _pointer; i++) _slice[i], + ]; } } @@ -349,16 +347,11 @@ final class _StringListChain { /// are read back, they do not affect the timings of the work being /// benchmarked. List extractElements() { - final List result = []; - for (final List slice in _chain) { - for (final String? element in slice) { - result.add(element!); - } - } - for (int i = 0; i < _pointer; i++) { - result.add(_slice[i]!); - } - return result; + return [ + for (final List slice in _chain) + for (final String? value in slice) value!, + for (int i = 0; i < _pointer; i++) _slice[i]!, + ]; } } diff --git a/packages/flutter/lib/src/material/menu_anchor.dart b/packages/flutter/lib/src/material/menu_anchor.dart index 503286e371c9..630b92a859c5 100644 --- a/packages/flutter/lib/src/material/menu_anchor.dart +++ b/packages/flutter/lib/src/material/menu_anchor.dart @@ -2125,37 +2125,22 @@ class _LocalizedShortcutLabeler { keySeparator = '+'; } if (serialized.trigger != null) { - final List modifiers = []; final LogicalKeyboardKey trigger = serialized.trigger!; - if (_usesSymbolicModifiers) { - // macOS/iOS platform convention uses this ordering, with ⌘ always last. - if (serialized.control!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations)); - } - if (serialized.alt!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations)); - } - if (serialized.shift!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations)); - } - if (serialized.meta!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations)); - } - } else { - // These should be in this order, to match the LogicalKeySet version. - if (serialized.alt!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations)); - } - if (serialized.control!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations)); - } - if (serialized.meta!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations)); - } - if (serialized.shift!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations)); - } - } + final List modifiers = [ + if (_usesSymbolicModifiers) ...[ + // MacOS/iOS platform convention uses this ordering, with ⌘ always last. + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.shift!) _getModifierLabel(LogicalKeyboardKey.shift, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + ] else ...[ + // This order matches the LogicalKeySet version. + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + if (serialized.shift!) _getModifierLabel(LogicalKeyboardKey.shift, localizations), + ], + ]; String? shortcutTrigger; final int logicalKeyId = trigger.keyId; if (_shortcutGraphicEquivalents.containsKey(trigger)) { diff --git a/packages/flutter/lib/src/material/navigation_drawer.dart b/packages/flutter/lib/src/material/navigation_drawer.dart index edd9946c9b7c..bc4cd218286d 100644 --- a/packages/flutter/lib/src/material/navigation_drawer.dart +++ b/packages/flutter/lib/src/material/navigation_drawer.dart @@ -141,7 +141,6 @@ class NavigationDrawer extends StatelessWidget { children.whereType().toList().length; int destinationIndex = 0; - final List wrappedChildren = []; Widget wrapChild(Widget child, int index) => _SelectableAnimatedBuilder( duration: const Duration(milliseconds: 500), isSelected: index == selectedIndex, @@ -162,14 +161,11 @@ class NavigationDrawer extends StatelessWidget { ); }); - for (int i = 0; i < children.length; i++) { - if (children[i] is! NavigationDrawerDestination) { - wrappedChildren.add(children[i]); - } else { - wrappedChildren.add(wrapChild(children[i], destinationIndex)); - destinationIndex += 1; - } - } + final List wrappedChildren = [ + for (final Widget child in children) + if (child is! NavigationDrawerDestination) child + else wrapChild(child, destinationIndex++), + ]; final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); return Drawer( diff --git a/packages/flutter/lib/src/painting/box_border.dart b/packages/flutter/lib/src/painting/box_border.dart index 0155ac9deaae..e41e926d0a11 100644 --- a/packages/flutter/lib/src/painting/box_border.dart +++ b/packages/flutter/lib/src/painting/box_border.dart @@ -492,20 +492,12 @@ class Border extends BoxBorder { } Set _distinctVisibleColors() { - final Set distinctVisibleColors = {}; - if (top.style != BorderStyle.none) { - distinctVisibleColors.add(top.color); - } - if (right.style != BorderStyle.none) { - distinctVisibleColors.add(right.color); - } - if (bottom.style != BorderStyle.none) { - distinctVisibleColors.add(bottom.color); - } - if (left.style != BorderStyle.none) { - distinctVisibleColors.add(left.color); - } - return distinctVisibleColors; + return { + if (top.style != BorderStyle.none) top.color, + if (right.style != BorderStyle.none) right.color, + if (bottom.style != BorderStyle.none) bottom.color, + if (left.style != BorderStyle.none) left.color, + }; } // [BoxBorder.paintNonUniformBorder] is about 20% faster than [paintBorder], @@ -840,21 +832,12 @@ class BorderDirectional extends BoxBorder { } Set _distinctVisibleColors() { - final Set distinctVisibleColors = {}; - if (top.style != BorderStyle.none) { - distinctVisibleColors.add(top.color); - } - if (end.style != BorderStyle.none) { - distinctVisibleColors.add(end.color); - } - if (bottom.style != BorderStyle.none) { - distinctVisibleColors.add(bottom.color); - } - if (start.style != BorderStyle.none) { - distinctVisibleColors.add(start.color); - } - - return distinctVisibleColors; + return { + if (top.style != BorderStyle.none) top.color, + if (end.style != BorderStyle.none) end.color, + if (bottom.style != BorderStyle.none) bottom.color, + if (start.style != BorderStyle.none) start.color, + }; } diff --git a/packages/flutter/lib/src/rendering/table.dart b/packages/flutter/lib/src/rendering/table.dart index 442bc5d3a1c2..abe6e4b504a9 100644 --- a/packages/flutter/lib/src/rendering/table.dart +++ b/packages/flutter/lib/src/rendering/table.dart @@ -1260,19 +1260,13 @@ class RenderTable extends RenderBox { return [DiagnosticsNode.message('table is empty')]; } - final List children = []; - for (int y = 0; y < rows; y += 1) { - for (int x = 0; x < columns; x += 1) { - final int xy = x + y * columns; - final RenderBox? child = _children[xy]; - final String name = 'child ($x, $y)'; - if (child != null) { - children.add(child.toDiagnosticsNode(name: name)); - } else { - children.add(DiagnosticsProperty(name, null, ifNull: 'is null', showSeparator: false)); - } - } - } - return children; + return [ + for (int y = 0; y < rows; y += 1) + for (int x = 0; x < columns; x += 1) + if (_children[x + y * columns] case final RenderBox child) + child.toDiagnosticsNode(name: 'child ($x, $y)') + else + DiagnosticsProperty('child ($x, $y)', null, ifNull: 'is null', showSeparator: false), + ]; } } diff --git a/packages/flutter/lib/src/services/binding.dart b/packages/flutter/lib/src/services/binding.dart index e6105ed6537f..14825107a942 100644 --- a/packages/flutter/lib/src/services/binding.dart +++ b/packages/flutter/lib/src/services/binding.dart @@ -205,20 +205,15 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { // This is run in another isolate created by _addLicenses above. static List _parseLicenses(String rawLicenses) { final String licenseSeparator = '\n${'-' * 80}\n'; - final List result = []; - final List licenses = rawLicenses.split(licenseSeparator); - for (final String license in licenses) { - final int split = license.indexOf('\n\n'); - if (split >= 0) { - result.add(LicenseEntryWithLineBreaks( - license.substring(0, split).split('\n'), - license.substring(split + 2), - )); - } else { - result.add(LicenseEntryWithLineBreaks(const [], license)); - } - } - return result; + return [ + for (final String license in rawLicenses.split(licenseSeparator)) + if (license.indexOf('\n\n') case final int split when split >= 0) + LicenseEntryWithLineBreaks( + license.substring(0, split).split('\n'), + license.substring(split + 2), + ) + else LicenseEntryWithLineBreaks(const [], license), + ]; } @override diff --git a/packages/flutter/lib/src/services/hardware_keyboard.dart b/packages/flutter/lib/src/services/hardware_keyboard.dart index 4fea3a7a3670..390c0fe8bb91 100644 --- a/packages/flutter/lib/src/services/hardware_keyboard.dart +++ b/packages/flutter/lib/src/services/hardware_keyboard.dart @@ -625,14 +625,13 @@ class HardwareKeyboard { } List _debugPressedKeysDetails() { - if (_pressedKeys.isEmpty) { - return ['Empty']; - } - final List details = []; - for (final PhysicalKeyboardKey physicalKey in _pressedKeys.keys) { - details.add('$physicalKey: ${_pressedKeys[physicalKey]}'); - } - return details; + return [ + if (_pressedKeys.isEmpty) + 'Empty' + else + for (final PhysicalKeyboardKey physicalKey in _pressedKeys.keys) + '$physicalKey: ${_pressedKeys[physicalKey]}', + ]; } /// Process a new [KeyEvent] by recording the state changes and dispatching diff --git a/packages/flutter/lib/src/services/spell_check.dart b/packages/flutter/lib/src/services/spell_check.dart index 24e36c3754b1..c07e63cd431f 100644 --- a/packages/flutter/lib/src/services/spell_check.dart +++ b/packages/flutter/lib/src/services/spell_check.dart @@ -180,20 +180,13 @@ class DefaultSpellCheckService implements SpellCheckService { return null; } - List suggestionSpans = []; - - for (final dynamic result in rawResults) { - final Map resultMap = - Map.from(result as Map); - suggestionSpans.add( + List suggestionSpans = [ + for (final Map resultMap in rawResults.cast>()) SuggestionSpan( - TextRange( - start: resultMap['startIndex'] as int, - end: resultMap['endIndex'] as int), - (resultMap['suggestions'] as List).cast(), - ) - ); - } + TextRange(start: resultMap['startIndex'] as int, end: resultMap['endIndex'] as int), + (resultMap['suggestions'] as List).cast(), + ), + ]; if (lastSavedResults != null) { // Merge current and previous spell check results if between requests, diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index d133d6857a3d..f46a753e30c8 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -1894,14 +1894,11 @@ class TextInput { TextInput._instance._updateEditingValue(value, exclude: _PlatformTextInputControl.instance); case 'TextInputClient.updateEditingStateWithDeltas': assert(_currentConnection!._client is DeltaTextInputClient, 'You must be using a DeltaTextInputClient if TextInputConfiguration.enableDeltaModel is set to true'); - final List deltas = []; - final Map encoded = args[1] as Map; - - for (final dynamic encodedDelta in encoded['deltas'] as List) { - final TextEditingDelta delta = TextEditingDelta.fromJSON(encodedDelta as Map); - deltas.add(delta); - } + final List deltas = [ + for (final dynamic encodedDelta in encoded['deltas'] as List) + TextEditingDelta.fromJSON(encodedDelta as Map) + ]; (_currentConnection!._client as DeltaTextInputClient).updateEditingValueWithDeltas(deltas); case 'TextInputClient.performAction': diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 92b450ae5221..0e8dd6833189 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -6686,16 +6686,11 @@ class MouseRegion extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final List listeners = []; - if (onEnter != null) { - listeners.add('enter'); - } - if (onExit != null) { - listeners.add('exit'); - } - if (onHover != null) { - listeners.add('hover'); - } + final List listeners = [ + if (onEnter != null) 'enter', + if (onExit != null) 'exit', + if (onHover != null) 'hover', + ]; properties.add(IterableProperty('listeners', listeners, ifEmpty: '')); properties.add(DiagnosticsProperty('cursor', cursor, defaultValue: null)); properties.add(DiagnosticsProperty('opaque', opaque, defaultValue: true)); @@ -7573,12 +7568,10 @@ class KeyedSubtree extends StatelessWidget { return items; } - final List itemsWithUniqueKeys = []; - int itemIndex = baseIndex; - for (final Widget item in items) { - itemsWithUniqueKeys.add(KeyedSubtree.wrap(item, itemIndex)); - itemIndex += 1; - } + final List itemsWithUniqueKeys = [ + for (final (int i, Widget item) in items.indexed) + KeyedSubtree.wrap(item, baseIndex + i), + ]; assert(!debugItemsHaveDuplicateKeys(itemsWithUniqueKeys)); return itemsWithUniqueKeys; diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index c68b8665c973..3aa856f8562d 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -909,17 +909,12 @@ class _DragAvatar extends Drag { Iterable<_DragTargetState> _getDragTargets(Iterable path) { // Look for the RenderBoxes that corresponds to the hit target (the hit target // widgets build RenderMetaData boxes for us for this purpose). - final List<_DragTargetState> targets = <_DragTargetState>[]; - for (final HitTestEntry entry in path) { - final HitTestTarget target = entry.target; - if (target is RenderMetaData) { - final dynamic metaData = target.metaData; - if (metaData is _DragTargetState && metaData.isExpectedDataType(data, T)) { - targets.add(metaData); - } - } - } - return targets; + return <_DragTargetState>[ + for (final HitTestEntry entry in path) + if (entry.target case final RenderMetaData target) + if (target.metaData case final _DragTargetState metaData) + if (metaData.isExpectedDataType(data, T)) metaData, + ]; } void _leaveAllEntered() { diff --git a/packages/flutter/lib/src/widgets/focus_manager.dart b/packages/flutter/lib/src/widgets/focus_manager.dart index 19e6294a5aeb..24ac44e5d3b7 100644 --- a/packages/flutter/lib/src/widgets/focus_manager.dart +++ b/packages/flutter/lib/src/widgets/focus_manager.dart @@ -2035,15 +2035,11 @@ class _HighlightModeManager { // Check to see if any of the early handlers handle the key. If so, then // return early. if (_earlyKeyEventHandlers.isNotEmpty) { - final List results = []; - // Copy the list before iteration to prevent problems if the list gets - // modified during iteration. - final List iterationList = _earlyKeyEventHandlers.toList(); - for (final OnKeyEventCallback callback in iterationList) { - for (final KeyEvent event in message.events) { - results.add(callback(event)); - } - } + final List results = [ + // Make a copy to prevent problems if the list is modified during iteration. + for (final OnKeyEventCallback callback in _earlyKeyEventHandlers.toList()) + for (final KeyEvent event in message.events) callback(event), + ]; final KeyEventResult result = combineKeyEventResults(results); switch (result) { case KeyEventResult.ignored: @@ -2067,15 +2063,13 @@ class _HighlightModeManager { FocusManager.instance.primaryFocus!, ...FocusManager.instance.primaryFocus!.ancestors, ]) { - final List results = []; - if (node.onKeyEvent != null) { - for (final KeyEvent event in message.events) { - results.add(node.onKeyEvent!(node, event)); - } - } - if (node.onKey != null && message.rawEvent != null) { - results.add(node.onKey!(node, message.rawEvent!)); - } + final List results = [ + if (node.onKeyEvent != null) + for (final KeyEvent event in message.events) + node.onKeyEvent!(node, event), + if (node.onKey != null && message.rawEvent != null) + node.onKey!(node, message.rawEvent!), + ]; final KeyEventResult result = combineKeyEventResults(results); switch (result) { case KeyEventResult.ignored: @@ -2095,15 +2089,11 @@ class _HighlightModeManager { // Check to see if any late key event handlers want to handle the event. if (!handled && _lateKeyEventHandlers.isNotEmpty) { - final List results = []; - // Copy the list before iteration to prevent problems if the list gets - // modified during iteration. - final List iterationList = _lateKeyEventHandlers.toList(); - for (final OnKeyEventCallback callback in iterationList) { - for (final KeyEvent event in message.events) { - results.add(callback(event)); - } - } + final List results = [ + // Make a copy to prevent problems if the list is modified during iteration. + for (final OnKeyEventCallback callback in _lateKeyEventHandlers.toList()) + for (final KeyEvent event in message.events) callback(event), + ]; final KeyEventResult result = combineKeyEventResults(results); switch (result) { case KeyEventResult.ignored: diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index f6fd1a087f4d..f45862549b4b 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -3194,14 +3194,11 @@ class BuildOwner { keyStringCount[key] = 1; } } - final List keyLabels = []; - keyStringCount.forEach((String key, int count) { - if (count == 1) { - keyLabels.add(key); - } else { - keyLabels.add('$key ($count different affected keys had this toString representation)'); - } - }); + final List keyLabels = [ + for (final MapEntry(:String key, value: int count) in keyStringCount.entries) + if (count == 1) key + else '$key ($count different affected keys had this toString representation)', + ]; final Iterable elements = _debugElementsThatWillNeedToBeRebuiltDueToGlobalKeyShenanigans!.keys; final Map elementStringCount = HashMap(); for (final String element in elements.map((Element element) => element.toString())) { @@ -3211,14 +3208,11 @@ class BuildOwner { elementStringCount[element] = 1; } } - final List elementLabels = []; - elementStringCount.forEach((String element, int count) { - if (count == 1) { - elementLabels.add(element); - } else { - elementLabels.add('$element ($count different affected elements had this toString representation)'); - } - }); + final List elementLabels = [ + for (final MapEntry(key: String element, value: int count) in elementStringCount.entries) + if (count == 1) element + else '$element ($count different affected elements had this toString representation)', + ]; assert(keyLabels.isNotEmpty); final String the = keys.length == 1 ? ' the' : ''; final String s = keys.length == 1 ? '' : 's'; diff --git a/packages/flutter/lib/src/widgets/platform_menu_bar.dart b/packages/flutter/lib/src/widgets/platform_menu_bar.dart index 687894d37805..4f743816476d 100644 --- a/packages/flutter/lib/src/widgets/platform_menu_bar.dart +++ b/packages/flutter/lib/src/widgets/platform_menu_bar.dart @@ -666,22 +666,12 @@ class PlatformMenuItemGroup extends PlatformMenuItem { PlatformMenuDelegate delegate, { required MenuItemSerializableIdGenerator getId, }) { - final List> result = >[]; - result.add({ - _kIdKey: getId(group), - _kIsDividerKey: true, - }); - for (final PlatformMenuItem item in group.members) { - result.addAll(item.toChannelRepresentation( - delegate, - getId: getId, - )); - } - result.add({ - _kIdKey: getId(group), - _kIsDividerKey: true, - }); - return result; + return >[ + {_kIdKey: getId(group), _kIsDividerKey: true}, + for (final PlatformMenuItem item in group.members) + ...item.toChannelRepresentation(delegate, getId: getId), + {_kIdKey: getId(group), _kIsDividerKey: true}, + ]; } @override diff --git a/packages/flutter/lib/src/widgets/scroll_position.dart b/packages/flutter/lib/src/widgets/scroll_position.dart index 5a995b2feb58..eb6ae9bc67ee 100644 --- a/packages/flutter/lib/src/widgets/scroll_position.dart +++ b/packages/flutter/lib/src/widgets/scroll_position.dart @@ -729,13 +729,10 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { AxisDirection.right => (SemanticsAction.scrollLeft, SemanticsAction.scrollRight), }; - final Set actions = {}; - if (pixels > minScrollExtent) { - actions.add(backward); - } - if (pixels < maxScrollExtent) { - actions.add(forward); - } + final Set actions = { + if (pixels > minScrollExtent) backward, + if (pixels < maxScrollExtent) forward, + }; if (setEquals(actions, _semanticActions)) { return; diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 780c3ed0a48d..74f27b95411a 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -2350,23 +2350,22 @@ class _HorizontalInnerDimensionState extends ScrollableState { ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit, RenderObject? targetRenderObject, }) { - final List> newFutures = >[]; - - newFutures.add(position.ensureVisible( - object, - alignment: alignment, - duration: duration, - curve: curve, - alignmentPolicy: alignmentPolicy, - )); - - newFutures.add(verticalScrollable.position.ensureVisible( - object, - alignment: alignment, - duration: duration, - curve: curve, - alignmentPolicy: alignmentPolicy, - )); + final List> newFutures = >[ + position.ensureVisible( + object, + alignment: alignment, + duration: duration, + curve: curve, + alignmentPolicy: alignmentPolicy, + ), + verticalScrollable.position.ensureVisible( + object, + alignment: alignment, + duration: duration, + curve: curve, + alignmentPolicy: alignmentPolicy, + ), + ]; return (newFutures, verticalScrollable); } diff --git a/packages/flutter/lib/src/widgets/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index 538267f1429d..09f5b35abffd 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart @@ -2213,13 +2213,10 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai /// Copies the selected contents of all [Selectable]s. @override SelectedContent? getSelectedContent() { - final List selections = []; - for (final Selectable selectable in selectables) { - final SelectedContent? data = selectable.getSelectedContent(); - if (data != null) { - selections.add(data); - } - } + final List selections = [ + for (final Selectable selectable in selectables) + if (selectable.getSelectedContent() case final SelectedContent data) data, + ]; if (selections.isEmpty) { return null; } diff --git a/packages/flutter/lib/src/widgets/tap_region.dart b/packages/flutter/lib/src/widgets/tap_region.dart index f4bdf8d89eaa..d00ec9d40841 100644 --- a/packages/flutter/lib/src/widgets/tap_region.dart +++ b/packages/flutter/lib/src/widgets/tap_region.dart @@ -254,18 +254,14 @@ class RenderTapRegionSurface extends RenderProxyBoxWithHitTestBehavior implement // groups of regions that were not hit. final Set hitRegions = _getRegionsHit(_registeredRegions, result.path).cast().toSet(); - final Set insideRegions = {}; assert(_tapRegionDebug('Tap event hit ${hitRegions.length} descendants.')); - for (final RenderTapRegion region in hitRegions) { - if (region.groupId == null) { - insideRegions.add(region); - continue; - } - // Add all grouped regions to the insideRegions so that groups act as a - // single region. - insideRegions.addAll(_groupIdToRegions[region.groupId]!); - } + final Set insideRegions = { + for (final RenderTapRegion region in hitRegions) + if (region.groupId == null) region + // Adding all grouped regions, so they act as a single region. + else ..._groupIdToRegions[region.groupId]!, + }; // If they're not inside, then they're outside. final Set outsideRegions = _registeredRegions.difference(insideRegions); @@ -292,15 +288,12 @@ class RenderTapRegionSurface extends RenderProxyBoxWithHitTestBehavior implement } // Returns the registered regions that are in the hit path. - Iterable _getRegionsHit(Set detectors, Iterable hitTestPath) { - final Set hitRegions = {}; - for (final HitTestEntry entry in hitTestPath) { - final HitTestTarget target = entry.target; - if (_registeredRegions.contains(target)) { - hitRegions.add(target); - } - } - return hitRegions; + Set _getRegionsHit(Set detectors, Iterable hitTestPath) { + return { + for (final HitTestEntry entry in hitTestPath) + if (entry.target case final HitTestTarget target) + if (_registeredRegions.contains(target)) target, + }; } } diff --git a/packages/flutter/lib/src/widgets/view.dart b/packages/flutter/lib/src/widgets/view.dart index ad7ab7f7aaff..728a09d46973 100644 --- a/packages/flutter/lib/src/widgets/view.dart +++ b/packages/flutter/lib/src/widgets/view.dart @@ -699,17 +699,14 @@ class _MultiChildComponentElement extends Element { @override List debugDescribeChildren() { - final List children = []; - if (_childElement != null) { - children.add(_childElement!.toDiagnosticsNode()); - } - for (int i = 0; i < _viewElements.length; i++) { - children.add(_viewElements[i].toDiagnosticsNode( - name: 'view ${i + 1}', - style: DiagnosticsTreeStyle.offstage, - )); - } - return children; + return [ + if (_childElement != null) _childElement!.toDiagnosticsNode(), + for (int i = 0; i < _viewElements.length; i++) + _viewElements[i].toDiagnosticsNode( + name: 'view ${i + 1}', + style: DiagnosticsTreeStyle.offstage, + ), + ]; } } diff --git a/packages/flutter/lib/src/widgets/widget_inspector.dart b/packages/flutter/lib/src/widgets/widget_inspector.dart index d578e594cb85..e04c121e7c56 100644 --- a/packages/flutter/lib/src/widgets/widget_inspector.dart +++ b/packages/flutter/lib/src/widgets/widget_inspector.dart @@ -960,17 +960,11 @@ mixin WidgetInspectorService { registerServiceExtension( name: name, callback: (Map parameters) async { - final List args = []; - int index = 0; - while (true) { - final String name = 'arg$index'; - if (parameters.containsKey(name)) { - args.add(parameters[name]!); - } else { - break; - } - index++; - } + int index; + final List args = [ + for (index = 0; parameters['arg$index'] != null; index++) + parameters['arg$index']!, + ]; // Verify that the only arguments other than perhaps 'isolateId' are // arguments we have already handled. assert(index == parameters.length || (index == parameters.length - 1 && parameters.containsKey('isolateId'))); @@ -3408,27 +3402,16 @@ class _Location { final String? name; Map toJsonMap() { - final Map json = { + return { 'file': file, 'line': line, 'column': column, + if (name != null) 'name': name, }; - if (name != null) { - json['name'] = name; - } - return json; } @override - String toString() { - final List parts = []; - if (name != null) { - parts.add(name!); - } - parts.add(file); - parts..add('$line')..add('$column'); - return parts.join(':'); - } + String toString() => [if (name != null) name!, file, '$line', '$column'].join(':'); } bool _isDebugCreator(DiagnosticsNode node) => node is DiagnosticsDebugCreator; diff --git a/packages/flutter/test/cupertino/text_selection_toolbar_test.dart b/packages/flutter/test/cupertino/text_selection_toolbar_test.dart index 5d9717d258e7..3fe50706fc08 100644 --- a/packages/flutter/test/cupertino/text_selection_toolbar_test.dart +++ b/packages/flutter/test/cupertino/text_selection_toolbar_test.dart @@ -204,12 +204,7 @@ void main() { // Adding 7 more children overflows onto a third page. setState(() { - children.add(const TestBox()); - children.add(const TestBox()); - children.add(const TestBox()); - children.add(const TestBox()); - children.add(const TestBox()); - children.add(const TestBox()); + children.addAll(List.filled(6, const TestBox())); }); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(7)); diff --git a/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart b/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart index 66c668f671b0..eafa7f828312 100644 --- a/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart +++ b/packages/flutter/test/material/spell_check_suggestions_toolbar_test.dart @@ -17,24 +17,15 @@ void main() { /// Builds test button items for each of the suggestions provided. List buildSuggestionButtons(List suggestions) { - final List buttonItems = []; - - for (final String suggestion in suggestions) { - buttonItems.add(ContextMenuButtonItem( - onPressed: () {}, - label: suggestion, - )); - } - - final ContextMenuButtonItem deleteButton = + return [ + for (final String suggestion in suggestions) + ContextMenuButtonItem(onPressed: () {}, label: suggestion), ContextMenuButtonItem( onPressed: () {}, type: ContextMenuButtonType.delete, label: 'DELETE', - ); - buttonItems.add(deleteButton); - - return buttonItems; + ), + ]; } /// Finds the container of the [SpellCheckSuggestionsToolbar] so that diff --git a/packages/flutter/test/widgets/slivers_test.dart b/packages/flutter/test/widgets/slivers_test.dart index 63868ff77fd7..4eda82dcac6d 100644 --- a/packages/flutter/test/widgets/slivers_test.dart +++ b/packages/flutter/test/widgets/slivers_test.dart @@ -338,14 +338,10 @@ void main() { testWidgets('SliverFixedExtentList handles underflow when its children changes', (WidgetTester tester) async { final List items = ['1', '2', '3', '4', '5', '6']; final List initializedChild = []; - List children = []; - for (final String item in items) { - children.add( - StateInitSpy( - item, () => initializedChild.add(item), key: ValueKey(item), - ), - ); - } + List children = [ + for (final String item in items) + StateInitSpy(item, () => initializedChild.add(item), key: ValueKey(item)), + ]; final ScrollController controller = ScrollController(initialScrollOffset: 5400); addTearDown(controller.dispose); diff --git a/packages/integration_test/lib/common.dart b/packages/integration_test/lib/common.dart index e148851b38c4..ff2906c6c1e2 100644 --- a/packages/integration_test/lib/common.dart +++ b/packages/integration_test/lib/common.dart @@ -106,16 +106,10 @@ class Response { /// Create a list of Strings from [_failureDetails]. List _failureDetailsAsString() { - final List list = []; - if (_failureDetails == null || _failureDetails.isEmpty) { - return list; - } - - for (final Failure failure in _failureDetails) { - list.add(failure.toJson()); - } - - return list; + return [ + if (_failureDetails != null) + for (final Failure failure in _failureDetails) failure.toJson(), + ]; } /// Creates a [Failure] list using a json response.