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).
This commit is contained in:
Nate
2024-04-15 11:06:07 -05:00
committed by GitHub
parent 600787891a
commit 2e748e8598
37 changed files with 276 additions and 494 deletions

View File

@@ -11,30 +11,20 @@ import 'package:flutter/services.dart';
import 'package:microbenchmarks/common.dart';
List<Object?> _makeTestBuffer(int size) {
final List<Object?> answer = <Object?>[];
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(<int>[1234]);
case 5:
answer.add(<String, int>{'hello': 1234});
case 6:
answer.add('this is a test');
case 7:
answer.add(true);
case 8:
answer.add(Uint8List(64));
}
}
return answer;
return <Object?>[
for (int i = 0; i < size; i++)
switch (i % 9) {
0 => 1,
1 => math.pow(2, 65),
2 => 1234.0,
3 => null,
4 => <int>[1234],
5 => <String, int>{'hello': 1234},
6 => 'this is a test',
7 => true,
_ => Uint8List(64),
},
];
}
Future<double> _runBasicStandardSmall(

View File

@@ -139,28 +139,21 @@ Future<void> verifyExist(
String flutterRoot,
{@visibleForTesting ProcessManager processManager = const LocalProcessManager()
}) async {
final Set<String> foundFiles = <String>{};
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<String> binaryPaths = await findBinaryPaths(
path.join(flutterRoot, 'bin', 'cache'),
processManager: processManager,
);
final List<String> allExpectedFiles = binariesWithEntitlements(flutterRoot) + binariesWithoutEntitlements(flutterRoot);
final Set<String> foundFiles = <String>{
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<String> unfoundFiles = allExpectedFiles
.where(
(String file) => !foundFiles.contains(file),
)
.toList();
final List<String> unfoundFiles = <String>[
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'

View File

@@ -913,18 +913,14 @@ Future<void> _runFrameworkTests() async {
final Uint8List libappBytes = libapp.content as Uint8List; // bytes decompressed here
final String libappStrings = utf8.decode(libappBytes, allowMalformed: true);
await runCommand(flutter, <String>['clean'], workingDirectory: tracingDirectory);
final List<String> results = <String>[];
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 <String>[
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 <String>[
error.toString(),
@@ -1332,11 +1328,9 @@ Future<void> _runDartTest(String workingDirectory, {
if (collectMetrics) {
try {
final List<String> testList = <String>[];
final Map<int, TestSpecs> allTestSpecs = test.allTestSpecs;
for (final TestSpecs testSpecs in allTestSpecs.values) {
testList.add(testSpecs.toJson());
}
final List<String> testList = <String>[
for (final TestSpecs testSpecs in test.allTestSpecs.values) testSpecs.toJson(),
];
if (testList.isNotEmpty) {
final String testJson = json.encode(testList);
final File testResults = fileSystem.file(

View File

@@ -110,12 +110,10 @@ class NextContext extends Context {
break;
}
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) {
if (!finishedStates.contains(cherrypick.state)) {
unappliedCherrypicks.add(cherrypick);
}
}
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[
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<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) {
if (!finishedStates.contains(cherrypick.state)) {
unappliedCherrypicks.add(cherrypick);
}
}
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks)
if (!finishedStates.contains(cherrypick.state)) cherrypick,
];
if (state.framework.cherrypicks.isEmpty) {
stdio.printStatus(

View File

@@ -183,15 +183,11 @@ abstract class Repository {
workingDirectory: (await checkoutDirectory).path,
);
final List<String> remoteBranches = <String>[];
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 <String>[
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.

View File

@@ -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,

View File

@@ -154,14 +154,11 @@ class AndroidSemanticsNode {
if (actions == null) {
return const <AndroidSemanticsAction>[];
}
final List<AndroidSemanticsAction> convertedActions = <AndroidSemanticsAction>[];
for (final int id in actions) {
final AndroidSemanticsAction? action = AndroidSemanticsAction.deserialize(id);
if (action != null) {
convertedActions.add(action);
}
}
return convertedActions;
return <AndroidSemanticsAction>[
for (final int id in actions)
if (AndroidSemanticsAction.deserialize(id) case final AndroidSemanticsAction action)
action,
];
}
@override

View File

@@ -121,10 +121,8 @@ class CalcExpression {
: this(<ExpressionToken>[], ExpressionState.Start);
CalcExpression.result(FloatToken result)
: _list = <ExpressionToken?>[],
state = ExpressionState.Result {
_list.add(result);
}
: _list = <ExpressionToken?>[result],
state = ExpressionState.Result;
/// The tokens comprising the expression.
final List<ExpressionToken?> _list;

View File

@@ -84,15 +84,11 @@ class _CupertinoSearchTextFieldDemoState
Widget _buildPlatformList() {
if (_searchPlatform.isNotEmpty) {
final List<String> tempList = <String>[];
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 = <String>[
for (final String platform in filteredPlatforms)
if (platform.toLowerCase().contains(search)) platform
];
}
return ListView.builder(
itemCount: filteredPlatforms.length,

View File

@@ -26,14 +26,10 @@ class _RestorableDessertSelections extends RestorableProperty<Set<int>> {
/// Takes a list of [_Dessert]s and saves the row indices of selected rows
/// into a [Set].
void setDessertSelections(List<_Dessert> desserts) {
final Set<int> updatedSet = <int>{};
for (int i = 0; i < desserts.length; i += 1) {
final _Dessert dessert = desserts[i];
if (dessert.selected) {
updatedSet.add(i);
}
}
_dessertSelections = updatedSet;
_dessertSelections = <int>{
for (final (int i, _Dessert dessert) in desserts.indexed)
if (dessert.selected) i,
};
notifyListeners();
}

View File

@@ -116,19 +116,18 @@ Future<File> generateTest(Directory apiDir) async {
});
// Collect the examples, and import them all as separate symbols.
final List<String> imports = <String>[];
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<ExampleInfo> infoList = <ExampleInfo>[];
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<ExampleInfo> infoList = <ExampleInfo>[
for (final File example in examples) ExampleInfo(example, examplesLibDir),
];
infoList.sort((ExampleInfo a, ExampleInfo b) => a.importPath.compareTo(b.importPath));
final List<String> imports = <String>[
"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.');

View File

@@ -388,15 +388,10 @@ bool testIsSuperset(Map<String, String> newCodepoints, Map<String, String> oldCo
@visibleForTesting
bool testIsStable(Map<String, String> newCodepoints, Map<String, String> oldCodepoints) {
final int oldCodepointsCount = oldCodepoints.length;
final List<String> unstable = <String>[];
oldCodepoints.forEach((String key, String value) {
if (newCodepoints.containsKey(key)) {
if (value != newCodepoints[key]) {
unstable.add(key);
}
}
});
final List<String> unstable = <String>[
for (final MapEntry<String, String>(: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');