Skip to content

Commit

Permalink
Control flow collections: flutter_tools/ (#147450)
Browse files Browse the repository at this point in the history
This pull request aims for improved readability, based on issue #146600.

```dart
// before
List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) {
  final List<SupportedPlatform> platforms = includeRoot
      ? <SupportedPlatform>[SupportedPlatform.root]
      : <SupportedPlatform>[];
  if (android.existsSync()) {
    platforms.add(SupportedPlatform.android);
  }
  if (ios.exists) {
    platforms.add(SupportedPlatform.ios);
  }
  if (web.existsSync()) {
    platforms.add(SupportedPlatform.web);
  }
  if (macos.existsSync()) {
    platforms.add(SupportedPlatform.macos);
  }
  if (linux.existsSync()) {
    platforms.add(SupportedPlatform.linux);
  }
  if (windows.existsSync()) {
    platforms.add(SupportedPlatform.windows);
  }
  if (fuchsia.existsSync()) {
    platforms.add(SupportedPlatform.fuchsia);
  }
  return platforms;
}

// after
List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) {
  return <SupportedPlatform>[
    if (includeRoot)          SupportedPlatform.root,
    if (android.existsSync()) SupportedPlatform.android,
    if (ios.exists)           SupportedPlatform.ios,
    if (web.existsSync())     SupportedPlatform.web,
    if (macos.existsSync())   SupportedPlatform.macos,
    if (linux.existsSync())   SupportedPlatform.linux,
    if (windows.existsSync()) SupportedPlatform.windows,
    if (fuchsia.existsSync()) SupportedPlatform.fuchsia,
  ];
}
```
  • Loading branch information
nate-thegrate committed May 2, 2024
1 parent 7436cc2 commit 5d1bfdc
Show file tree
Hide file tree
Showing 26 changed files with 221 additions and 459 deletions.
15 changes: 5 additions & 10 deletions packages/flutter_tools/lib/src/android/android_studio.dart
Expand Up @@ -384,17 +384,12 @@ class AndroidStudio {
final String? homeDirPath = globals.fsUtils.homeDirPath;

if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) {
final Directory homeDir = globals.fs.directory(homeDirPath);

final List<Directory> directoriesToSearch = <Directory>[homeDir];

// >=4.1 has new install location at $HOME/.cache/Google
final String cacheDirPath =
globals.fs.path.join(homeDirPath, '.cache', 'Google');

if (globals.fs.isDirectorySync(cacheDirPath)) {
directoriesToSearch.add(globals.fs.directory(cacheDirPath));
}
final String cacheDirPath = globals.fs.path.join(homeDirPath, '.cache', 'Google');
final List<Directory> directoriesToSearch = <Directory>[
globals.fs.directory(homeDirPath),
if (globals.fs.isDirectorySync(cacheDirPath)) globals.fs.directory(cacheDirPath),
];

final List<Directory> entities = <Directory>[];

Expand Down
13 changes: 5 additions & 8 deletions packages/flutter_tools/lib/src/android/gradle.dart
Expand Up @@ -811,14 +811,11 @@ class AndroidGradleBuilder implements AndroidBuilder {
_logger.printError(result.stderr, wrap: false);
return const <String>[];
}
final List<String> options = <String>[];
for (final String line in LineSplitter.split(result.stdout)) {
final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line);
if (match != null) {
options.add(match.namedGroup(_kBuildVariantRegexGroupName)!);
}
}
return options;
return <String>[
for (final String line in LineSplitter.split(result.stdout))
if (_kBuildVariantRegex.firstMatch(line) case final RegExpMatch match)
match.namedGroup(_kBuildVariantRegexGroupName)!,
];
}

@override
Expand Down
15 changes: 6 additions & 9 deletions packages/flutter_tools/lib/src/base/analyze_size.dart
Expand Up @@ -469,18 +469,15 @@ class _SymbolNode {
}

Map<String, Object?> toJson() {
final Map<String, Object?> json = <String, Object?>{
final List<Map<String, Object?>> childrenAsJson = <Map<String, Object?>>[
for (final _SymbolNode child in children) child.toJson(),
];

return <String, Object?>{
'n': name,
'value': byteSize,
if (childrenAsJson.isNotEmpty) 'children': childrenAsJson,
};
final List<Map<String, Object?>> childrenAsJson = <Map<String, Object?>>[];
for (final _SymbolNode child in children) {
childrenAsJson.add(child.toJson());
}
if (childrenAsJson.isNotEmpty) {
json['children'] = childrenAsJson;
}
return json;
}
}

Expand Down
40 changes: 16 additions & 24 deletions packages/flutter_tools/lib/src/base/deferred_component.dart
Expand Up @@ -71,14 +71,11 @@ class DeferredComponent {
/// status, but will result in [loadingUnits] returning an empty set.
void assignLoadingUnits(List<LoadingUnit> allLoadingUnits) {
_assigned = true;
_loadingUnits = <LoadingUnit>{};
for (final String lib in libraries) {
for (final LoadingUnit loadingUnit in allLoadingUnits) {
if (loadingUnit.libraries.contains(lib)) {
_loadingUnits!.add(loadingUnit);
}
}
}
_loadingUnits = <LoadingUnit>{
for (final String lib in libraries)
for (final LoadingUnit loadingUnit in allLoadingUnits)
if (loadingUnit.libraries.contains(lib)) loadingUnit,
};
}

/// Provides a human readable string representation of the
Expand Down Expand Up @@ -193,21 +190,16 @@ class LoadingUnit {
} on FormatException catch (e) {
logger.printError('Loading unit manifest at `${manifestFile.path}` was invalid JSON:\n$e');
}
final List<LoadingUnit> loadingUnits = <LoadingUnit>[];
// Setup android source directory
if (manifest != null) {
for (final dynamic loadingUnitMetadata in manifest['loadingUnits'] as List<dynamic>) {
final Map<String, dynamic> loadingUnitMap = loadingUnitMetadata as Map<String, dynamic>;
if (loadingUnitMap['id'] == 1) {
continue; // Skip base unit
}
loadingUnits.add(LoadingUnit(
id: loadingUnitMap['id'] as int,
path: loadingUnitMap['path'] as String,
libraries: List<String>.from(loadingUnitMap['libraries'] as List<dynamic>)),
);
}
}
return loadingUnits;
// Set up android source directory
return <LoadingUnit>[
if (manifest?['loadingUnits'] case final List<dynamic> loadingUnits)
for (final Map<String, dynamic> loadingUnitMap in loadingUnits.cast<Map<String, dynamic>>())
if (loadingUnitMap['id'] != 1) // skip base unit
LoadingUnit(
id: loadingUnitMap['id'] as int,
path: loadingUnitMap['path'] as String,
libraries: List<String>.from(loadingUnitMap['libraries'] as List<dynamic>),
),
];
}
}
11 changes: 4 additions & 7 deletions packages/flutter_tools/lib/src/base/process.dart
Expand Up @@ -69,13 +69,10 @@ class _DefaultShutdownHooks implements ShutdownHooks {
);
_shutdownHooksRunning = true;
try {
final List<Future<dynamic>> futures = <Future<dynamic>>[];
for (final ShutdownHook shutdownHook in registeredHooks) {
final FutureOr<dynamic> result = shutdownHook();
if (result is Future<dynamic>) {
futures.add(result);
}
}
final List<Future<dynamic>> futures = <Future<dynamic>>[
for (final ShutdownHook shutdownHook in registeredHooks)
if (shutdownHook() case final Future<dynamic> result) result,
];
await Future.wait<dynamic>(futures);
} finally {
_shutdownHooksRunning = false;
Expand Down
18 changes: 5 additions & 13 deletions packages/flutter_tools/lib/src/build_system/build_system.dart
Expand Up @@ -182,21 +182,13 @@ abstract class Target {
List<File> outputs,
Environment environment,
) {
final File stamp = _findStampFile(environment);
final List<String> inputPaths = <String>[];
for (final File input in inputs) {
inputPaths.add(input.path);
}
final List<String> outputPaths = <String>[];
for (final File output in outputs) {
outputPaths.add(output.path);
}
final String? key = buildKey;
String getPath(File file) => file.path;
final Map<String, Object> result = <String, Object>{
'inputs': inputPaths,
'outputs': outputPaths,
if (key != null) 'buildKey': key,
'inputs': inputs.map(getPath).toList(),
'outputs': outputs.map(getPath).toList(),
if (buildKey case final String key) 'buildKey': key,
};
final File stamp = _findStampFile(environment);
if (!stamp.existsSync()) {
stamp.createSync();
}
Expand Down
20 changes: 6 additions & 14 deletions packages/flutter_tools/lib/src/build_system/depfile.dart
Expand Up @@ -58,20 +58,12 @@ class DepfileService {
/// The [file] contains a list of newline separated file URIs. The output
/// file must be manually specified.
Depfile parseDart2js(File file, File output) {
final List<File> inputs = <File>[];
for (final String rawUri in file.readAsLinesSync()) {
if (rawUri.trim().isEmpty) {
continue;
}
final Uri? fileUri = Uri.tryParse(rawUri);
if (fileUri == null) {
continue;
}
if (fileUri.scheme != 'file') {
continue;
}
inputs.add(_fileSystem.file(fileUri));
}
final List<File> inputs = <File>[
for (final String rawUri in file.readAsLinesSync())
if (rawUri.trim().isNotEmpty)
if (Uri.tryParse(rawUri) case final Uri fileUri when fileUri.scheme == 'file')
_fileSystem.file(fileUri),
];
return Depfile(inputs, <File>[output]);
}

Expand Down
Expand Up @@ -37,15 +37,11 @@ class DeferredComponentsGenSnapshotValidatorTarget extends Target {

/// The abis to validate.
List<String> get _abis {
final List<String> abis = <String>[];
for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies) {
if (deferredComponentsTargets.contains(target.name)) {
abis.add(
getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)).archName
);
}
}
return abis;
return <String>[
for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies)
if (deferredComponentsTargets.contains(target.name))
getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)).archName,
];
}

@override
Expand Down
18 changes: 5 additions & 13 deletions packages/flutter_tools/lib/src/commands/build_ios_framework.dart
Expand Up @@ -112,19 +112,11 @@ abstract class BuildFrameworkCommand extends BuildSubCommand {
late final FlutterProject project = FlutterProject.current();

Future<List<BuildInfo>> getBuildInfos() async {
final List<BuildInfo> buildInfos = <BuildInfo>[];

if (boolArg('debug')) {
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.debug));
}
if (boolArg('profile')) {
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.profile));
}
if (boolArg('release')) {
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.release));
}

return buildInfos;
return <BuildInfo>[
if (boolArg('debug')) await getBuildInfo(forcedBuildMode: BuildMode.debug),
if (boolArg('profile')) await getBuildInfo(forcedBuildMode: BuildMode.profile),
if (boolArg('release')) await getBuildInfo(forcedBuildMode: BuildMode.release),
];
}

@override
Expand Down
13 changes: 5 additions & 8 deletions packages/flutter_tools/lib/src/custom_devices/custom_device.dart
Expand Up @@ -101,14 +101,11 @@ class CustomDeviceLogReader extends DeviceLogReader {
/// [logLines] as done.
@override
Future<void> dispose() async {
final List<Future<void>> futures = <Future<void>>[];

for (final StreamSubscription<String> subscription in subscriptions) {
futures.add(subscription.cancel());
}

futures.add(logLinesController.close());

final List<Future<void>> futures = <Future<void>>[
for (final StreamSubscription<String> subscription in subscriptions)
subscription.cancel(),
logLinesController.close(),
];
await Future.wait(futures);
}

Expand Down
46 changes: 10 additions & 36 deletions packages/flutter_tools/lib/src/doctor.dart
Expand Up @@ -196,42 +196,16 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {

@override
List<Workflow> get workflows {
if (_workflows == null) {
_workflows = <Workflow>[];

if (globals.iosWorkflow!.appliesToHostPlatform) {
_workflows!.add(globals.iosWorkflow!);
}

if (androidWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(androidWorkflow!);
}

if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(fuchsiaWorkflow!);
}

if (linuxWorkflow.appliesToHostPlatform) {
_workflows!.add(linuxWorkflow);
}

if (macOSWorkflow.appliesToHostPlatform) {
_workflows!.add(macOSWorkflow);
}

if (windowsWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(windowsWorkflow!);
}

if (webWorkflow.appliesToHostPlatform) {
_workflows!.add(webWorkflow);
}

if (customDeviceWorkflow.appliesToHostPlatform) {
_workflows!.add(customDeviceWorkflow);
}
}
return _workflows!;
return _workflows ??= <Workflow>[
if (globals.iosWorkflow!.appliesToHostPlatform) globals.iosWorkflow!,
if (androidWorkflow?.appliesToHostPlatform ?? false) androidWorkflow!,
if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) fuchsiaWorkflow!,
if (linuxWorkflow.appliesToHostPlatform) linuxWorkflow,
if (macOSWorkflow.appliesToHostPlatform) macOSWorkflow,
if (windowsWorkflow?.appliesToHostPlatform ?? false) windowsWorkflow!,
if (webWorkflow.appliesToHostPlatform) webWorkflow,
if (customDeviceWorkflow.appliesToHostPlatform) customDeviceWorkflow,
];
}
}

Expand Down
13 changes: 5 additions & 8 deletions packages/flutter_tools/lib/src/flutter_plugins.dart
Expand Up @@ -316,14 +316,11 @@ public final class GeneratedPluginRegistrant {
''';

List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) {
final List<Map<String, Object?>> pluginConfigs = <Map<String, Object?>>[];
for (final Plugin p in plugins) {
final PluginPlatform? platformPlugin = p.platforms[type];
if (platformPlugin != null) {
pluginConfigs.add(platformPlugin.toMap());
}
}
return pluginConfigs;
return <Map<String, Object?>>[
for (final Plugin plugin in plugins)
if (plugin.platforms[type] case final PluginPlatform platformPlugin)
platformPlugin.toMap(),
];
}

Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {
Expand Down
13 changes: 4 additions & 9 deletions packages/flutter_tools/lib/src/fuchsia/fuchsia_device.dart
Expand Up @@ -188,15 +188,10 @@ class FuchsiaDevices extends PollingDeviceDiscovery {
if (text == null || text.isEmpty) {
return <Device>[];
}
final List<FuchsiaDevice> devices = <FuchsiaDevice>[];
for (final String line in text) {
final FuchsiaDevice? device = await _parseDevice(line);
if (device == null) {
continue;
}
devices.add(device);
}
return devices;
return <FuchsiaDevice>[
for (final String line in text)
if (await _parseDevice(line) case final FuchsiaDevice device) device,
];
}

@override
Expand Down

0 comments on commit 5d1bfdc

Please sign in to comment.