Skip to content

Commit 2e748e8

Browse files
Implementing control flow collections (#146601)
This pull request aims for improved readability, based on issue #146600. ```dart // before Set<Color> _distinctVisibleColors() { final Set<Color> distinctVisibleColors = <Color>{}; 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<Color> _distinctVisibleColors() { return <Color>{ 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).
1 parent 6007878 commit 2e748e8

37 files changed

+276
-494
lines changed

dev/benchmarks/platform_channels_benchmarks/lib/main.dart

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,20 @@ import 'package:flutter/services.dart';
1111
import 'package:microbenchmarks/common.dart';
1212

1313
List<Object?> _makeTestBuffer(int size) {
14-
final List<Object?> answer = <Object?>[];
15-
for (int i = 0; i < size; ++i) {
16-
switch (i % 9) {
17-
case 0:
18-
answer.add(1);
19-
case 1:
20-
answer.add(math.pow(2, 65));
21-
case 2:
22-
answer.add(1234.0);
23-
case 3:
24-
answer.add(null);
25-
case 4:
26-
answer.add(<int>[1234]);
27-
case 5:
28-
answer.add(<String, int>{'hello': 1234});
29-
case 6:
30-
answer.add('this is a test');
31-
case 7:
32-
answer.add(true);
33-
case 8:
34-
answer.add(Uint8List(64));
35-
}
36-
}
37-
return answer;
14+
return <Object?>[
15+
for (int i = 0; i < size; i++)
16+
switch (i % 9) {
17+
0 => 1,
18+
1 => math.pow(2, 65),
19+
2 => 1234.0,
20+
3 => null,
21+
4 => <int>[1234],
22+
5 => <String, int>{'hello': 1234},
23+
6 => 'this is a test',
24+
7 => true,
25+
_ => Uint8List(64),
26+
},
27+
];
3828
}
3929

4030
Future<double> _runBasicStandardSmall(

dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -139,28 +139,21 @@ Future<void> verifyExist(
139139
String flutterRoot,
140140
{@visibleForTesting ProcessManager processManager = const LocalProcessManager()
141141
}) async {
142-
final Set<String> foundFiles = <String>{};
143-
final String cacheDirectory = path.join(flutterRoot, 'bin', 'cache');
144-
145-
for (final String binaryPath
146-
in await findBinaryPaths(cacheDirectory, processManager: processManager)) {
147-
if (binariesWithEntitlements(flutterRoot).contains(binaryPath)) {
148-
foundFiles.add(binaryPath);
149-
} else if (binariesWithoutEntitlements(flutterRoot).contains(binaryPath)) {
150-
foundFiles.add(binaryPath);
151-
} else {
152-
throw Exception(
153-
'Found unexpected binary in cache: $binaryPath');
154-
}
155-
}
156-
142+
final List<String> binaryPaths = await findBinaryPaths(
143+
path.join(flutterRoot, 'bin', 'cache'),
144+
processManager: processManager,
145+
);
157146
final List<String> allExpectedFiles = binariesWithEntitlements(flutterRoot) + binariesWithoutEntitlements(flutterRoot);
147+
final Set<String> foundFiles = <String>{
148+
for (final String binaryPath in binaryPaths)
149+
if (allExpectedFiles.contains(binaryPath)) binaryPath
150+
else throw Exception('Found unexpected binary in cache: $binaryPath'),
151+
};
152+
158153
if (foundFiles.length < allExpectedFiles.length) {
159-
final List<String> unfoundFiles = allExpectedFiles
160-
.where(
161-
(String file) => !foundFiles.contains(file),
162-
)
163-
.toList();
154+
final List<String> unfoundFiles = <String>[
155+
for (final String file in allExpectedFiles) if (!foundFiles.contains(file)) file,
156+
];
164157
print(
165158
'Expected binaries not found in cache:\n\n${unfoundFiles.join('\n')}\n\n'
166159
'If this commit is removing binaries from the cache, this test should be fixed by\n'

dev/bots/test.dart

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -913,18 +913,14 @@ Future<void> _runFrameworkTests() async {
913913
final Uint8List libappBytes = libapp.content as Uint8List; // bytes decompressed here
914914
final String libappStrings = utf8.decode(libappBytes, allowMalformed: true);
915915
await runCommand(flutter, <String>['clean'], workingDirectory: tracingDirectory);
916-
final List<String> results = <String>[];
917-
for (final String pattern in allowed) {
918-
if (!libappStrings.contains(pattern)) {
919-
results.add('When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.');
920-
}
921-
}
922-
for (final String pattern in disallowed) {
923-
if (libappStrings.contains(pattern)) {
924-
results.add('When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.');
925-
}
926-
}
927-
return results;
916+
return <String>[
917+
for (final String pattern in allowed)
918+
if (!libappStrings.contains(pattern))
919+
'When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.',
920+
for (final String pattern in disallowed)
921+
if (libappStrings.contains(pattern))
922+
'When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.',
923+
];
928924
} catch (error, stackTrace) {
929925
return <String>[
930926
error.toString(),
@@ -1332,11 +1328,9 @@ Future<void> _runDartTest(String workingDirectory, {
13321328

13331329
if (collectMetrics) {
13341330
try {
1335-
final List<String> testList = <String>[];
1336-
final Map<int, TestSpecs> allTestSpecs = test.allTestSpecs;
1337-
for (final TestSpecs testSpecs in allTestSpecs.values) {
1338-
testList.add(testSpecs.toJson());
1339-
}
1331+
final List<String> testList = <String>[
1332+
for (final TestSpecs testSpecs in test.allTestSpecs.values) testSpecs.toJson(),
1333+
];
13401334
if (testList.isNotEmpty) {
13411335
final String testJson = json.encode(testList);
13421336
final File testResults = fileSystem.file(

dev/conductor/core/lib/src/next.dart

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,10 @@ class NextContext extends Context {
110110
break;
111111
}
112112

113-
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
114-
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) {
115-
if (!finishedStates.contains(cherrypick.state)) {
116-
unappliedCherrypicks.add(cherrypick);
117-
}
118-
}
113+
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[
114+
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks)
115+
if (!finishedStates.contains(cherrypick.state)) cherrypick,
116+
];
119117

120118
if (unappliedCherrypicks.isEmpty) {
121119
stdio.printStatus('All engine cherrypicks have been auto-applied by the conductor.\n');
@@ -206,12 +204,10 @@ class NextContext extends Context {
206204
);
207205
}
208206

209-
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
210-
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) {
211-
if (!finishedStates.contains(cherrypick.state)) {
212-
unappliedCherrypicks.add(cherrypick);
213-
}
214-
}
207+
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[
208+
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks)
209+
if (!finishedStates.contains(cherrypick.state)) cherrypick,
210+
];
215211

216212
if (state.framework.cherrypicks.isEmpty) {
217213
stdio.printStatus(

dev/conductor/core/lib/src/repository.dart

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -183,15 +183,11 @@ abstract class Repository {
183183
workingDirectory: (await checkoutDirectory).path,
184184
);
185185

186-
final List<String> remoteBranches = <String>[];
187-
for (final String line in output.split('\n')) {
188-
final RegExpMatch? match = _lsRemotePattern.firstMatch(line);
189-
if (match != null) {
190-
remoteBranches.add(match.group(1)!);
191-
}
192-
}
193-
194-
return remoteBranches;
186+
return <String>[
187+
for (final String line in output.split('\n'))
188+
if (_lsRemotePattern.firstMatch(line) case final RegExpMatch match)
189+
match.group(1)!,
190+
];
195191
}
196192

197193
/// Ensure the repository is cloned to disk and initialized with proper state.

dev/devicelab/lib/tasks/microbenchmarks.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ TaskFunction createMicrobenchmarkTask({
3939
if (enableImpeller != null && !enableImpeller) '--no-enable-impeller',
4040
'-d',
4141
device.deviceId,
42+
benchmarkPath,
4243
];
43-
options.add(benchmarkPath);
4444
return startFlutter(
4545
'run',
4646
options: options,

dev/integration_tests/android_semantics_testing/lib/src/common.dart

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,11 @@ class AndroidSemanticsNode {
154154
if (actions == null) {
155155
return const <AndroidSemanticsAction>[];
156156
}
157-
final List<AndroidSemanticsAction> convertedActions = <AndroidSemanticsAction>[];
158-
for (final int id in actions) {
159-
final AndroidSemanticsAction? action = AndroidSemanticsAction.deserialize(id);
160-
if (action != null) {
161-
convertedActions.add(action);
162-
}
163-
}
164-
return convertedActions;
157+
return <AndroidSemanticsAction>[
158+
for (final int id in actions)
159+
if (AndroidSemanticsAction.deserialize(id) case final AndroidSemanticsAction action)
160+
action,
161+
];
165162
}
166163

167164
@override

dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,10 +121,8 @@ class CalcExpression {
121121
: this(<ExpressionToken>[], ExpressionState.Start);
122122

123123
CalcExpression.result(FloatToken result)
124-
: _list = <ExpressionToken?>[],
125-
state = ExpressionState.Result {
126-
_list.add(result);
127-
}
124+
: _list = <ExpressionToken?>[result],
125+
state = ExpressionState.Result;
128126

129127
/// The tokens comprising the expression.
130128
final List<ExpressionToken?> _list;

dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,11 @@ class _CupertinoSearchTextFieldDemoState
8484

8585
Widget _buildPlatformList() {
8686
if (_searchPlatform.isNotEmpty) {
87-
final List<String> tempList = <String>[];
88-
for (int i = 0; i < filteredPlatforms.length; i++) {
89-
if (filteredPlatforms[i]
90-
.toLowerCase()
91-
.contains(_searchPlatform.toLowerCase())) {
92-
tempList.add(filteredPlatforms[i]);
93-
}
94-
}
95-
filteredPlatforms = tempList;
87+
final String search = _searchPlatform.toLowerCase();
88+
filteredPlatforms = <String>[
89+
for (final String platform in filteredPlatforms)
90+
if (platform.toLowerCase().contains(search)) platform
91+
];
9692
}
9793
return ListView.builder(
9894
itemCount: filteredPlatforms.length,

dev/integration_tests/new_gallery/lib/demos/material/data_table_demo.dart

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,10 @@ class _RestorableDessertSelections extends RestorableProperty<Set<int>> {
2626
/// Takes a list of [_Dessert]s and saves the row indices of selected rows
2727
/// into a [Set].
2828
void setDessertSelections(List<_Dessert> desserts) {
29-
final Set<int> updatedSet = <int>{};
30-
for (int i = 0; i < desserts.length; i += 1) {
31-
final _Dessert dessert = desserts[i];
32-
if (dessert.selected) {
33-
updatedSet.add(i);
34-
}
35-
}
36-
_dessertSelections = updatedSet;
29+
_dessertSelections = <int>{
30+
for (final (int i, _Dessert dessert) in desserts.indexed)
31+
if (dessert.selected) i,
32+
};
3733
notifyListeners();
3834
}
3935

dev/tools/examples_smoke_test.dart

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -116,19 +116,18 @@ Future<File> generateTest(Directory apiDir) async {
116116
});
117117

118118
// Collect the examples, and import them all as separate symbols.
119-
final List<String> imports = <String>[];
120-
imports.add('''import 'package:flutter/widgets.dart';''');
121-
imports.add('''import 'package:flutter/scheduler.dart';''');
122-
imports.add('''import 'package:flutter_test/flutter_test.dart';''');
123-
imports.add('''import 'package:integration_test/integration_test.dart';''');
124-
final List<ExampleInfo> infoList = <ExampleInfo>[];
125-
for (final File example in examples) {
126-
final ExampleInfo info = ExampleInfo(example, examplesLibDir);
127-
infoList.add(info);
128-
imports.add('''import 'package:flutter_api_samples/${info.importPath}' as ${info.importName};''');
129-
}
130-
imports.sort();
119+
final List<ExampleInfo> infoList = <ExampleInfo>[
120+
for (final File example in examples) ExampleInfo(example, examplesLibDir),
121+
];
131122
infoList.sort((ExampleInfo a, ExampleInfo b) => a.importPath.compareTo(b.importPath));
123+
final List<String> imports = <String>[
124+
"import 'package:flutter/widgets.dart';",
125+
"import 'package:flutter/scheduler.dart';",
126+
"import 'package:flutter_test/flutter_test.dart';",
127+
"import 'package:integration_test/integration_test.dart';",
128+
for (final ExampleInfo info in infoList)
129+
"import 'package:flutter_api_samples/${info.importPath}' as ${info.importName};"
130+
]..sort();
132131

133132
final StringBuffer buffer = StringBuffer();
134133
buffer.writeln('// Temporary generated file. Do not commit.');

dev/tools/update_icons.dart

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -388,15 +388,10 @@ bool testIsSuperset(Map<String, String> newCodepoints, Map<String, String> oldCo
388388
@visibleForTesting
389389
bool testIsStable(Map<String, String> newCodepoints, Map<String, String> oldCodepoints) {
390390
final int oldCodepointsCount = oldCodepoints.length;
391-
final List<String> unstable = <String>[];
392-
393-
oldCodepoints.forEach((String key, String value) {
394-
if (newCodepoints.containsKey(key)) {
395-
if (value != newCodepoints[key]) {
396-
unstable.add(key);
397-
}
398-
}
399-
});
391+
final List<String> unstable = <String>[
392+
for (final MapEntry<String, String>(:String key, :String value) in oldCodepoints.entries)
393+
if (newCodepoints.containsKey(key) && value != newCodepoints[key]) key,
394+
];
400395

401396
if (unstable.isNotEmpty) {
402397
stderr.writeln('❌ out of $oldCodepointsCount existing codepoints, ${unstable.length} were unstable: $unstable');

packages/flutter/lib/src/cupertino/dialog.dart

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1485,22 +1485,15 @@ class _CupertinoAlertActionSection extends StatelessWidget {
14851485

14861486
@override
14871487
Widget build(BuildContext context) {
1488-
1489-
final List<Widget> interactiveButtons = <Widget>[];
1490-
for (int i = 0; i < children.length; i += 1) {
1491-
interactiveButtons.add(
1492-
_PressableActionButton(
1493-
child: children[i],
1494-
),
1495-
);
1496-
}
1497-
14981488
return CupertinoScrollbar(
14991489
controller: scrollController,
15001490
child: SingleChildScrollView(
15011491
controller: scrollController,
15021492
child: _CupertinoDialogActionsRenderWidget(
1503-
actionButtons: interactiveButtons,
1493+
actionButtons: <Widget>[
1494+
for (final Widget child in children)
1495+
_PressableActionButton(child: child),
1496+
],
15041497
dividerThickness: _kDividerThickness,
15051498
hasCancelButton: hasCancelButton,
15061499
isActionSheet: isActionSheet,

packages/flutter/lib/src/foundation/timeline.dart

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -311,12 +311,10 @@ final class _Float64ListChain {
311311
/// are read back, they do not affect the timings of the work being
312312
/// benchmarked.
313313
List<double> extractElements() {
314-
final List<double> result = <double>[];
315-
_chain.forEach(result.addAll);
316-
for (int i = 0; i < _pointer; i++) {
317-
result.add(_slice[i]);
318-
}
319-
return result;
314+
return <double>[
315+
for (final Float64List list in _chain) ...list,
316+
for (int i = 0; i < _pointer; i++) _slice[i],
317+
];
320318
}
321319
}
322320

@@ -349,16 +347,11 @@ final class _StringListChain {
349347
/// are read back, they do not affect the timings of the work being
350348
/// benchmarked.
351349
List<String> extractElements() {
352-
final List<String> result = <String>[];
353-
for (final List<String?> slice in _chain) {
354-
for (final String? element in slice) {
355-
result.add(element!);
356-
}
357-
}
358-
for (int i = 0; i < _pointer; i++) {
359-
result.add(_slice[i]!);
360-
}
361-
return result;
350+
return <String>[
351+
for (final List<String?> slice in _chain)
352+
for (final String? value in slice) value!,
353+
for (int i = 0; i < _pointer; i++) _slice[i]!,
354+
];
362355
}
363356
}
364357

0 commit comments

Comments
 (0)