Skip to content

Commit

Permalink
Implementing control flow collections (#146601)
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
nate-thegrate authored Apr 15, 2024
1 parent 6007878 commit 2e748e8
Show file tree
Hide file tree
Showing 37 changed files with 276 additions and 494 deletions.
38 changes: 14 additions & 24 deletions dev/benchmarks/platform_channels_benchmarks/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
33 changes: 13 additions & 20 deletions dev/bots/suite_runners/run_verify_binaries_codesigned_tests.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
28 changes: 11 additions & 17 deletions dev/bots/test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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(
Expand Down
20 changes: 8 additions & 12 deletions dev/conductor/core/lib/src/next.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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(
Expand Down
14 changes: 5 additions & 9 deletions dev/conductor/core/lib/src/repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion dev/devicelab/lib/tasks/microbenchmarks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
23 changes: 11 additions & 12 deletions dev/tools/examples_smoke_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand Down
13 changes: 4 additions & 9 deletions dev/tools/update_icons.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
15 changes: 4 additions & 11 deletions packages/flutter/lib/src/cupertino/dialog.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1485,22 +1485,15 @@ class _CupertinoAlertActionSection extends StatelessWidget {

@override
Widget build(BuildContext context) {

final List<Widget> interactiveButtons = <Widget>[];
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: <Widget>[
for (final Widget child in children)
_PressableActionButton(child: child),
],
dividerThickness: _kDividerThickness,
hasCancelButton: hasCancelButton,
isActionSheet: isActionSheet,
Expand Down
25 changes: 9 additions & 16 deletions packages/flutter/lib/src/foundation/timeline.dart
Original file line number Diff line number Diff line change
Expand Up @@ -311,12 +311,10 @@ final class _Float64ListChain {
/// are read back, they do not affect the timings of the work being
/// benchmarked.
List<double> extractElements() {
final List<double> result = <double>[];
_chain.forEach(result.addAll);
for (int i = 0; i < _pointer; i++) {
result.add(_slice[i]);
}
return result;
return <double>[
for (final Float64List list in _chain) ...list,
for (int i = 0; i < _pointer; i++) _slice[i],
];
}
}

Expand Down Expand Up @@ -349,16 +347,11 @@ final class _StringListChain {
/// are read back, they do not affect the timings of the work being
/// benchmarked.
List<String> extractElements() {
final List<String> result = <String>[];
for (final List<String?> 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 <String>[
for (final List<String?> slice in _chain)
for (final String? value in slice) value!,
for (int i = 0; i < _pointer; i++) _slice[i]!,
];
}
}

Expand Down
Loading

0 comments on commit 2e748e8

Please sign in to comment.