Control flow collections: flutter_tools/ (#147450)

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,
  ];
}
```
This commit is contained in:
Nate 2024-05-02 16:19:18 -06:00 committed by GitHub
parent 7436cc25eb
commit 5d1bfdcb87
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 219 additions and 457 deletions

View File

@ -384,17 +384,12 @@ class AndroidStudio {
final String? homeDirPath = globals.fsUtils.homeDirPath; final String? homeDirPath = globals.fsUtils.homeDirPath;
if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) { 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 // >=4.1 has new install location at $HOME/.cache/Google
final String cacheDirPath = final String cacheDirPath = globals.fs.path.join(homeDirPath, '.cache', 'Google');
globals.fs.path.join(homeDirPath, '.cache', 'Google'); final List<Directory> directoriesToSearch = <Directory>[
globals.fs.directory(homeDirPath),
if (globals.fs.isDirectorySync(cacheDirPath)) { if (globals.fs.isDirectorySync(cacheDirPath)) globals.fs.directory(cacheDirPath),
directoriesToSearch.add(globals.fs.directory(cacheDirPath)); ];
}
final List<Directory> entities = <Directory>[]; final List<Directory> entities = <Directory>[];

View File

@ -811,14 +811,11 @@ class AndroidGradleBuilder implements AndroidBuilder {
_logger.printError(result.stderr, wrap: false); _logger.printError(result.stderr, wrap: false);
return const <String>[]; return const <String>[];
} }
final List<String> options = <String>[]; return <String>[
for (final String line in LineSplitter.split(result.stdout)) { for (final String line in LineSplitter.split(result.stdout))
final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line); if (_kBuildVariantRegex.firstMatch(line) case final RegExpMatch match)
if (match != null) { match.namedGroup(_kBuildVariantRegexGroupName)!,
options.add(match.namedGroup(_kBuildVariantRegexGroupName)!); ];
}
}
return options;
} }
@override @override

View File

@ -469,18 +469,15 @@ class _SymbolNode {
} }
Map<String, Object?> toJson() { 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, 'n': name,
'value': byteSize, '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;
} }
} }

View File

@ -71,14 +71,11 @@ class DeferredComponent {
/// status, but will result in [loadingUnits] returning an empty set. /// status, but will result in [loadingUnits] returning an empty set.
void assignLoadingUnits(List<LoadingUnit> allLoadingUnits) { void assignLoadingUnits(List<LoadingUnit> allLoadingUnits) {
_assigned = true; _assigned = true;
_loadingUnits = <LoadingUnit>{}; _loadingUnits = <LoadingUnit>{
for (final String lib in libraries) { for (final String lib in libraries)
for (final LoadingUnit loadingUnit in allLoadingUnits) { for (final LoadingUnit loadingUnit in allLoadingUnits)
if (loadingUnit.libraries.contains(lib)) { if (loadingUnit.libraries.contains(lib)) loadingUnit,
_loadingUnits!.add(loadingUnit); };
}
}
}
} }
/// Provides a human readable string representation of the /// Provides a human readable string representation of the
@ -193,21 +190,16 @@ class LoadingUnit {
} on FormatException catch (e) { } on FormatException catch (e) {
logger.printError('Loading unit manifest at `${manifestFile.path}` was invalid JSON:\n$e'); logger.printError('Loading unit manifest at `${manifestFile.path}` was invalid JSON:\n$e');
} }
final List<LoadingUnit> loadingUnits = <LoadingUnit>[]; // Set up android source directory
// Setup android source directory return <LoadingUnit>[
if (manifest != null) { if (manifest?['loadingUnits'] case final List<dynamic> loadingUnits)
for (final dynamic loadingUnitMetadata in manifest['loadingUnits'] as List<dynamic>) { for (final Map<String, dynamic> loadingUnitMap in loadingUnits.cast<Map<String, dynamic>>())
final Map<String, dynamic> loadingUnitMap = loadingUnitMetadata as Map<String, dynamic>; if (loadingUnitMap['id'] != 1) // skip base unit
if (loadingUnitMap['id'] == 1) { LoadingUnit(
continue; // Skip base unit id: loadingUnitMap['id'] as int,
} path: loadingUnitMap['path'] as String,
loadingUnits.add(LoadingUnit( libraries: List<String>.from(loadingUnitMap['libraries'] as List<dynamic>),
id: loadingUnitMap['id'] as int, ),
path: loadingUnitMap['path'] as String, ];
libraries: List<String>.from(loadingUnitMap['libraries'] as List<dynamic>)),
);
}
}
return loadingUnits;
} }
} }

View File

@ -69,13 +69,10 @@ class _DefaultShutdownHooks implements ShutdownHooks {
); );
_shutdownHooksRunning = true; _shutdownHooksRunning = true;
try { try {
final List<Future<dynamic>> futures = <Future<dynamic>>[]; final List<Future<dynamic>> futures = <Future<dynamic>>[
for (final ShutdownHook shutdownHook in registeredHooks) { for (final ShutdownHook shutdownHook in registeredHooks)
final FutureOr<dynamic> result = shutdownHook(); if (shutdownHook() case final Future<dynamic> result) result,
if (result is Future<dynamic>) { ];
futures.add(result);
}
}
await Future.wait<dynamic>(futures); await Future.wait<dynamic>(futures);
} finally { } finally {
_shutdownHooksRunning = false; _shutdownHooksRunning = false;

View File

@ -182,21 +182,13 @@ abstract class Target {
List<File> outputs, List<File> outputs,
Environment environment, Environment environment,
) { ) {
final File stamp = _findStampFile(environment); String getPath(File file) => file.path;
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;
final Map<String, Object> result = <String, Object>{ final Map<String, Object> result = <String, Object>{
'inputs': inputPaths, 'inputs': inputs.map(getPath).toList(),
'outputs': outputPaths, 'outputs': outputs.map(getPath).toList(),
if (key != null) 'buildKey': key, if (buildKey case final String key) 'buildKey': key,
}; };
final File stamp = _findStampFile(environment);
if (!stamp.existsSync()) { if (!stamp.existsSync()) {
stamp.createSync(); stamp.createSync();
} }

View File

@ -58,20 +58,12 @@ class DepfileService {
/// The [file] contains a list of newline separated file URIs. The output /// The [file] contains a list of newline separated file URIs. The output
/// file must be manually specified. /// file must be manually specified.
Depfile parseDart2js(File file, File output) { Depfile parseDart2js(File file, File output) {
final List<File> inputs = <File>[]; final List<File> inputs = <File>[
for (final String rawUri in file.readAsLinesSync()) { for (final String rawUri in file.readAsLinesSync())
if (rawUri.trim().isEmpty) { if (rawUri.trim().isNotEmpty)
continue; if (Uri.tryParse(rawUri) case final Uri fileUri when fileUri.scheme == 'file')
} _fileSystem.file(fileUri),
final Uri? fileUri = Uri.tryParse(rawUri); ];
if (fileUri == null) {
continue;
}
if (fileUri.scheme != 'file') {
continue;
}
inputs.add(_fileSystem.file(fileUri));
}
return Depfile(inputs, <File>[output]); return Depfile(inputs, <File>[output]);
} }

View File

@ -37,15 +37,11 @@ class DeferredComponentsGenSnapshotValidatorTarget extends Target {
/// The abis to validate. /// The abis to validate.
List<String> get _abis { List<String> get _abis {
final List<String> abis = <String>[]; return <String>[
for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies) { for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies)
if (deferredComponentsTargets.contains(target.name)) { if (deferredComponentsTargets.contains(target.name))
abis.add( getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)).archName,
getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)).archName ];
);
}
}
return abis;
} }
@override @override

View File

@ -112,19 +112,11 @@ abstract class BuildFrameworkCommand extends BuildSubCommand {
late final FlutterProject project = FlutterProject.current(); late final FlutterProject project = FlutterProject.current();
Future<List<BuildInfo>> getBuildInfos() async { Future<List<BuildInfo>> getBuildInfos() async {
final List<BuildInfo> buildInfos = <BuildInfo>[]; return <BuildInfo>[
if (boolArg('debug')) await getBuildInfo(forcedBuildMode: BuildMode.debug),
if (boolArg('debug')) { if (boolArg('profile')) await getBuildInfo(forcedBuildMode: BuildMode.profile),
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.debug)); if (boolArg('release')) await getBuildInfo(forcedBuildMode: BuildMode.release),
} ];
if (boolArg('profile')) {
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.profile));
}
if (boolArg('release')) {
buildInfos.add(await getBuildInfo(forcedBuildMode: BuildMode.release));
}
return buildInfos;
} }
@override @override

View File

@ -101,14 +101,11 @@ class CustomDeviceLogReader extends DeviceLogReader {
/// [logLines] as done. /// [logLines] as done.
@override @override
Future<void> dispose() async { Future<void> dispose() async {
final List<Future<void>> futures = <Future<void>>[]; final List<Future<void>> futures = <Future<void>>[
for (final StreamSubscription<String> subscription in subscriptions)
for (final StreamSubscription<String> subscription in subscriptions) { subscription.cancel(),
futures.add(subscription.cancel()); logLinesController.close(),
} ];
futures.add(logLinesController.close());
await Future.wait(futures); await Future.wait(futures);
} }

View File

@ -196,42 +196,16 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
@override @override
List<Workflow> get workflows { List<Workflow> get workflows {
if (_workflows == null) { return _workflows ??= <Workflow>[
_workflows = <Workflow>[]; if (globals.iosWorkflow!.appliesToHostPlatform) globals.iosWorkflow!,
if (androidWorkflow?.appliesToHostPlatform ?? false) androidWorkflow!,
if (globals.iosWorkflow!.appliesToHostPlatform) { if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) fuchsiaWorkflow!,
_workflows!.add(globals.iosWorkflow!); if (linuxWorkflow.appliesToHostPlatform) linuxWorkflow,
} if (macOSWorkflow.appliesToHostPlatform) macOSWorkflow,
if (windowsWorkflow?.appliesToHostPlatform ?? false) windowsWorkflow!,
if (androidWorkflow?.appliesToHostPlatform ?? false) { if (webWorkflow.appliesToHostPlatform) webWorkflow,
_workflows!.add(androidWorkflow!); if (customDeviceWorkflow.appliesToHostPlatform) customDeviceWorkflow,
} ];
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!;
} }
} }

View File

@ -316,14 +316,11 @@ public final class GeneratedPluginRegistrant {
'''; ''';
List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) { List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) {
final List<Map<String, Object?>> pluginConfigs = <Map<String, Object?>>[]; return <Map<String, Object?>>[
for (final Plugin p in plugins) { for (final Plugin plugin in plugins)
final PluginPlatform? platformPlugin = p.platforms[type]; if (plugin.platforms[type] case final PluginPlatform platformPlugin)
if (platformPlugin != null) { platformPlugin.toMap(),
pluginConfigs.add(platformPlugin.toMap()); ];
}
}
return pluginConfigs;
} }
Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async {

View File

@ -188,15 +188,10 @@ class FuchsiaDevices extends PollingDeviceDiscovery {
if (text == null || text.isEmpty) { if (text == null || text.isEmpty) {
return <Device>[]; return <Device>[];
} }
final List<FuchsiaDevice> devices = <FuchsiaDevice>[]; return <FuchsiaDevice>[
for (final String line in text) { for (final String line in text)
final FuchsiaDevice? device = await _parseDevice(line); if (await _parseDevice(line) case final FuchsiaDevice device) device,
if (device == null) { ];
continue;
}
devices.add(device);
}
return devices;
} }
@override @override

View File

@ -117,15 +117,12 @@ class IOSCoreDeviceControl {
Future<List<IOSCoreDevice>> getCoreDevices({ Future<List<IOSCoreDevice>> getCoreDevices({
Duration timeout = const Duration(seconds: _minimumTimeoutInSeconds), Duration timeout = const Duration(seconds: _minimumTimeoutInSeconds),
}) async { }) async {
final List<IOSCoreDevice> devices = <IOSCoreDevice>[];
final List<Object?> devicesSection = await _listCoreDevices(timeout: timeout); final List<Object?> devicesSection = await _listCoreDevices(timeout: timeout);
for (final Object? deviceObject in devicesSection) { return <IOSCoreDevice>[
if (deviceObject is Map<String, Object?>) { for (final Object? deviceObject in devicesSection)
devices.add(IOSCoreDevice.fromBetaJson(deviceObject, logger: _logger)); if (deviceObject is Map<String, Object?>)
} IOSCoreDevice.fromBetaJson(deviceObject, logger: _logger),
} ];
return devices;
} }
/// Executes `devicectl` command to get list of apps installed on the device. /// Executes `devicectl` command to get list of apps installed on the device.
@ -192,15 +189,12 @@ class IOSCoreDeviceControl {
required String deviceId, required String deviceId,
String? bundleId, String? bundleId,
}) async { }) async {
final List<IOSCoreDeviceInstalledApp> apps = <IOSCoreDeviceInstalledApp>[];
final List<Object?> appsData = await _listInstalledApps(deviceId: deviceId, bundleId: bundleId); final List<Object?> appsData = await _listInstalledApps(deviceId: deviceId, bundleId: bundleId);
for (final Object? appObject in appsData) { return <IOSCoreDeviceInstalledApp>[
if (appObject is Map<String, Object?>) { for (final Object? appObject in appsData)
apps.add(IOSCoreDeviceInstalledApp.fromBetaJson(appObject)); if (appObject is Map<String, Object?>)
} IOSCoreDeviceInstalledApp.fromBetaJson(appObject),
} ];
return apps;
} }
Future<bool> isAppInstalled({ Future<bool> isAppInstalled({
@ -401,15 +395,12 @@ class IOSCoreDevice {
Map<String, Object?> data, { Map<String, Object?> data, {
required Logger logger, required Logger logger,
}) { }) {
final List<_IOSCoreDeviceCapability> capabilitiesList = <_IOSCoreDeviceCapability>[]; final List<_IOSCoreDeviceCapability> capabilitiesList = <_IOSCoreDeviceCapability>[
if (data['capabilities'] is List<Object?>) { if (data['capabilities'] case final List<Object?> capabilitiesData)
final List<Object?> capabilitiesData = data['capabilities']! as List<Object?>; for (final Object? capabilityData in capabilitiesData)
for (final Object? capabilityData in capabilitiesData) { if (capabilityData != null && capabilityData is Map<String, Object?>)
if (capabilityData != null && capabilityData is Map<String, Object?>) { _IOSCoreDeviceCapability.fromBetaJson(capabilityData),
capabilitiesList.add(_IOSCoreDeviceCapability.fromBetaJson(capabilityData)); ];
}
}
}
_IOSCoreDeviceConnectionProperties? connectionProperties; _IOSCoreDeviceConnectionProperties? connectionProperties;
if (data['connectionProperties'] is Map<String, Object?>) { if (data['connectionProperties'] is Map<String, Object?>) {
@ -713,20 +704,17 @@ class _IOSCoreDeviceHardwareProperties {
required Logger logger, required Logger logger,
}) { }) {
_IOSCoreDeviceCPUType? cpuType; _IOSCoreDeviceCPUType? cpuType;
if (data['cpuType'] is Map<String, Object?>) { if (data['cpuType'] case final Map<String, Object?> betaJson) {
cpuType = _IOSCoreDeviceCPUType.fromBetaJson(data['cpuType']! as Map<String, Object?>); cpuType = _IOSCoreDeviceCPUType.fromBetaJson(betaJson);
} }
List<_IOSCoreDeviceCPUType>? supportedCPUTypes; List<_IOSCoreDeviceCPUType>? supportedCPUTypes;
if (data['supportedCPUTypes'] is List<Object?>) { if (data['supportedCPUTypes'] case final List<Object?> values) {
final List<Object?> values = data['supportedCPUTypes']! as List<Object?>; supportedCPUTypes = <_IOSCoreDeviceCPUType>[
final List<_IOSCoreDeviceCPUType> cpuTypes = <_IOSCoreDeviceCPUType>[]; for (final Object? cpuTypeData in values)
for (final Object? cpuTypeData in values) { if (cpuTypeData is Map<String, Object?>)
if (cpuTypeData is Map<String, Object?>) { _IOSCoreDeviceCPUType.fromBetaJson(cpuTypeData),
cpuTypes.add(_IOSCoreDeviceCPUType.fromBetaJson(cpuTypeData)); ];
}
}
supportedCPUTypes = cpuTypes;
} }
List<int>? supportedDeviceFamilies; List<int>? supportedDeviceFamilies;

View File

@ -782,15 +782,12 @@ class IOSDevice extends Device {
final List<Future<Uri?>> discoveryOptions = <Future<Uri?>>[ final List<Future<Uri?>> discoveryOptions = <Future<Uri?>>[
vmUrlFromMDns, vmUrlFromMDns,
// vmServiceDiscovery uses device logs (`idevicesyslog`), which doesn't work
// on wireless devices.
if (vmServiceDiscovery != null && !isWirelesslyConnected)
vmServiceDiscovery.uri,
]; ];
// vmServiceDiscovery uses device logs (`idevicesyslog`), which doesn't work
// on wireless devices.
if (vmServiceDiscovery != null && !isWirelesslyConnected) {
final Future<Uri?> vmUrlFromLogs = vmServiceDiscovery.uri;
discoveryOptions.add(vmUrlFromLogs);
}
Uri? localUri = await Future.any( Uri? localUri = await Future.any(
<Future<Uri?>>[...discoveryOptions, cancelCompleter.future], <Future<Uri?>>[...discoveryOptions, cancelCompleter.future],
); );

View File

@ -183,20 +183,14 @@ class SimControl {
/// Returns all the connected simulator devices. /// Returns all the connected simulator devices.
Future<List<BootedSimDevice>> getConnectedDevices() async { Future<List<BootedSimDevice>> getConnectedDevices() async {
final List<BootedSimDevice> devices = <BootedSimDevice>[];
final Map<String, Object?> devicesSection = await _listBootedDevices(); final Map<String, Object?> devicesSection = await _listBootedDevices();
for (final String deviceCategory in devicesSection.keys) { return <BootedSimDevice>[
final Object? devicesData = devicesSection[deviceCategory]; for (final String deviceCategory in devicesSection.keys)
if (devicesData != null && devicesData is List<Object?>) { if (devicesSection[deviceCategory] case final List<Object?> devicesData)
for (final Map<String, Object?> data in devicesData.map<Map<String, Object?>?>(castStringKeyedMap).whereType<Map<String, Object?>>()) { for (final Object? data in devicesData.map<Map<String, Object?>?>(castStringKeyedMap))
devices.add(BootedSimDevice(deviceCategory, data)); if (data is Map<String, Object?>) BootedSimDevice(deviceCategory, data),
} ];
}
}
return devices;
} }
Future<bool> isInstalled(String deviceId, String appId) { Future<bool> isInstalled(String deviceId, String appId) {

View File

@ -298,38 +298,29 @@ class Plugin {
if (yaml == null) { if (yaml == null) {
return <String>['Invalid "platforms" specification.']; return <String>['Invalid "platforms" specification.'];
} }
final List<String> errors = <String>[]; return <String>[
if (isInvalid(AndroidPlugin.kConfigKey, AndroidPlugin.validate)) { if (isInvalid(AndroidPlugin.kConfigKey, AndroidPlugin.validate))
errors.add('Invalid "android" plugin specification.'); 'Invalid "android" plugin specification.',
} if (isInvalid(IOSPlugin.kConfigKey, IOSPlugin.validate))
if (isInvalid(IOSPlugin.kConfigKey, IOSPlugin.validate)) { 'Invalid "ios" plugin specification.',
errors.add('Invalid "ios" plugin specification.'); if (isInvalid(LinuxPlugin.kConfigKey, LinuxPlugin.validate))
} 'Invalid "linux" plugin specification.',
if (isInvalid(LinuxPlugin.kConfigKey, LinuxPlugin.validate)) { if (isInvalid(MacOSPlugin.kConfigKey, MacOSPlugin.validate))
errors.add('Invalid "linux" plugin specification.'); 'Invalid "macos" plugin specification.',
} if (isInvalid(WindowsPlugin.kConfigKey, WindowsPlugin.validate))
if (isInvalid(MacOSPlugin.kConfigKey, MacOSPlugin.validate)) { 'Invalid "windows" plugin specification.',
errors.add('Invalid "macos" plugin specification.'); ];
}
if (isInvalid(WindowsPlugin.kConfigKey, WindowsPlugin.validate)) {
errors.add('Invalid "windows" plugin specification.');
}
return errors;
} }
static List<String> _validateLegacyYaml(YamlMap yaml) { static List<String> _validateLegacyYaml(YamlMap yaml) {
final List<String> errors = <String>[]; return <String>[
if (yaml['androidPackage'] is! String?)
if (yaml['androidPackage'] != null && yaml['androidPackage'] is! String) { 'The "androidPackage" must either be null or a string.',
errors.add('The "androidPackage" must either be null or a string.'); if (yaml['iosPrefix'] is! String?)
} 'The "iosPrefix" must either be null or a string.',
if (yaml['iosPrefix'] != null && yaml['iosPrefix'] is! String) { if (yaml['pluginClass'] is! String?)
errors.add('The "iosPrefix" must either be null or a string.'); 'The "pluginClass" must either be null or a string.',
} ];
if (yaml['pluginClass'] != null && yaml['pluginClass'] is! String) {
errors.add('The "pluginClass" must either be null or a string..');
}
return errors;
} }
static bool _supportsPlatform(YamlMap platformsYaml, String platformKey) { static bool _supportsPlatform(YamlMap platformsYaml, String platformKey) {

View File

@ -288,29 +288,16 @@ class FlutterProject {
/// Returns a list of platform names that are supported by the project. /// Returns a list of platform names that are supported by the project.
List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) { List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) {
final List<SupportedPlatform> platforms = includeRoot ? <SupportedPlatform>[SupportedPlatform.root] : <SupportedPlatform>[]; return <SupportedPlatform>[
if (android.existsSync()) { if (includeRoot) SupportedPlatform.root,
platforms.add(SupportedPlatform.android); if (android.existsSync()) SupportedPlatform.android,
} if (ios.exists) SupportedPlatform.ios,
if (ios.exists) { if (web.existsSync()) SupportedPlatform.web,
platforms.add(SupportedPlatform.ios); if (macos.existsSync()) SupportedPlatform.macos,
} if (linux.existsSync()) SupportedPlatform.linux,
if (web.existsSync()) { if (windows.existsSync()) SupportedPlatform.windows,
platforms.add(SupportedPlatform.web); if (fuchsia.existsSync()) SupportedPlatform.fuchsia,
} ];
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;
} }
/// The directory that will contain the example if an example exists. /// The directory that will contain the example if an example exists.

View File

@ -59,137 +59,53 @@ class VariableDumpMachineProjectValidator extends MachineProjectValidator {
@override @override
Future<List<ProjectValidatorResult>> start(FlutterProject project) async { Future<List<ProjectValidatorResult>> start(FlutterProject project) async {
final List<ProjectValidatorResult> result = <ProjectValidatorResult>[];
result.add(ProjectValidatorResult(
name: 'FlutterProject.directory',
value: _toJsonValue(project.directory.absolute.path),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.metadataFile',
value: _toJsonValue(project.metadataFile.absolute.path),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.android.exists',
value: _toJsonValue(project.android.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.ios.exists',
value: _toJsonValue(project.ios.exists),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.web.exists',
value: _toJsonValue(project.web.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.macos.exists',
value: _toJsonValue(project.macos.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.linux.exists',
value: _toJsonValue(project.linux.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.windows.exists',
value: _toJsonValue(project.windows.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.fuchsia.exists',
value: _toJsonValue(project.fuchsia.existsSync()),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.android.isKotlin',
value: _toJsonValue(project.android.isKotlin),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.ios.isSwift',
value: _toJsonValue(project.ios.isSwift),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.isModule',
value: _toJsonValue(project.isModule),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.isPlugin',
value: _toJsonValue(project.isPlugin),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'FlutterProject.manifest.appname',
value: _toJsonValue(project.manifest.appName),
status: StatusProjectValidator.info,
));
// FlutterVersion
final FlutterVersion version = FlutterVersion( final FlutterVersion version = FlutterVersion(
flutterRoot: Cache.flutterRoot!, flutterRoot: Cache.flutterRoot!,
fs: fileSystem, fs: fileSystem,
); );
result.add(ProjectValidatorResult( final Map<String, Object?> result = <String, Object?>{
name: 'FlutterVersion.frameworkRevision', 'FlutterProject.directory': project.directory.absolute.path,
value: _toJsonValue(version.frameworkRevision), 'FlutterProject.metadataFile': project.metadataFile.absolute.path,
status: StatusProjectValidator.info, 'FlutterProject.android.exists': project.android.existsSync(),
)); 'FlutterProject.ios.exists': project.ios.exists,
'FlutterProject.web.exists': project.web.existsSync(),
'FlutterProject.macos.exists': project.macos.existsSync(),
'FlutterProject.linux.exists': project.linux.existsSync(),
'FlutterProject.windows.exists': project.windows.existsSync(),
'FlutterProject.fuchsia.exists': project.fuchsia.existsSync(),
// Platform 'FlutterProject.android.isKotlin': project.android.isKotlin,
result.add(ProjectValidatorResult( 'FlutterProject.ios.isSwift': project.ios.isSwift,
name: 'Platform.operatingSystem',
value: _toJsonValue(platform.operatingSystem),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.isAndroid',
value: _toJsonValue(platform.isAndroid),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.isIOS',
value: _toJsonValue(platform.isIOS),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.isWindows',
value: _toJsonValue(platform.isWindows),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.isMacOS',
value: _toJsonValue(platform.isMacOS),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.isFuchsia',
value: _toJsonValue(platform.isFuchsia),
status: StatusProjectValidator.info,
));
result.add(ProjectValidatorResult(
name: 'Platform.pathSeparator',
value: _toJsonValue(platform.pathSeparator),
status: StatusProjectValidator.info,
));
// Cache 'FlutterProject.isModule': project.isModule,
result.add(ProjectValidatorResult( 'FlutterProject.isPlugin': project.isPlugin,
name: 'Cache.flutterRoot',
value: _toJsonValue(Cache.flutterRoot), 'FlutterProject.manifest.appname': project.manifest.appName,
status: StatusProjectValidator.info,
)); // FlutterVersion
return result; 'FlutterVersion.frameworkRevision': version.frameworkRevision,
// Platform
'Platform.operatingSystem': platform.operatingSystem,
'Platform.isAndroid': platform.isAndroid,
'Platform.isIOS': platform.isIOS,
'Platform.isWindows': platform.isWindows,
'Platform.isMacOS': platform.isMacOS,
'Platform.isFuchsia': platform.isFuchsia,
'Platform.pathSeparator': platform.pathSeparator,
// Cache
'Cache.flutterRoot': Cache.flutterRoot,
};
return <ProjectValidatorResult>[
for (final String key in result.keys)
ProjectValidatorResult(
name: key,
value: _toJsonValue(result[key]),
status: StatusProjectValidator.info,
),
];
} }
@override @override

View File

@ -62,19 +62,14 @@ class ProxyValidator extends DoctorValidator {
} }
Future<List<String>> _getLoopbackAddresses() async { Future<List<String>> _getLoopbackAddresses() async {
final List<String> loopBackAddresses = <String>['localhost'];
final List<NetworkInterface> networkInterfaces = final List<NetworkInterface> networkInterfaces =
await listNetworkInterfaces(includeLinkLocal: true, includeLoopback: true); await listNetworkInterfaces(includeLinkLocal: true, includeLoopback: true);
for (final NetworkInterface networkInterface in networkInterfaces) { return <String>[
for (final InternetAddress internetAddress in networkInterface.addresses) { 'localhost',
if (internetAddress.isLoopback) { for (final NetworkInterface networkInterface in networkInterfaces)
loopBackAddresses.add(internetAddress.address); for (final InternetAddress internetAddress in networkInterface.addresses)
} if (internetAddress.isLoopback) internetAddress.address,
} ];
}
return loopBackAddresses;
} }
} }

View File

@ -1452,17 +1452,12 @@ abstract class ResidentRunner extends ResidentHandlers {
Future<void> enableObservatory() async { Future<void> enableObservatory() async {
assert(debuggingOptions.serveObservatory); assert(debuggingOptions.serveObservatory);
final List<Future<vm_service.Response?>> serveObservatoryRequests = <Future<vm_service.Response?>>[]; final List<Future<vm_service.Response?>> serveObservatoryRequests = <Future<vm_service.Response?>>[
for (final FlutterDevice? device in flutterDevices) { for (final FlutterDevice? device in flutterDevices)
if (device == null) { if (device != null)
continue; // Notify the VM service if the user wants Observatory to be served.
} device.vmService?.callMethodWrapper('_serveObservatory') ?? Future<vm_service.Response?>.value(),
// Notify the VM service if the user wants Observatory to be served. ];
serveObservatoryRequests.add(
device.vmService?.callMethodWrapper('_serveObservatory') ??
Future<vm_service.Response?>.value(),
);
}
try { try {
await Future.wait(serveObservatoryRequests); await Future.wait(serveObservatoryRequests);
} on vm_service.RPCError catch (e) { } on vm_service.RPCError catch (e) {

View File

@ -35,11 +35,7 @@ class TestTimeRecorder {
@visibleForTesting @visibleForTesting
List<String> getPrintAsListForTesting() { List<String> getPrintAsListForTesting() {
final List<String> result = <String>[]; return TestTimePhases.values.map(_getPrintStringForPhase).toList();
for (final TestTimePhases phase in TestTimePhases.values) {
result.add(_getPrintStringForPhase(phase));
}
return result;
} }
@visibleForTesting @visibleForTesting

View File

@ -993,14 +993,11 @@ class FlutterVmService {
throw VmServiceDisappearedException(); throw VmServiceDisappearedException();
} }
final List<vm_service.IsolateRef> refs = <vm_service.IsolateRef>[]; return <vm_service.IsolateRef>[
for (final FlutterView flutterView in flutterViews) { for (final FlutterView flutterView in flutterViews)
final vm_service.IsolateRef? uiIsolate = flutterView.uiIsolate; if (flutterView.uiIsolate case final vm_service.IsolateRef uiIsolate)
if (uiIsolate != null) { uiIsolate,
refs.add(uiIsolate); ];
}
}
return refs;
} }
/// Attempt to retrieve the isolate with id [isolateId], or `null` if it has /// Attempt to retrieve the isolate with id [isolateId], or `null` if it has

View File

@ -52,12 +52,10 @@ abstract class WindowsApp extends ApplicationPackage {
globals.printError('Invalid prebuilt Windows app. Unable to extract from archive.'); globals.printError('Invalid prebuilt Windows app. Unable to extract from archive.');
return null; return null;
} }
final List<FileSystemEntity> exeFilesFound = <FileSystemEntity>[]; final List<FileSystemEntity> exeFilesFound = <FileSystemEntity>[
for (final FileSystemEntity file in tempDir.listSync()) { for (final FileSystemEntity file in tempDir.listSync())
if (file.basename.endsWith('.exe')) { if (file.basename.endsWith('.exe')) file,
exeFilesFound.add(file); ];
}
}
if (exeFilesFound.isEmpty) { if (exeFilesFound.isEmpty) {
globals.printError('Cannot find .exe files in the zip archive.'); globals.printError('Cannot find .exe files in the zip archive.');

View File

@ -385,14 +385,11 @@ class IosProject extends XcodeBasedProject {
)?.cast<String>(); )?.cast<String>();
if (domains != null) { if (domains != null) {
final List<String> result = <String>[]; return <String>[
for (final String domain in domains) { for (final String domain in domains)
final RegExpMatch? match = _associatedDomainPattern.firstMatch(domain); if (_associatedDomainPattern.firstMatch(domain) case final RegExpMatch match)
if (match != null) { match.group(1)!,
result.add(match.group(1)!); ];
}
}
return result;
} }
} }
} }

View File

@ -836,14 +836,12 @@ class _FakeDeviceManager extends DeviceManager {
@override @override
Future<List<Device>> getAllDevices({DeviceDiscoveryFilter? filter}) async { Future<List<Device>> getAllDevices({DeviceDiscoveryFilter? filter}) async {
final List<Device> devices = <Device>[]; final DeviceConnectionInterface? interface = filter?.deviceConnectionInterface;
for (final FakeDeviceJsonData deviceJson in fakeDevices) { return <Device>[
if (filter?.deviceConnectionInterface == null || for (final FakeDeviceJsonData deviceJson in fakeDevices)
deviceJson.dev.connectionInterface == filter?.deviceConnectionInterface) { if (interface == null || deviceJson.dev.connectionInterface == interface)
devices.add(deviceJson.dev); deviceJson.dev,
} ];
}
return devices;
} }
@override @override