Remove unnecessary null checks in flutter_tool (#118857)

* dart fix --apply

* manual fixes

* fix after merge conflicts

* review
This commit is contained in:
Michael Goderbauer 2023-01-23 13:43:08 -08:00 committed by GitHub
parent edb571e49b
commit 38630b6bd1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
108 changed files with 286 additions and 653 deletions

View File

@ -147,7 +147,7 @@ class AndroidDevices extends PollingDeviceDiscovery {
final String deviceID = match[1]!; final String deviceID = match[1]!;
final String deviceState = match[2]!; final String deviceState = match[2]!;
String rest = match[3]!; String? rest = match[3];
final Map<String, String> info = <String, String>{}; final Map<String, String> info = <String, String>{};
if (rest != null && rest.isNotEmpty) { if (rest != null && rest.isNotEmpty) {

View File

@ -62,9 +62,7 @@ class AndroidEmulators extends EmulatorDiscovery {
<String>[emulatorPath, '-list-avds'])).stdout.trim(); <String>[emulatorPath, '-list-avds'])).stdout.trim();
final List<AndroidEmulator> emulators = <AndroidEmulator>[]; final List<AndroidEmulator> emulators = <AndroidEmulator>[];
if (listAvdsOutput != null) { _extractEmulatorAvdInfo(listAvdsOutput, emulators);
_extractEmulatorAvdInfo(listAvdsOutput, emulators);
}
return emulators; return emulators;
} }

View File

@ -435,11 +435,9 @@ class AndroidSdk {
throwOnError: true, throwOnError: true,
hideStdout: true, hideStdout: true,
).stdout.trim(); ).stdout.trim();
if (javaHomeOutput != null) { if (javaHomeOutput.isNotEmpty) {
if ((javaHomeOutput != null) && (javaHomeOutput.isNotEmpty)) { final String javaHome = javaHomeOutput.split('\n').last.trim();
final String javaHome = javaHomeOutput.split('\n').last.trim(); return fileSystem.path.join(javaHome, 'bin', 'java');
return fileSystem.path.join(javaHome, 'bin', 'java');
}
} }
} on Exception { /* ignore */ } } on Exception { /* ignore */ }
} }
@ -500,10 +498,7 @@ class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
required this.platformName, required this.platformName,
required this.buildToolsVersion, required this.buildToolsVersion,
required FileSystem fileSystem, required FileSystem fileSystem,
}) : assert(sdkLevel != null), }) : _fileSystem = fileSystem;
assert(platformName != null),
assert(buildToolsVersion != null),
_fileSystem = fileSystem;
final AndroidSdk sdk; final AndroidSdk sdk;
final int sdkLevel; final int sdkLevel;

View File

@ -110,7 +110,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
// and <base dir>/system/.home for Android Studio < 4.1 // and <base dir>/system/.home for Android Studio < 4.1
String dotHomeFilePath; String dotHomeFilePath;
if (major != null && major >= 4 && minor != null && minor >= 1) { if (major >= 4 && minor >= 1) {
dotHomeFilePath = globals.fs.path.join(homeDotDir.path, '.home'); dotHomeFilePath = globals.fs.path.join(homeDotDir.path, '.home');
} else { } else {
dotHomeFilePath = dotHomeFilePath =
@ -161,7 +161,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
if (globals.platform.isMacOS) { if (globals.platform.isMacOS) {
/// plugin path of Android Studio has been changed after version 4.1. /// plugin path of Android Studio has been changed after version 4.1.
if (major != null && major >= 4 && minor != null && minor >= 1) { if (major >= 4 && minor >= 1) {
return globals.fs.path.join( return globals.fs.path.join(
homeDirPath, homeDirPath,
'Library', 'Library',
@ -185,7 +185,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
return toolboxPluginsPath; return toolboxPluginsPath;
} }
if (major != null && major >= 4 && minor != null && minor >= 1 && if (major >= 4 && minor >= 1 &&
globals.platform.isLinux) { globals.platform.isLinux) {
return globals.fs.path.join( return globals.fs.path.join(
homeDirPath, homeDirPath,
@ -394,7 +394,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
version: Version.parse(version), version: Version.parse(version),
studioAppName: title, studioAppName: title,
); );
if (studio != null && !hasStudioAt(studio.directory, newerThan: studio.version)) { if (!hasStudioAt(studio.directory, newerThan: studio.version)) {
studios.removeWhere((AndroidStudio other) => other.directory == studio.directory); studios.removeWhere((AndroidStudio other) => other.directory == studio.directory);
studios.add(studio); studios.add(studio);
} }
@ -425,9 +425,6 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
static String? extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) { static String? extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) {
if (plistValue == null || keyMatcher == null) {
return null;
}
return keyMatcher.stringMatch(plistValue)?.split('=').last.trim().replaceAll('"', ''); return keyMatcher.stringMatch(plistValue)?.split('=').last.trim().replaceAll('"', '');
} }

View File

@ -27,8 +27,7 @@ class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackag
required this.applicationPackage, required this.applicationPackage,
required this.versionCode, required this.versionCode,
required this.launchActivity, required this.launchActivity,
}) : assert(applicationPackage != null), });
assert(launchActivity != null);
/// Creates a new AndroidApk from an existing APK. /// Creates a new AndroidApk from an existing APK.
/// ///
@ -294,7 +293,7 @@ class ApkManifestData {
} }
static ApkManifestData? parseFromXmlDump(String data, Logger logger) { static ApkManifestData? parseFromXmlDump(String data, Logger logger) {
if (data == null || data.trim().isEmpty) { if (data.trim().isEmpty) {
return null; return null;
} }

View File

@ -187,12 +187,6 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
loadingUnitComparisonResults = <String, Object>{}; loadingUnitComparisonResults = <String, Object>{};
final Set<LoadingUnit> unmatchedLoadingUnits = <LoadingUnit>{}; final Set<LoadingUnit> unmatchedLoadingUnits = <LoadingUnit>{};
final List<LoadingUnit> newLoadingUnits = <LoadingUnit>[]; final List<LoadingUnit> newLoadingUnits = <LoadingUnit>[];
if (generatedLoadingUnits == null || cachedLoadingUnits == null) {
loadingUnitComparisonResults!['new'] = newLoadingUnits;
loadingUnitComparisonResults!['missing'] = unmatchedLoadingUnits;
loadingUnitComparisonResults!['match'] = false;
return false;
}
unmatchedLoadingUnits.addAll(cachedLoadingUnits); unmatchedLoadingUnits.addAll(cachedLoadingUnits);
final Set<int> addedNewIds = <int>{}; final Set<int> addedNewIds = <int>{};
for (final LoadingUnit genUnit in generatedLoadingUnits) { for (final LoadingUnit genUnit in generatedLoadingUnits) {
@ -335,7 +329,7 @@ loading-units:
continue; continue;
} }
buffer.write(' - id: ${unit.id}\n'); buffer.write(' - id: ${unit.id}\n');
if (unit.libraries != null && unit.libraries.isNotEmpty) { if (unit.libraries.isNotEmpty) {
buffer.write(' libraries:\n'); buffer.write(' libraries:\n');
for (final String lib in unit.libraries) { for (final String lib in unit.libraries) {
buffer.write(' - $lib\n'); buffer.write(' - $lib\n');

View File

@ -51,7 +51,7 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
/// valid, as there are many ways that they can be validly configured. /// valid, as there are many ways that they can be validly configured.
Future<bool> checkAndroidDynamicFeature(List<DeferredComponent> components) async { Future<bool> checkAndroidDynamicFeature(List<DeferredComponent> components) async {
inputs.add(projectDir.childFile('pubspec.yaml')); inputs.add(projectDir.childFile('pubspec.yaml'));
if (components == null || components.isEmpty) { if (components.isEmpty) {
return false; return false;
} }
bool changesMade = false; bool changesMade = false;
@ -124,7 +124,7 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
.childDirectory('values') .childDirectory('values')
.childFile('strings.xml'); .childFile('strings.xml');
ErrorHandlingFileSystem.deleteIfExists(stringResOutput); ErrorHandlingFileSystem.deleteIfExists(stringResOutput);
if (components == null || components.isEmpty) { if (components.isEmpty) {
return true; return true;
} }
final Map<String, String> requiredEntriesMap = <String, String>{}; final Map<String, String> requiredEntriesMap = <String, String>{};
@ -148,7 +148,7 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
for (final XmlElement element in resources.findElements('string')) { for (final XmlElement element in resources.findElements('string')) {
final String? name = element.getAttribute('name'); final String? name = element.getAttribute('name');
if (requiredEntriesMap.containsKey(name)) { if (requiredEntriesMap.containsKey(name)) {
if (element.text != null && element.text != requiredEntriesMap[name]) { if (element.text != requiredEntriesMap[name]) {
element.innerText = requiredEntriesMap[name]!; element.innerText = requiredEntriesMap[name]!;
modified = true; modified = true;
} }

View File

@ -122,7 +122,7 @@ abstract class DeferredComponentsValidator {
} }
} }
// Log diff file contents, with color highlighting // Log diff file contents, with color highlighting
if (diffLines != null && diffLines.isNotEmpty) { if (diffLines.isNotEmpty) {
logger.printStatus('Diff between `android` and expected files:', emphasis: true); logger.printStatus('Diff between `android` and expected files:', emphasis: true);
logger.printStatus(''); logger.printStatus('');
for (final String line in diffLines) { for (final String line in diffLines) {
@ -163,7 +163,7 @@ abstract class DeferredComponentsValidator {
The above files have been placed into `build/$kDeferredComponentsTempDirectory`, The above files have been placed into `build/$kDeferredComponentsTempDirectory`,
a temporary directory. The files should be reviewed and moved into the project's a temporary directory. The files should be reviewed and moved into the project's
`android` directory.'''); `android` directory.''');
if (diffLines != null && diffLines.isNotEmpty && !platform.isWindows) { if (diffLines.isNotEmpty && !platform.isWindows) {
logger.printStatus(r''' logger.printStatus(r'''
The recommended changes can be quickly applied by running: The recommended changes can be quickly applied by running:

View File

@ -229,11 +229,6 @@ class AndroidGradleBuilder implements AndroidBuilder {
int retry = 0, int retry = 0,
@visibleForTesting int? maxRetries, @visibleForTesting int? maxRetries,
}) async { }) async {
assert(project != null);
assert(androidBuildInfo != null);
assert(target != null);
assert(isBuildingBundle != null);
assert(localGradleErrors != null);
if (!project.android.isSupportedVersion) { if (!project.android.isSupportedVersion) {
_exitWithUnsupportedProjectMessage(_usage, _logger.terminal); _exitWithUnsupportedProjectMessage(_usage, _logger.terminal);
@ -299,9 +294,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
.map(getPlatformNameForAndroidArch).join(','); .map(getPlatformNameForAndroidArch).join(',');
command.add('-Ptarget-platform=$targetPlatforms'); command.add('-Ptarget-platform=$targetPlatforms');
} }
if (target != null) { command.add('-Ptarget=$target');
command.add('-Ptarget=$target');
}
// Only attempt adding multidex support if all the flutter generated files exist. // Only attempt adding multidex support if all the flutter generated files exist.
// If the files do not exist and it was unintentional, the app will fail to build // If the files do not exist and it was unintentional, the app will fail to build
// and prompt the developer if they wish Flutter to add the files again via gradle_error.dart. // and prompt the developer if they wish Flutter to add the files again via gradle_error.dart.
@ -342,7 +335,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
} }
} }
command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) { if (buildInfo.fileSystemRoots.isNotEmpty) {
command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}');
} }
if (buildInfo.fileSystemScheme != null) { if (buildInfo.fileSystemScheme != null) {
@ -557,10 +550,6 @@ class AndroidGradleBuilder implements AndroidBuilder {
required Directory outputDirectory, required Directory outputDirectory,
required String buildNumber, required String buildNumber,
}) async { }) async {
assert(project != null);
assert(target != null);
assert(androidBuildInfo != null);
assert(outputDirectory != null);
final FlutterManifest manifest = project.manifest; final FlutterManifest manifest = project.manifest;
if (!manifest.isModule && !manifest.isPlugin) { if (!manifest.isModule && !manifest.isPlugin) {
@ -600,7 +589,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
command.add('--no-daemon'); command.add('--no-daemon');
} }
if (target != null && target.isNotEmpty) { if (target.isNotEmpty) {
command.add('-Ptarget=$target'); command.add('-Ptarget=$target');
} }
command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
@ -699,8 +688,7 @@ void printHowToConsumeAar({
required FileSystem fileSystem, required FileSystem fileSystem,
String? buildNumber, String? buildNumber,
}) { }) {
assert(buildModes != null && buildModes.isNotEmpty); assert(buildModes.isNotEmpty);
assert(repoDirectory != null);
buildNumber ??= '1.0'; buildNumber ??= '1.0';
logger.printStatus('\nConsuming the Module', emphasis: true); logger.printStatus('\nConsuming the Module', emphasis: true);
@ -913,8 +901,6 @@ Never _exitWithExpectedFileNotFound({
required Logger logger, required Logger logger,
required Usage usage, required Usage usage,
}) { }) {
assert(project != null);
assert(fileExtension != null);
final String androidGradlePluginVersion = final String androidGradlePluginVersion =
getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger); getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger);
@ -984,8 +970,6 @@ Directory _getLocalEngineRepo({
required AndroidBuildInfo androidBuildInfo, required AndroidBuildInfo androidBuildInfo,
required FileSystem fileSystem, required FileSystem fileSystem,
}) { }) {
assert(engineOutPath != null);
assert(androidBuildInfo != null);
final String abi = _getAbiByLocalEnginePath(engineOutPath); final String abi = _getAbiByLocalEnginePath(engineOutPath);
final Directory localEngineRepo = fileSystem.systemTempDirectory final Directory localEngineRepo = fileSystem.systemTempDirectory

View File

@ -337,7 +337,6 @@ final GradleHandledError licenseNotAcceptedHandler = GradleHandledError(
r'You have not accepted the license agreements of the following SDK components:\s*\[(.+)\]'; r'You have not accepted the license agreements of the following SDK components:\s*\[(.+)\]';
final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true); final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true);
assert(licenseFailure != null);
final Match? licenseMatch = licenseFailure.firstMatch(line); final Match? licenseMatch = licenseFailure.firstMatch(line);
globals.printBox( globals.printBox(
'${globals.logger.terminal.warningMark} Unable to download needed Android SDK components, as the ' '${globals.logger.terminal.warningMark} Unable to download needed Android SDK components, as the '

View File

@ -151,8 +151,6 @@ bool _isWithinVersionRange(
required String min, required String min,
required String max, required String max,
}) { }) {
assert(min != null);
assert(max != null);
final Version? parsedTargetVersion = Version.parse(targetVersion); final Version? parsedTargetVersion = Version.parse(targetVersion);
final Version? minVersion = Version.parse(min); final Version? minVersion = Version.parse(min);
final Version? maxVersion = Version.parse(max); final Version? maxVersion = Version.parse(max);

View File

@ -18,8 +18,7 @@ abstract class ApplicationPackageFactory {
} }
abstract class ApplicationPackage { abstract class ApplicationPackage {
ApplicationPackage({ required this.id }) ApplicationPackage({ required this.id });
: assert(id != null);
/// Package ID from the Android Manifest or equivalent. /// Package ID from the Android Manifest or equivalent.
final String id; final String id;

View File

@ -625,7 +625,6 @@ class CachedArtifacts implements Artifacts {
} }
String _getHostArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode) { String _getHostArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode) {
assert(platform != null);
switch (artifact) { switch (artifact) {
case Artifact.genSnapshot: case Artifact.genSnapshot:
// For script snapshots any gen_snapshot binary will do. Returning gen_snapshot for // For script snapshots any gen_snapshot binary will do. Returning gen_snapshot for
@ -1227,7 +1226,7 @@ class OverrideArtifacts implements Artifacts {
this.engineDartBinary, this.engineDartBinary,
this.platformKernelDill, this.platformKernelDill,
this.flutterPatchedSdk, this.flutterPatchedSdk,
}) : assert(parent != null); });
final Artifacts parent; final Artifacts parent;
final File? frontendServer; final File? frontendServer;

View File

@ -200,9 +200,6 @@ class ManifestAssetBundle implements AssetBundle {
} }
for (final File file in directory.listSync().whereType<File>()) { for (final File file in directory.listSync().whereType<File>()) {
final DateTime dateTime = file.statSync().modified; final DateTime dateTime = file.statSync().modified;
if (dateTime == null) {
continue;
}
if (dateTime.isAfter(lastBuildTimestamp)) { if (dateTime.isAfter(lastBuildTimestamp)) {
return true; return true;
} }
@ -301,7 +298,7 @@ class ManifestAssetBundle implements AssetBundle {
final Map<String, List<File>> additionalLicenseFiles = <String, List<File>>{}; final Map<String, List<File>> additionalLicenseFiles = <String, List<File>>{};
for (final Package package in packageConfig.packages) { for (final Package package in packageConfig.packages) {
final Uri packageUri = package.packageUriRoot; final Uri packageUri = package.packageUriRoot;
if (packageUri != null && packageUri.scheme == 'file') { if (packageUri.scheme == 'file') {
final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml')); final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml'));
inputFiles.add(_fileSystem.file(packageManifestPath)); inputFiles.add(_fileSystem.file(packageManifestPath));
final FlutterManifest? packageFlutterManifest = FlutterManifest.createFromPath( final FlutterManifest? packageFlutterManifest = FlutterManifest.createFromPath(
@ -390,34 +387,32 @@ class ManifestAssetBundle implements AssetBundle {
} }
// Save the contents of each deferred component image, image variant, and font // Save the contents of each deferred component image, image variant, and font
// asset in deferredComponentsEntries. // asset in deferredComponentsEntries.
if (deferredComponentsAssetVariants != null) { for (final String componentName in deferredComponentsAssetVariants.keys) {
for (final String componentName in deferredComponentsAssetVariants.keys) { deferredComponentsEntries[componentName] = <String, DevFSContent>{};
deferredComponentsEntries[componentName] = <String, DevFSContent>{}; final Map<_Asset, List<_Asset>> assetsMap = deferredComponentsAssetVariants[componentName]!;
final Map<_Asset, List<_Asset>> assetsMap = deferredComponentsAssetVariants[componentName]!; for (final _Asset asset in assetsMap.keys) {
for (final _Asset asset in assetsMap.keys) { final File assetFile = asset.lookupAssetFile(_fileSystem);
final File assetFile = asset.lookupAssetFile(_fileSystem); if (!assetFile.existsSync() && assetsMap[asset]!.isEmpty) {
if (!assetFile.existsSync() && assetsMap[asset]!.isEmpty) { _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true); _logger.printError('No file or variants found for $asset.\n');
_logger.printError('No file or variants found for $asset.\n'); if (asset.package != null) {
if (asset.package != null) { _logger.printError('This asset was included from package ${asset.package?.name}.');
_logger.printError('This asset was included from package ${asset.package?.name}.');
}
return 1;
}
// The file name for an asset's "main" entry is whatever appears in
// the pubspec.yaml file. The main entry's file must always exist for
// font assets. It need not exist for an image if resolution-specific
// variant files exist. An image's main entry is treated the same as a
// "1x" resolution variant and if both exist then the explicit 1x
// variant is preferred.
if (assetFile.existsSync() && !assetsMap[asset]!.contains(asset)) {
assetsMap[asset]!.insert(0, asset);
}
for (final _Asset variant in assetsMap[asset]!) {
final File variantFile = variant.lookupAssetFile(_fileSystem);
assert(variantFile.existsSync());
deferredComponentsEntries[componentName]![variant.entryUri.path] ??= DevFSFileContent(variantFile);
} }
return 1;
}
// The file name for an asset's "main" entry is whatever appears in
// the pubspec.yaml file. The main entry's file must always exist for
// font assets. It need not exist for an image if resolution-specific
// variant files exist. An image's main entry is treated the same as a
// "1x" resolution variant and if both exist then the explicit 1x
// variant is preferred.
if (assetFile.existsSync() && !assetsMap[asset]!.contains(asset)) {
assetsMap[asset]!.insert(0, asset);
}
for (final _Asset variant in assetsMap[asset]!) {
final File variantFile = variant.lookupAssetFile(_fileSystem);
assert(variantFile.existsSync());
deferredComponentsEntries[componentName]![variant.entryUri.path] ??= DevFSFileContent(variantFile);
} }
} }
} }
@ -665,15 +660,13 @@ class ManifestAssetBundle implements AssetBundle {
variant.entryUri.path, variant.entryUri.path,
]; ];
}); });
if (deferredComponentsAssetVariants != null) { for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) {
for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) { componentAssets.forEach((_Asset main, List<_Asset> variants) {
componentAssets.forEach((_Asset main, List<_Asset> variants) { entries[main] = <String>[
entries[main] = <String>[ for (final _Asset variant in variants)
for (final _Asset variant in variants) variant.entryUri.path,
variant.entryUri.path, ];
]; });
});
}
} }
final List<_Asset> sortedKeys = entries.keys.toList() final List<_Asset> sortedKeys = entries.keys.toList()
..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path)); ..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path));

View File

@ -430,9 +430,7 @@ class _SymbolNode {
_SymbolNode( _SymbolNode(
this.name, { this.name, {
this.byteSize = 0, this.byteSize = 0,
}) : assert(name != null), }) : _children = <String, _SymbolNode>{};
assert(byteSize != null),
_children = <String, _SymbolNode>{};
/// The human friendly identifier for this node. /// The human friendly identifier for this node.
String name; String name;

View File

@ -14,8 +14,7 @@ import 'process.dart';
/// A snapshot build configuration. /// A snapshot build configuration.
class SnapshotType { class SnapshotType {
SnapshotType(this.platform, this.mode) SnapshotType(this.platform, this.mode);
: assert(mode != null);
final TargetPlatform? platform; final TargetPlatform? platform;
final BuildMode mode; final BuildMode mode;
@ -145,7 +144,7 @@ class AOTSnapshotter {
// We strip snapshot by default, but allow to suppress this behavior // We strip snapshot by default, but allow to suppress this behavior
// by supplying --no-strip in extraGenSnapshotOptions. // by supplying --no-strip in extraGenSnapshotOptions.
bool shouldStrip = true; bool shouldStrip = true;
if (extraGenSnapshotOptions != null && extraGenSnapshotOptions.isNotEmpty) { if (extraGenSnapshotOptions.isNotEmpty) {
_logger.printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions'); _logger.printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions');
for (final String option in extraGenSnapshotOptions) { for (final String option in extraGenSnapshotOptions) {
if (option == '--no-strip') { if (option == '--no-strip') {

View File

@ -220,7 +220,7 @@ class CommandHelpOption {
/// Text shown in parenthesis to give the context. /// Text shown in parenthesis to give the context.
final String inParenthesis; final String inParenthesis;
bool get _hasTextInParenthesis => inParenthesis != null && inParenthesis.isNotEmpty; bool get _hasTextInParenthesis => inParenthesis.isNotEmpty;
int get _rawMessageLength => key.length + description.length; int get _rawMessageLength => key.length + description.length;

View File

@ -71,9 +71,6 @@ class DeferredComponent {
void assignLoadingUnits(List<LoadingUnit> allLoadingUnits) { void assignLoadingUnits(List<LoadingUnit> allLoadingUnits) {
_assigned = true; _assigned = true;
_loadingUnits = <LoadingUnit>{}; _loadingUnits = <LoadingUnit>{};
if (allLoadingUnits == null) {
return;
}
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)) {

View File

@ -40,8 +40,6 @@ class ErrorHandlingFileSystem extends ForwardingFileSystem {
required FileSystem delegate, required FileSystem delegate,
required Platform platform, required Platform platform,
}) : }) :
assert(delegate != null),
assert(platform != null),
_platform = platform, _platform = platform,
super(delegate); super(delegate);
@ -164,9 +162,6 @@ class ErrorHandlingFile
required this.fileSystem, required this.fileSystem,
required this.delegate, required this.delegate,
}) : }) :
assert(platform != null),
assert(fileSystem != null),
assert(delegate != null),
_platform = platform; _platform = platform;
@override @override
@ -379,9 +374,6 @@ class ErrorHandlingDirectory
required this.fileSystem, required this.fileSystem,
required this.delegate, required this.delegate,
}) : }) :
assert(platform != null),
assert(fileSystem != null),
assert(delegate != null),
_platform = platform; _platform = platform;
@override @override
@ -518,9 +510,6 @@ class ErrorHandlingLink
required this.fileSystem, required this.fileSystem,
required this.delegate, required this.delegate,
}) : }) :
assert(platform != null),
assert(fileSystem != null),
assert(delegate != null),
_platform = platform; _platform = platform;
@override @override
@ -563,7 +552,6 @@ Future<T> _run<T>(Future<T> Function() op, {
String? failureMessage, String? failureMessage,
String? posixPermissionSuggestion, String? posixPermissionSuggestion,
}) async { }) async {
assert(platform != null);
try { try {
return await op(); return await op();
} on ProcessPackageExecutableNotFoundException catch (e) { } on ProcessPackageExecutableNotFoundException catch (e) {
@ -595,7 +583,6 @@ T _runSync<T>(T Function() op, {
String? failureMessage, String? failureMessage,
String? posixPermissionSuggestion, String? posixPermissionSuggestion,
}) { }) {
assert(platform != null);
try { try {
return op(); return op();
} on ProcessPackageExecutableNotFoundException catch (e) { } on ProcessPackageExecutableNotFoundException catch (e) {

View File

@ -22,8 +22,6 @@ class Fingerprinter {
required FileSystem fileSystem, required FileSystem fileSystem,
required Logger logger, required Logger logger,
}) : _paths = paths.toList(), }) : _paths = paths.toList(),
assert(fingerprintPath != null),
assert(paths != null && paths.every((String path) => path != null)),
_logger = logger, _logger = logger,
_fileSystem = fileSystem; _fileSystem = fileSystem;

View File

@ -399,7 +399,6 @@ class _DefaultProcessInfo implements ProcessInfo {
@override @override
File writePidFile(String pidFile) { File writePidFile(String pidFile) {
assert(pidFile != null);
return _fileSystem.file(pidFile) return _fileSystem.file(pidFile)
..writeAsStringSync(io.pid.toString()); ..writeAsStringSync(io.pid.toString());
} }
@ -419,7 +418,6 @@ class _TestProcessInfo implements ProcessInfo {
@override @override
File writePidFile(String pidFile) { File writePidFile(String pidFile) {
assert(pidFile != null);
return _fileSystem.file(pidFile) return _fileSystem.file(pidFile)
..writeAsStringSync('12345'); ..writeAsStringSync('12345');
} }

View File

@ -877,7 +877,6 @@ class BufferLogger extends Logger {
String? progressId, String? progressId,
int progressIndicatorPadding = kDefaultStatusPadding, int progressIndicatorPadding = kDefaultStatusPadding,
}) { }) {
assert(progressIndicatorPadding != null);
printStatus(message); printStatus(message);
return SilentStatus( return SilentStatus(
stopwatch: _stopwatchFactory.createStopwatch(), stopwatch: _stopwatchFactory.createStopwatch(),
@ -1020,7 +1019,6 @@ class VerboseLogger extends DelegatingLogger {
String? progressId, String? progressId,
int progressIndicatorPadding = kDefaultStatusPadding, int progressIndicatorPadding = kDefaultStatusPadding,
}) { }) {
assert(progressIndicatorPadding != null);
printStatus(message); printStatus(message);
final Stopwatch timer = _stopwatchFactory.createStopwatch()..start(); final Stopwatch timer = _stopwatchFactory.createStopwatch()..start();
return SilentStatus( return SilentStatus(
@ -1356,7 +1354,6 @@ class AnonymousSpinnerStatus extends Status {
void _callback(Timer timer) { void _callback(Timer timer) {
assert(this.timer == timer); assert(this.timer == timer);
assert(timer != null);
assert(timer.isActive); assert(timer.isActive);
_writeToStdOut(_backspaceChar * _lastAnimationFrameLength); _writeToStdOut(_backspaceChar * _lastAnimationFrameLength);
ticks += 1; ticks += 1;

View File

@ -44,8 +44,7 @@ class MultiRootFileSystem extends ForwardingFileSystem {
required FileSystem delegate, required FileSystem delegate,
required String scheme, required String scheme,
required List<String> roots, required List<String> roots,
}) : assert(delegate != null), }) : assert(roots.isNotEmpty),
assert(roots.isNotEmpty),
_scheme = scheme, _scheme = scheme,
_roots = roots.map((String root) => delegate.path.normalize(root)).toList(), _roots = roots.map((String root) => delegate.path.normalize(root)).toList(),
super(delegate); super(delegate);

View File

@ -133,7 +133,6 @@ class Net {
_logger.printTrace('Download error: $error'); _logger.printTrace('Download error: $error');
return false; return false;
} }
assert(response != null);
// If we're making a HEAD request, we're only checking to see if the URL is // If we're making a HEAD request, we're only checking to see if the URL is
// valid. // valid.

View File

@ -90,7 +90,7 @@ abstract class OperatingSystemUtils {
/// if `which` was not able to locate the binary. /// if `which` was not able to locate the binary.
File? which(String execName) { File? which(String execName) {
final List<File> result = _which(execName); final List<File> result = _which(execName);
if (result == null || result.isEmpty) { if (result.isEmpty) {
return null; return null;
} }
return result.first; return result.first;

View File

@ -98,8 +98,7 @@ class ProcessExit implements Exception {
class RunResult { class RunResult {
RunResult(this.processResult, this._command) RunResult(this.processResult, this._command)
: assert(_command != null), : assert(_command.isNotEmpty);
assert(_command.isNotEmpty);
final ProcessResult processResult; final ProcessResult processResult;
@ -256,7 +255,7 @@ class _DefaultProcessUtils implements ProcessUtils {
Duration? timeout, Duration? timeout,
int timeoutRetries = 0, int timeoutRetries = 0,
}) async { }) async {
if (cmd == null || cmd.isEmpty) { if (cmd.isEmpty) {
throw ArgumentError('cmd must be a non-empty list'); throw ArgumentError('cmd must be a non-empty list');
} }
if (timeoutRetries < 0) { if (timeoutRetries < 0) {

View File

@ -226,7 +226,6 @@ class AnsiTerminal implements Terminal {
@override @override
String bolden(String message) { String bolden(String message) {
assert(message != null);
if (!supportsColor || message.isEmpty) { if (!supportsColor || message.isEmpty) {
return message; return message;
} }
@ -247,8 +246,7 @@ class AnsiTerminal implements Terminal {
@override @override
String color(String message, TerminalColor color) { String color(String message, TerminalColor color) {
assert(message != null); if (!supportsColor || message.isEmpty) {
if (!supportsColor || color == null || message.isEmpty) {
return message; return message;
} }
final StringBuffer buffer = StringBuffer(); final StringBuffer buffer = StringBuffer();

View File

@ -207,7 +207,7 @@ String wrapText(String text, {
int? indent, int? indent,
}) { }) {
assert(columnWidth >= 0); assert(columnWidth >= 0);
if (text == null || text.isEmpty) { if (text.isEmpty) {
return ''; return '';
} }
indent ??= 0; indent ??= 0;
@ -295,7 +295,7 @@ List<String> _wrapTextAsLines(String text, {
required int columnWidth, required int columnWidth,
required bool shouldWrap, required bool shouldWrap,
}) { }) {
if (text == null || text.isEmpty) { if (text.isEmpty) {
return <String>['']; return <String>[''];
} }
assert(start >= 0); assert(start >= 0);

View File

@ -6,7 +6,6 @@ import 'package:package_config/package_config_types.dart';
import 'artifacts.dart'; import 'artifacts.dart';
import 'base/config.dart'; import 'base/config.dart';
import 'base/context.dart';
import 'base/file_system.dart'; import 'base/file_system.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'base/os.dart'; import 'base/os.dart';
@ -237,18 +236,15 @@ class BuildInfo {
kBuildMode: getNameForBuildMode(mode), kBuildMode: getNameForBuildMode(mode),
if (dartDefines.isNotEmpty) if (dartDefines.isNotEmpty)
kDartDefines: encodeDartDefines(dartDefines), kDartDefines: encodeDartDefines(dartDefines),
if (dartObfuscation != null) kDartObfuscation: dartObfuscation.toString(),
kDartObfuscation: dartObfuscation.toString(),
if (extraFrontEndOptions.isNotEmpty) if (extraFrontEndOptions.isNotEmpty)
kExtraFrontEndOptions: extraFrontEndOptions.join(','), kExtraFrontEndOptions: extraFrontEndOptions.join(','),
if (extraGenSnapshotOptions.isNotEmpty) if (extraGenSnapshotOptions.isNotEmpty)
kExtraGenSnapshotOptions: extraGenSnapshotOptions.join(','), kExtraGenSnapshotOptions: extraGenSnapshotOptions.join(','),
if (splitDebugInfoPath != null) if (splitDebugInfoPath != null)
kSplitDebugInfo: splitDebugInfoPath!, kSplitDebugInfo: splitDebugInfoPath!,
if (trackWidgetCreation != null) kTrackWidgetCreation: trackWidgetCreation.toString(),
kTrackWidgetCreation: trackWidgetCreation.toString(), kIconTreeShakerFlag: treeShakeIcons.toString(),
if (treeShakeIcons != null)
kIconTreeShakerFlag: treeShakeIcons.toString(),
if (bundleSkSLPath != null) if (bundleSkSLPath != null)
kBundleSkSLPath: bundleSkSLPath!, kBundleSkSLPath: bundleSkSLPath!,
if (codeSizeDirectory != null) if (codeSizeDirectory != null)
@ -277,24 +273,20 @@ class BuildInfo {
final Map<String, String> environmentMap = <String, String>{ final Map<String, String> environmentMap = <String, String>{
if (dartDefines.isNotEmpty) if (dartDefines.isNotEmpty)
'DART_DEFINES': encodeDartDefines(dartDefines), 'DART_DEFINES': encodeDartDefines(dartDefines),
if (dartObfuscation != null) 'DART_OBFUSCATION': dartObfuscation.toString(),
'DART_OBFUSCATION': dartObfuscation.toString(),
if (extraFrontEndOptions.isNotEmpty) if (extraFrontEndOptions.isNotEmpty)
'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions.join(','), 'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions.join(','),
if (extraGenSnapshotOptions.isNotEmpty) if (extraGenSnapshotOptions.isNotEmpty)
'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions.join(','), 'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions.join(','),
if (splitDebugInfoPath != null) if (splitDebugInfoPath != null)
'SPLIT_DEBUG_INFO': splitDebugInfoPath!, 'SPLIT_DEBUG_INFO': splitDebugInfoPath!,
if (trackWidgetCreation != null) 'TRACK_WIDGET_CREATION': trackWidgetCreation.toString(),
'TRACK_WIDGET_CREATION': trackWidgetCreation.toString(), 'TREE_SHAKE_ICONS': treeShakeIcons.toString(),
if (treeShakeIcons != null)
'TREE_SHAKE_ICONS': treeShakeIcons.toString(),
if (performanceMeasurementFile != null) if (performanceMeasurementFile != null)
'PERFORMANCE_MEASUREMENT_FILE': performanceMeasurementFile!, 'PERFORMANCE_MEASUREMENT_FILE': performanceMeasurementFile!,
if (bundleSkSLPath != null) if (bundleSkSLPath != null)
'BUNDLE_SKSL_PATH': bundleSkSLPath!, 'BUNDLE_SKSL_PATH': bundleSkSLPath!,
if (packagesPath != null) 'PACKAGE_CONFIG': packagesPath,
'PACKAGE_CONFIG': packagesPath,
if (codeSizeDirectory != null) if (codeSizeDirectory != null)
'CODE_SIZE_DIRECTORY': codeSizeDirectory!, 'CODE_SIZE_DIRECTORY': codeSizeDirectory!,
}; };
@ -317,18 +309,15 @@ class BuildInfo {
final List<String> result = <String>[ final List<String> result = <String>[
if (dartDefines.isNotEmpty) if (dartDefines.isNotEmpty)
'-Pdart-defines=${encodeDartDefines(dartDefines)}', '-Pdart-defines=${encodeDartDefines(dartDefines)}',
if (dartObfuscation != null) '-Pdart-obfuscation=$dartObfuscation',
'-Pdart-obfuscation=$dartObfuscation',
if (extraFrontEndOptions.isNotEmpty) if (extraFrontEndOptions.isNotEmpty)
'-Pextra-front-end-options=${extraFrontEndOptions.join(',')}', '-Pextra-front-end-options=${extraFrontEndOptions.join(',')}',
if (extraGenSnapshotOptions.isNotEmpty) if (extraGenSnapshotOptions.isNotEmpty)
'-Pextra-gen-snapshot-options=${extraGenSnapshotOptions.join(',')}', '-Pextra-gen-snapshot-options=${extraGenSnapshotOptions.join(',')}',
if (splitDebugInfoPath != null) if (splitDebugInfoPath != null)
'-Psplit-debug-info=$splitDebugInfoPath', '-Psplit-debug-info=$splitDebugInfoPath',
if (trackWidgetCreation != null) '-Ptrack-widget-creation=$trackWidgetCreation',
'-Ptrack-widget-creation=$trackWidgetCreation', '-Ptree-shake-icons=$treeShakeIcons',
if (treeShakeIcons != null)
'-Ptree-shake-icons=$treeShakeIcons',
if (performanceMeasurementFile != null) if (performanceMeasurementFile != null)
'-Pperformance-measurement-file=$performanceMeasurementFile', '-Pperformance-measurement-file=$performanceMeasurementFile',
if (bundleSkSLPath != null) if (bundleSkSLPath != null)
@ -870,14 +859,8 @@ FileSystemEntity getWebPlatformBinariesDirectory(Artifacts artifacts, WebRendere
String getBuildDirectory([Config? config, FileSystem? fileSystem]) { String getBuildDirectory([Config? config, FileSystem? fileSystem]) {
// TODO(johnmccutchan): Stop calling this function as part of setting // TODO(johnmccutchan): Stop calling this function as part of setting
// up command line argument processing. // up command line argument processing.
if (context == null) {
return 'build';
}
final Config localConfig = config ?? globals.config; final Config localConfig = config ?? globals.config;
final FileSystem localFilesystem = fileSystem ?? globals.fs; final FileSystem localFilesystem = fileSystem ?? globals.fs;
if (localConfig == null) {
return 'build';
}
final String buildDir = localConfig.getValue('build-dir') as String? ?? 'build'; final String buildDir = localConfig.getValue('build-dir') as String? ?? 'build';
if (localFilesystem.path.isAbsolute(buildDir)) { if (localFilesystem.path.isAbsolute(buildDir)) {

View File

@ -985,7 +985,7 @@ class Node {
} }
final String content = stamp.readAsStringSync(); final String content = stamp.readAsStringSync();
// Something went wrong writing the stamp file. // Something went wrong writing the stamp file.
if (content == null || content.isEmpty) { if (content.isEmpty) {
stamp.deleteSync(); stamp.deleteSync();
// Malformed stamp file, not safe to skip. // Malformed stamp file, not safe to skip.
_dirty = true; _dirty = true;

View File

@ -42,12 +42,7 @@ class IconTreeShaker {
required Logger logger, required Logger logger,
required FileSystem fileSystem, required FileSystem fileSystem,
required Artifacts artifacts, required Artifacts artifacts,
}) : assert(_environment != null), }) : _processManager = processManager,
assert(processManager != null),
assert(logger != null),
assert(fileSystem != null),
assert(artifacts != null),
_processManager = processManager,
_logger = logger, _logger = logger,
_fs = fileSystem, _fs = fileSystem,
_artifacts = artifacts, _artifacts = artifacts,
@ -366,9 +361,7 @@ class _IconTreeShakerData {
required this.family, required this.family,
required this.relativePath, required this.relativePath,
required this.codePoints, required this.codePoints,
}) : assert(family != null), });
assert(relativePath != null),
assert(codePoints != null);
/// The font family name, e.g. "MaterialIcons". /// The font family name, e.g. "MaterialIcons".
final String family; final String family;

View File

@ -85,18 +85,16 @@ class BundleBuilder {
} }
throwToolExit('Failed to build bundle.'); throwToolExit('Failed to build bundle.');
} }
if (depfilePath != null) { final Depfile depfile = Depfile(result.inputFiles, result.outputFiles);
final Depfile depfile = Depfile(result.inputFiles, result.outputFiles); final File outputDepfile = globals.fs.file(depfilePath);
final File outputDepfile = globals.fs.file(depfilePath); if (!outputDepfile.parent.existsSync()) {
if (!outputDepfile.parent.existsSync()) { outputDepfile.parent.createSync(recursive: true);
outputDepfile.parent.createSync(recursive: true);
}
final DepfileService depfileService = DepfileService(
fileSystem: globals.fs,
logger: globals.logger,
);
depfileService.writeToFile(depfile, outputDepfile);
} }
final DepfileService depfileService = DepfileService(
fileSystem: globals.fs,
logger: globals.logger,
);
depfileService.writeToFile(depfile, outputDepfile);
// Work around for flutter_tester placing kernel artifacts in odd places. // Work around for flutter_tester placing kernel artifacts in odd places.
if (applicationKernelFilePath != null) { if (applicationKernelFilePath != null) {

View File

@ -575,7 +575,7 @@ class Cache {
final List<String> paths = <String>[]; final List<String> paths = <String>[];
for (final ArtifactSet artifact in _artifacts) { for (final ArtifactSet artifact in _artifacts) {
final Map<String, String> env = artifact.environment; final Map<String, String> env = artifact.environment;
if (env == null || !env.containsKey('DYLD_LIBRARY_PATH')) { if (!env.containsKey('DYLD_LIBRARY_PATH')) {
continue; continue;
} }
final String path = env['DYLD_LIBRARY_PATH']!; final String path = env['DYLD_LIBRARY_PATH']!;
@ -721,7 +721,7 @@ class Cache {
/// Representation of a set of artifacts used by the tool. /// Representation of a set of artifacts used by the tool.
abstract class ArtifactSet { abstract class ArtifactSet {
ArtifactSet(this.developmentArtifact) : assert(developmentArtifact != null); ArtifactSet(this.developmentArtifact);
/// The development artifact. /// The development artifact.
final DevelopmentArtifact developmentArtifact; final DevelopmentArtifact developmentArtifact;

View File

@ -113,9 +113,7 @@ class AnalyzeContinuously extends AnalyzeBase {
for (final AnalysisError error in sortedErrors) { for (final AnalysisError error in sortedErrors) {
logger.printStatus(error.toString()); logger.printStatus(error.toString());
if (error.code != null) { logger.printTrace('error code: ${error.code}');
logger.printTrace('error code: ${error.code}');
}
} }
dumpErrors(sortedErrors.map<String>((AnalysisError error) => error.toLegacyString())); dumpErrors(sortedErrors.map<String>((AnalysisError error) => error.toLegacyString()));

View File

@ -138,9 +138,6 @@ class AssembleCommand extends FlutterCommand {
@override @override
Future<CustomDimensions> get usageValues async { Future<CustomDimensions> get usageValues async {
final FlutterProject flutterProject = FlutterProject.current(); final FlutterProject flutterProject = FlutterProject.current();
if (flutterProject == null) {
return const CustomDimensions();
}
try { try {
return CustomDimensions( return CustomDimensions(
commandBuildBundleTargetPlatform: environment.defines[kTargetPlatform], commandBuildBundleTargetPlatform: environment.defines[kTargetPlatform],

View File

@ -287,7 +287,7 @@ known, it can be explicitly provided to attach via the command-line, e.g.
if ((debugPort == null && debugUri == null) || isNetworkDevice) { if ((debugPort == null && debugUri == null) || isNetworkDevice) {
if (device is FuchsiaDevice) { if (device is FuchsiaDevice) {
final String module = stringArgDeprecated('module')!; final String? module = stringArgDeprecated('module');
if (module == null) { if (module == null) {
throwToolExit("'--module' is required for attaching to a Fuchsia device"); throwToolExit("'--module' is required for attaching to a Fuchsia device");
} }
@ -439,7 +439,6 @@ known, it can be explicitly provided to attach via the command-line, e.g.
throwToolExit(error.toString()); throwToolExit(error.toString());
} }
result = await app.runner!.waitForAppToFinish(); result = await app.runner!.waitForAppToFinish();
assert(result != null);
return; return;
} }
while (true) { while (true) {
@ -498,10 +497,6 @@ known, it can be explicitly provided to attach via the command-line, e.g.
required FlutterProject flutterProject, required FlutterProject flutterProject,
required bool usesIpv6, required bool usesIpv6,
}) async { }) async {
assert(observatoryUris != null);
assert(device != null);
assert(flutterProject != null);
assert(usesIpv6 != null);
final BuildInfo buildInfo = await getBuildInfo(); final BuildInfo buildInfo = await getBuildInfo();
final FlutterDevice flutterDevice = await FlutterDevice.create( final FlutterDevice flutterDevice = await FlutterDevice.create(

View File

@ -79,9 +79,6 @@ class BuildAarCommand extends BuildSubCommand {
@override @override
Future<CustomDimensions> get usageValues async { Future<CustomDimensions> get usageValues async {
final FlutterProject flutterProject = _getProject(); final FlutterProject flutterProject = _getProject();
if (flutterProject == null) {
return const CustomDimensions();
}
String projectType; String projectType;
if (flutterProject.manifest.isModule) { if (flutterProject.manifest.isModule) {

View File

@ -77,9 +77,6 @@ class BuildBundleCommand extends BuildSubCommand {
Future<CustomDimensions> get usageValues async { Future<CustomDimensions> get usageValues async {
final String projectDir = globals.fs.file(targetFile).parent.parent.path; final String projectDir = globals.fs.file(targetFile).parent.parent.path;
final FlutterProject flutterProject = FlutterProject.fromDirectory(globals.fs.directory(projectDir)); final FlutterProject flutterProject = FlutterProject.fromDirectory(globals.fs.directory(projectDir));
if (flutterProject == null) {
return const CustomDimensions();
}
return CustomDimensions( return CustomDimensions(
commandBuildBundleTargetPlatform: stringArgDeprecated('target-platform'), commandBuildBundleTargetPlatform: stringArgDeprecated('target-platform'),
commandBuildBundleIsModule: flutterProject.isModule, commandBuildBundleIsModule: flutterProject.isModule,
@ -98,9 +95,6 @@ class BuildBundleCommand extends BuildSubCommand {
Future<FlutterCommandResult> runCommand() async { Future<FlutterCommandResult> runCommand() async {
final String targetPlatform = stringArgDeprecated('target-platform')!; final String targetPlatform = stringArgDeprecated('target-platform')!;
final TargetPlatform platform = getTargetPlatformForName(targetPlatform); final TargetPlatform platform = getTargetPlatformForName(targetPlatform);
if (platform == null) {
throwToolExit('Unknown platform: $targetPlatform');
}
// Check for target platforms that are only allowed via feature flags. // Check for target platforms that are only allowed via feature flags.
switch (platform) { switch (platform) {
case TargetPlatform.darwin: case TargetPlatform.darwin:

View File

@ -232,7 +232,7 @@ class CreateCommand extends CreateBase {
'The "--platforms" argument is not supported in $template template.', 'The "--platforms" argument is not supported in $template template.',
exitCode: 2 exitCode: 2
); );
} else if (platforms == null || platforms.isEmpty) { } else if (platforms.isEmpty) {
throwToolExit('Must specify at least one platform using --platforms', throwToolExit('Must specify at least one platform using --platforms',
exitCode: 2); exitCode: 2);
} else if (generateFfiPlugin && argResults!.wasParsed('platforms') && platforms.contains('web')) { } else if (generateFfiPlugin && argResults!.wasParsed('platforms') && platforms.contains('web')) {
@ -731,7 +731,7 @@ Your plugin code is in $relativePluginMain.
Your example app code is in $relativeExampleMain. Your example app code is in $relativeExampleMain.
'''); ''');
if (platformsString != null && platformsString.isNotEmpty) { if (platformsString.isNotEmpty) {
globals.printStatus(''' globals.printStatus('''
Host platform code is in the $platformsString directories under $pluginPath. Host platform code is in the $platformsString directories under $pluginPath.
To edit platform code in an IDE see https://flutter.dev/developing-packages/#edit-plugin-package. To edit platform code in an IDE see https://flutter.dev/developing-packages/#edit-plugin-package.

View File

@ -333,7 +333,6 @@ abstract class CreateBase extends FlutterCommand {
throwToolExit(error); throwToolExit(error);
} }
} }
assert(projectName != null);
return projectName; return projectName;
} }
@ -688,7 +687,7 @@ abstract class CreateBase extends FlutterCommand {
onFileCopied: (File sourceFile, File destinationFile) { onFileCopied: (File sourceFile, File destinationFile) {
filesCreated++; filesCreated++;
final String modes = sourceFile.statSync().modeString(); final String modes = sourceFile.statSync().modeString();
if (modes != null && modes.contains('x')) { if (modes.contains('x')) {
globals.os.makeExecutable(destinationFile); globals.os.makeExecutable(destinationFile);
} }
}, },

View File

@ -88,16 +88,7 @@ class CustomDevicesCommand extends FlutterCommand {
required Logger logger, required Logger logger,
required FeatureFlags featureFlags, required FeatureFlags featureFlags,
PrintFn usagePrintFn = print, PrintFn usagePrintFn = print,
}) : assert(customDevicesConfig != null), }) : _customDevicesConfig = customDevicesConfig,
assert(operatingSystemUtils != null),
assert(terminal != null),
assert(platform != null),
assert(processManager != null),
assert(fileSystem != null),
assert(logger != null),
assert(featureFlags != null),
assert(usagePrintFn != null),
_customDevicesConfig = customDevicesConfig,
_featureFlags = featureFlags, _featureFlags = featureFlags,
_usagePrintFn = usagePrintFn _usagePrintFn = usagePrintFn
{ {
@ -443,13 +434,13 @@ class CustomDevicesAddCommand extends CustomDevicesCommandBase {
// find a random port we can forward // find a random port we can forward
final int port = await _operatingSystemUtils.findFreePort(); final int port = await _operatingSystemUtils.findFreePort();
final ForwardedPort forwardedPort = await (portForwarder.tryForward(port, port) as FutureOr<ForwardedPort>); final ForwardedPort? forwardedPort = await portForwarder.tryForward(port, port);
if (forwardedPort == null) { if (forwardedPort == null) {
_printConfigCheckingError("Couldn't forward test port $port from device.",); _printConfigCheckingError("Couldn't forward test port $port from device.",);
result = false; result = false;
} else {
await portForwarder.unforward(forwardedPort);
} }
await portForwarder.unforward(forwardedPort);
} on Exception catch (e) { } on Exception catch (e) {
_printConfigCheckingError( _printConfigCheckingError(
'While forwarding/unforwarding device port: $e', 'While forwarding/unforwarding device port: $e',

View File

@ -210,7 +210,6 @@ class Daemon {
try { try {
final String method = request.data['method']! as String; final String method = request.data['method']! as String;
assert(method != null);
if (!method.contains('.')) { if (!method.contains('.')) {
throw DaemonException('method not understood: $method'); throw DaemonException('method not understood: $method');
} }
@ -1529,7 +1528,7 @@ class AppRunLogger extends DelegatingLogger {
'id': eventId, 'id': eventId,
'progressId': eventType, 'progressId': eventType,
if (message != null) 'message': message, if (message != null) 'message': message,
if (finished != null) 'finished': finished, 'finished': finished,
}; };
domain!._sendAppEvent(app, 'progress', event); domain!._sendAppEvent(app, 'progress', event);

View File

@ -240,7 +240,7 @@ class DriveCommand extends RunCommandBase {
@override @override
Future<FlutterCommandResult> runCommand() async { Future<FlutterCommandResult> runCommand() async {
final String testFile = _getTestFile()!; final String? testFile = _getTestFile();
if (testFile == null) { if (testFile == null) {
throwToolExit(null); throwToolExit(null);
} }

View File

@ -53,7 +53,7 @@ class EmulatorsCommand extends FlutterCommand {
await _createEmulator(name: stringArgDeprecated('name')); await _createEmulator(name: stringArgDeprecated('name'));
} else { } else {
final String? searchText = final String? searchText =
argumentResults.rest != null && argumentResults.rest.isNotEmpty argumentResults.rest.isNotEmpty
? argumentResults.rest.first ? argumentResults.rest.first
: null; : null;
await _listEmulators(searchText); await _listEmulators(searchText);

View File

@ -104,10 +104,6 @@ Future<bool> installApp(
String? userIdentifier, String? userIdentifier,
bool uninstall = true bool uninstall = true
}) async { }) async {
if (package == null) {
return false;
}
try { try {
if (uninstall && await device.isAppInstalled(package, userIdentifier: userIdentifier)) { if (uninstall && await device.isAppInstalled(package, userIdentifier: userIdentifier)) {
globals.printStatus('Uninstalling old version...'); globals.printStatus('Uninstalling old version...');

View File

@ -437,14 +437,14 @@ class RunCommand extends RunCommandBase {
final List<String> hostLanguage = <String>[]; final List<String> hostLanguage = <String>[];
if (anyAndroidDevices) { if (anyAndroidDevices) {
final AndroidProject androidProject = FlutterProject.current().android; final AndroidProject androidProject = FlutterProject.current().android;
if (androidProject != null && androidProject.existsSync()) { if (androidProject.existsSync()) {
hostLanguage.add(androidProject.isKotlin ? 'kotlin' : 'java'); hostLanguage.add(androidProject.isKotlin ? 'kotlin' : 'java');
androidEmbeddingVersion = androidProject.getEmbeddingVersion().toString().split('.').last; androidEmbeddingVersion = androidProject.getEmbeddingVersion().toString().split('.').last;
} }
} }
if (anyIOSDevices) { if (anyIOSDevices) {
final IosProject iosProject = FlutterProject.current().ios; final IosProject iosProject = FlutterProject.current().ios;
if (iosProject != null && iosProject.exists) { if (iosProject.exists) {
final Iterable<File> swiftFiles = iosProject.hostAppRoot final Iterable<File> swiftFiles = iosProject.hostAppRoot
.listSync(recursive: true, followLinks: false) .listSync(recursive: true, followLinks: false)
.whereType<File>() .whereType<File>()

View File

@ -64,7 +64,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
this.testWrapper = const TestWrapper(), this.testWrapper = const TestWrapper(),
this.testRunner = const FlutterTestRunner(), this.testRunner = const FlutterTestRunner(),
this.verbose = false, this.verbose = false,
}) : assert(testWrapper != null) { }) {
requiresPubspecYaml(); requiresPubspecYaml();
usesPubOption(); usesPubOption();
addNullSafetyModeOptions(hide: !verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp);

View File

@ -598,11 +598,11 @@ class UpdatePackagesCommand extends FlutterCommand {
} }
} }
for (_DependencyLink path in paths) { for (_DependencyLink? path in paths) {
final StringBuffer buf = StringBuffer(); final StringBuffer buf = StringBuffer();
while (path != null) { while (path != null) {
buf.write(path.to); buf.write(path.to);
path = path.from!; path = path.from;
if (path != null) { if (path != null) {
buf.write(' <- '); buf.write(' <- ');
} }
@ -878,7 +878,6 @@ class PubspecYaml {
/// that depend on the Flutter or Dart SDK directly and are thus automatically /// that depend on the Flutter or Dart SDK directly and are thus automatically
/// pinned). /// pinned).
void apply(PubDependencyTree versions, Set<String> specialDependencies) { void apply(PubDependencyTree versions, Set<String> specialDependencies) {
assert(versions != null);
final List<String> output = <String>[]; // the string data to output to the file, line by line final List<String> output = <String>[]; // the string data to output to the file, line by line
final Set<String> directDependencies = <String>{}; // packages this pubspec directly depends on (i.e. not transitive) final Set<String> directDependencies = <String>{}; // packages this pubspec directly depends on (i.e. not transitive)
final Set<String> devDependencies = <String>{}; final Set<String> devDependencies = <String>{};
@ -1311,7 +1310,6 @@ class PubspecDependency extends PubspecLine {
/// We return true if we parsed it and stored the line in lockLine. /// We return true if we parsed it and stored the line in lockLine.
/// We return false if we parsed it and it's a git dependency that needs the next few lines. /// We return false if we parsed it and it's a git dependency that needs the next few lines.
bool parseLock(String line, String pubspecPath, { required bool lockIsOverride }) { bool parseLock(String line, String pubspecPath, { required bool lockIsOverride }) {
assert(lockIsOverride != null);
assert(kind == DependencyKind.unknown); assert(kind == DependencyKind.unknown);
if (line.startsWith(_pathPrefix)) { if (line.startsWith(_pathPrefix)) {
// We're a path dependency; remember the (absolute) path. // We're a path dependency; remember the (absolute) path.
@ -1545,8 +1543,6 @@ class PubDependencyTree {
required Set<String> exclude, required Set<String> exclude,
List<String>? result, List<String>? result,
}) { }) {
assert(seen != null);
assert(exclude != null);
result ??= <String>[]; result ??= <String>[];
final Set<String>? dependencies = _dependencyTree[package]; final Set<String>? dependencies = _dependencyTree[package];
if (dependencies == null) { if (dependencies == null) {
@ -1580,9 +1576,6 @@ String _computeChecksum(Iterable<String> names, String Function(String name) get
final List<String> sortedNames = names.toList()..sort(); final List<String> sortedNames = names.toList()..sort();
for (final String name in sortedNames) { for (final String name in sortedNames) {
final String version = getVersion(name); final String version = getVersion(name);
if (version == null) {
continue;
}
final String value = '$name: $version'; final String value = '$name: $version';
// Each code unit is 16 bits. // Each code unit is 16 bits.
for (final int codeUnit in value.codeUnits) { for (final int codeUnit in value.codeUnits) {

View File

@ -590,8 +590,7 @@ class DefaultResidentCompiler implements ResidentCompiler {
List<String>? dartDefines, List<String>? dartDefines,
this.librariesSpec, this.librariesSpec,
@visibleForTesting StdoutHandler? stdoutHandler, @visibleForTesting StdoutHandler? stdoutHandler,
}) : assert(sdkRoot != null), }) : _logger = logger,
_logger = logger,
_processManager = processManager, _processManager = processManager,
_artifacts = artifacts, _artifacts = artifacts,
_stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem), _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem),
@ -654,7 +653,6 @@ class DefaultResidentCompiler implements ResidentCompiler {
String? projectRootPath, String? projectRootPath,
FileSystem? fs, FileSystem? fs,
}) async { }) async {
assert(outputPath != null);
if (!_controller.hasListener) { if (!_controller.hasListener) {
_controller.stream.listen(_handleCompilationRequest); _controller.stream.listen(_handleCompilationRequest);
} }
@ -777,11 +775,10 @@ class DefaultResidentCompiler implements ResidentCompiler {
], ],
...buildModeOptions(buildMode, dartDefines), ...buildModeOptions(buildMode, dartDefines),
if (trackWidgetCreation) '--track-widget-creation', if (trackWidgetCreation) '--track-widget-creation',
if (fileSystemRoots != null) for (final String root in fileSystemRoots) ...<String>[
for (final String root in fileSystemRoots) ...<String>[ '--filesystem-root',
'--filesystem-root', root,
root, ],
],
if (fileSystemScheme != null) ...<String>[ if (fileSystemScheme != null) ...<String>[
'--filesystem-scheme', '--filesystem-scheme',
fileSystemScheme!, fileSystemScheme!,

View File

@ -14,8 +14,6 @@ Future<void> generateLocalizationsSyntheticPackage({
required Environment environment, required Environment environment,
required BuildSystem buildSystem, required BuildSystem buildSystem,
}) async { }) async {
assert(environment != null);
assert(buildSystem != null);
final FileSystem fileSystem = environment.fileSystem; final FileSystem fileSystem = environment.fileSystem;
final File l10nYamlFile = fileSystem.file( final File l10nYamlFile = fileSystem.file(
@ -60,9 +58,6 @@ Future<void> generateLocalizationsSyntheticPackage({
environment, environment,
); );
if (result == null) {
throwToolExit('Generating synthetic localizations package failed: result is null.');
}
if (result.hasException) { if (result.hasException) {
throwToolExit( throwToolExit(
'Generating synthetic localizations package failed with ${result.exceptions.length} ${pluralize('error', result.exceptions.length)}:' 'Generating synthetic localizations package failed with ${result.exceptions.length} ${pluralize('error', result.exceptions.length)}:'

View File

@ -124,8 +124,7 @@ class DevFSFileContent extends DevFSContent {
if (oldFileStat == null && newFileStat == null) { if (oldFileStat == null && newFileStat == null) {
return false; return false;
} }
return time == null return oldFileStat == null
|| oldFileStat == null
|| newFileStat == null || newFileStat == null
|| newFileStat.modified.isAfter(time); || newFileStat.modified.isAfter(time);
} }
@ -173,7 +172,7 @@ class DevFSByteContent extends DevFSContent {
@override @override
bool isModifiedAfter(DateTime time) { bool isModifiedAfter(DateTime time) {
return time == null || _modificationTime.isAfter(time); return _modificationTime.isAfter(time);
} }
@override @override
@ -246,7 +245,7 @@ class DevFSStringCompressingBytesContent extends DevFSContent {
@override @override
bool isModifiedAfter(DateTime time) { bool isModifiedAfter(DateTime time) {
return time == null || _modificationTime.isAfter(time); return _modificationTime.isAfter(time);
} }
@override @override
@ -594,8 +593,6 @@ class DevFS {
String? projectRootPath, String? projectRootPath,
File? dartPluginRegistrant, File? dartPluginRegistrant,
}) async { }) async {
assert(trackWidgetCreation != null);
assert(generator != null);
final DateTime candidateCompileTime = DateTime.now(); final DateTime candidateCompileTime = DateTime.now();
didUpdateFontManifest = false; didUpdateFontManifest = false;
lastPackageConfig = packageConfig; lastPackageConfig = packageConfig;
@ -670,7 +667,7 @@ class DevFS {
} }
dirtyEntries[deviceUri] = content; dirtyEntries[deviceUri] = content;
syncedBytes += content.size; syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) { if (!bundleFirstUpload) {
shaderPathsToEvict.add(archivePath); shaderPathsToEvict.add(archivePath);
} }
}); });
@ -688,7 +685,7 @@ class DevFS {
} }
dirtyEntries[deviceUri] = content; dirtyEntries[deviceUri] = content;
syncedBytes += content.size; syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) { if (!bundleFirstUpload) {
scenePathsToEvict.add(archivePath); scenePathsToEvict.add(archivePath);
} }
}); });
@ -698,7 +695,7 @@ class DevFS {
case null: case null:
dirtyEntries[deviceUri] = content; dirtyEntries[deviceUri] = content;
syncedBytes += content.size; syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) { if (!bundleFirstUpload) {
assetPathsToEvict.add(archivePath); assetPathsToEvict.add(archivePath);
} }
} }

View File

@ -165,7 +165,6 @@ class ValidationResult {
final List<ValidationMessage> messages; final List<ValidationMessage> messages;
String get leadingBox { String get leadingBox {
assert(type != null);
switch (type) { switch (type) {
case ValidationType.crash: case ValidationType.crash:
return '[☠]'; return '[☠]';
@ -180,7 +179,6 @@ class ValidationResult {
} }
String get coloredLeadingBox { String get coloredLeadingBox {
assert(type != null);
switch (type) { switch (type) {
case ValidationType.crash: case ValidationType.crash:
return globals.terminal.color(leadingBox, TerminalColor.red); return globals.terminal.color(leadingBox, TerminalColor.red);
@ -196,7 +194,6 @@ class ValidationResult {
/// The string representation of the type. /// The string representation of the type.
String get typeStr { String get typeStr {
assert(type != null);
switch (type) { switch (type) {
case ValidationType.crash: case ValidationType.crash:
return 'crash'; return 'crash';

View File

@ -184,7 +184,7 @@ class FlutterDriverService extends DriverService {
userIdentifier: userIdentifier, userIdentifier: userIdentifier,
prebuiltApplication: prebuiltApplication, prebuiltApplication: prebuiltApplication,
); );
if (result != null && result.started) { if (result.started) {
break; break;
} }
// On attempts past 1, assume the application is built correctly and re-use it. // On attempts past 1, assume the application is built correctly and re-use it.

View File

@ -100,7 +100,7 @@ class PubDependencies extends ArtifactSet {
logger: _logger, logger: _logger,
throwOnError: false, throwOnError: false,
); );
if (packageConfig == null || packageConfig == PackageConfig.empty) { if (packageConfig == PackageConfig.empty) {
return false; return false;
} }
for (final Package package in packageConfig.packages) { for (final Package package in packageConfig.packages) {

View File

@ -32,7 +32,7 @@ class FlutterManifest {
required FileSystem fileSystem, required FileSystem fileSystem,
required Logger logger, required Logger logger,
}) { }) {
if (path == null || !fileSystem.isFileSync(path)) { if (!fileSystem.isFileSync(path)) {
return _createFromYaml(null, logger); return _createFromYaml(null, logger);
} }
final String manifest = fileSystem.file(path).readAsStringSync(); final String manifest = fileSystem.file(path).readAsStringSync();
@ -42,7 +42,7 @@ class FlutterManifest {
/// Returns null on missing or invalid manifest. /// Returns null on missing or invalid manifest.
@visibleForTesting @visibleForTesting
static FlutterManifest? createFromString(String manifest, { required Logger logger }) { static FlutterManifest? createFromString(String manifest, { required Logger logger }) {
return _createFromYaml(manifest != null ? loadYaml(manifest) : null, logger); return _createFromYaml(loadYaml(manifest), logger);
} }
static FlutterManifest? _createFromYaml(Object? yamlDocument, Logger logger) { static FlutterManifest? _createFromYaml(Object? yamlDocument, Logger logger) {
@ -237,7 +237,7 @@ class FlutterManifest {
assetsUri = const <Uri>[]; assetsUri = const <Uri>[];
} else { } else {
for (final Object? asset in assets) { for (final Object? asset in assets) {
if (asset is! String || asset == null || asset == '') { if (asset is! String || asset == '') {
_logger.printError('Deferred component asset manifest contains a null or empty uri.'); _logger.printError('Deferred component asset manifest contains a null or empty uri.');
continue; continue;
} }
@ -319,7 +319,7 @@ class FlutterManifest {
} }
final List<Uri> results = <Uri>[]; final List<Uri> results = <Uri>[];
for (final Object? asset in assets) { for (final Object? asset in assets) {
if (asset is! String || asset == null || asset == '') { if (asset is! String || asset == '') {
_logger.printError('Asset manifest contains a null or empty uri.'); _logger.printError('Asset manifest contains a null or empty uri.');
continue; continue;
} }
@ -387,7 +387,7 @@ class FlutterManifest {
} }
final List<Uri> results = <Uri>[]; final List<Uri> results = <Uri>[];
for (final Object? item in items) { for (final Object? item in items) {
if (item is! String || item == null || item == '') { if (item is! String || item == '') {
_logger.printError('$singularName manifest contains a null or empty uri.'); _logger.printError('$singularName manifest contains a null or empty uri.');
continue; continue;
} }
@ -422,9 +422,7 @@ class FlutterManifest {
class Font { class Font {
Font(this.familyName, this.fontAssets) Font(this.familyName, this.fontAssets)
: assert(familyName != null), : assert(fontAssets.isNotEmpty);
assert(fontAssets != null),
assert(fontAssets.isNotEmpty);
final String familyName; final String familyName;
final List<FontAsset> fontAssets; final List<FontAsset> fontAssets;
@ -441,8 +439,7 @@ class Font {
} }
class FontAsset { class FontAsset {
FontAsset(this.assetUri, {this.weight, this.style}) FontAsset(this.assetUri, {this.weight, this.style});
: assert(assetUri != null);
final Uri assetUri; final Uri assetUri;
final int? weight; final int? weight;
@ -510,7 +507,7 @@ bool _validate(Object? manifest, Logger logger) {
} }
void _validateFlutter(YamlMap? yaml, List<String> errors) { void _validateFlutter(YamlMap? yaml, List<String> errors) {
if (yaml == null || yaml.entries == null) { if (yaml == null) {
return; return;
} }
for (final MapEntry<Object?, Object?> kvp in yaml.entries) { for (final MapEntry<Object?, Object?> kvp in yaml.entries) {
@ -602,7 +599,7 @@ void _validateFlutter(YamlMap? yaml, List<String> errors) {
} }
break; break;
case 'plugin': case 'plugin':
if (yamlValue is! YamlMap || yamlValue == null) { if (yamlValue is! YamlMap) {
errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).'); errors.add('Expected "$yamlKey" to be an object, but got $yamlValue (${yamlValue.runtimeType}).');
break; break;
} }
@ -666,9 +663,6 @@ void _validateDeferredComponents(MapEntry<Object?, Object?> kvp, List<String> er
} }
void _validateFonts(YamlList fonts, List<String> errors) { void _validateFonts(YamlList fonts, List<String> errors) {
if (fonts == null) {
return;
}
const Set<int> fontWeights = <int>{ const Set<int> fontWeights = <int>{
100, 200, 300, 400, 500, 600, 700, 800, 900, 100, 200, 300, 400, 500, 600, 700, 800, 900,
}; };

View File

@ -361,7 +361,6 @@ List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String typ
/// Returns the version of the Android embedding that the current /// Returns the version of the Android embedding that the current
/// [project] is using. /// [project] is using.
AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) { AndroidEmbeddingVersion _getAndroidEmbeddingVersion(FlutterProject project) {
assert(project.android != null);
return project.android.getEmbeddingVersion(); return project.android.getEmbeddingVersion();
} }
@ -912,9 +911,8 @@ List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, P
if (platformPlugin == null) { if (platformPlugin == null) {
return false; return false;
} }
assert(variant == null || platformPlugin is VariantPlatformPlugin); assert(platformPlugin is VariantPlatformPlugin);
return variant == null || return (platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant);
(platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant);
}).toList(); }).toList();
} }

View File

@ -146,11 +146,6 @@ class FlutterProjectMetadata {
/// needs to be able to write the .migrate_config file into legacy apps. /// needs to be able to write the .migrate_config file into legacy apps.
void writeFile({File? outputFile}) { void writeFile({File? outputFile}) {
outputFile = outputFile ?? file; outputFile = outputFile ?? file;
if (outputFile == null) {
// In-memory FlutterProjectMetadata instances requires an output file to
// be passed or specified in the constructor.
throw const FileSystemException('No outputFile specified to write .metadata to. Initialize with a file or provide one when writing.');
}
outputFile outputFile
..createSync(recursive: true) ..createSync(recursive: true)
..writeAsStringSync(toString(), flush: true); ..writeAsStringSync(toString(), flush: true);

View File

@ -298,13 +298,11 @@ Future<XcodeBuildResult> buildXcodeProject({
if (activeArch != null) { if (activeArch != null) {
final String activeArchName = getNameForDarwinArch(activeArch); final String activeArchName = getNameForDarwinArch(activeArch);
if (activeArchName != null) { buildCommands.add('ONLY_ACTIVE_ARCH=YES');
buildCommands.add('ONLY_ACTIVE_ARCH=YES'); // Setting ARCHS to $activeArchName will break the build if a watchOS companion app exists,
// Setting ARCHS to $activeArchName will break the build if a watchOS companion app exists, // as it cannot be build for the architecture of the Flutter app.
// as it cannot be build for the architecture of the Flutter app. if (!hasWatchCompanion) {
if (!hasWatchCompanion) { buildCommands.add('ARCHS=$activeArchName');
buildCommands.add('ARCHS=$activeArchName');
}
} }
} }
@ -550,7 +548,6 @@ Future<RunResult?> _runBuildWithRetries(List<String> buildCommands, BuildableIOS
bool _isXcodeConcurrentBuildFailure(RunResult result) { bool _isXcodeConcurrentBuildFailure(RunResult result) {
return result.exitCode != 0 && return result.exitCode != 0 &&
result.stdout != null &&
result.stdout.contains('database is locked') && result.stdout.contains('database is locked') &&
result.stdout.contains('there are two concurrent builds running'); result.stdout.contains('there are two concurrent builds running');
} }

View File

@ -66,7 +66,6 @@ class PlistParser {
/// ///
/// The [plistFilePath] argument must not be null. /// The [plistFilePath] argument must not be null.
Map<String, Object> parseFile(String plistFilePath) { Map<String, Object> parseFile(String plistFilePath) {
assert(plistFilePath != null);
if (!_fileSystem.isFileSync(plistFilePath)) { if (!_fileSystem.isFileSync(plistFilePath)) {
return const <String, Object>{}; return const <String, Object>{};
} }

View File

@ -865,9 +865,6 @@ class _IOSSimulatorLogReader extends DeviceLogReader {
} }
final String filteredLine = _filterSystemLog(line); final String filteredLine = _filterSystemLog(line);
if (filteredLine == null) {
return;
}
_linesController.add(filteredLine); _linesController.add(filteredLine);
} }

View File

@ -105,7 +105,7 @@ class WebExpressionCompiler implements ExpressionCompiler {
await _generator.compileExpressionToJs(libraryUri, line, column, await _generator.compileExpressionToJs(libraryUri, line, column,
jsModules, jsFrameValues, moduleName, expression); jsModules, jsFrameValues, moduleName, expression);
if (compilerOutput != null && compilerOutput.outputFilename != null) { if (compilerOutput != null) {
final String content = utf8.decode( final String content = utf8.decode(
_fileSystem.file(compilerOutput.outputFilename).readAsBytesSync()); _fileSystem.file(compilerOutput.outputFilename).readAsBytesSync());
return ExpressionCompilationResult( return ExpressionCompilationResult(
@ -827,8 +827,6 @@ class WebDevFS implements DevFS {
String? projectRootPath, String? projectRootPath,
File? dartPluginRegistrant, File? dartPluginRegistrant,
}) async { }) async {
assert(trackWidgetCreation != null);
assert(generator != null);
lastPackageConfig = packageConfig; lastPackageConfig = packageConfig;
final File mainFile = globals.fs.file(mainUri); final File mainFile = globals.fs.file(mainUri);
final String outputDirectoryPath = mainFile.parent.path; final String outputDirectoryPath = mainFile.parent.path;
@ -1031,8 +1029,7 @@ class ReleaseAssetServer {
} else { } else {
for (final Uri uri in _searchPaths()) { for (final Uri uri in _searchPaths()) {
final Uri potential = uri.resolve(requestPath); final Uri potential = uri.resolve(requestPath);
if (potential == null || if (!_fileSystem.isFileSync(
!_fileSystem.isFileSync(
potential.toFilePath(windows: _platform.isWindows))) { potential.toFilePath(windows: _platform.isWindows))) {
continue; continue;
} }

View File

@ -47,7 +47,7 @@ class LicenseCollector {
for (final Package package in packageConfig.packages) { for (final Package package in packageConfig.packages) {
final Uri packageUri = package.packageUriRoot; final Uri packageUri = package.packageUriRoot;
if (packageUri == null || packageUri.scheme != 'file') { if (packageUri.scheme != 'file') {
continue; continue;
} }
// First check for NOTICES, then fallback to LICENSE // First check for NOTICES, then fallback to LICENSE

View File

@ -185,7 +185,7 @@ class L10nMissingPlaceholderException extends L10nParserException {
// } // }
// } // }
class OptionalParameter { class OptionalParameter {
const OptionalParameter(this.name, this.value) : assert(name != null), assert(value != null); const OptionalParameter(this.name, this.value);
final String name; final String name;
final Object value; final Object value;
@ -226,9 +226,7 @@ class OptionalParameter {
// //
class Placeholder { class Placeholder {
Placeholder(this.resourceId, this.name, Map<String, Object?> attributes) Placeholder(this.resourceId, this.name, Map<String, Object?> attributes)
: assert(resourceId != null), : example = _stringAttribute(resourceId, name, attributes, 'example'),
assert(name != null),
example = _stringAttribute(resourceId, name, attributes, 'example'),
type = _stringAttribute(resourceId, name, attributes, 'type'), type = _stringAttribute(resourceId, name, attributes, 'type'),
format = _stringAttribute(resourceId, name, attributes, 'format'), format = _stringAttribute(resourceId, name, attributes, 'format'),
optionalParameters = _optionalParameters(resourceId, name, attributes), optionalParameters = _optionalParameters(resourceId, name, attributes),
@ -338,9 +336,7 @@ class Message {
this.useEscaping = false, this.useEscaping = false,
this.logger, this.logger,
} }
) : assert(templateBundle != null), ) : assert(resourceId.isNotEmpty),
assert(allBundles != null),
assert(resourceId != null && resourceId.isNotEmpty),
value = _value(templateBundle.resources, resourceId), value = _value(templateBundle.resources, resourceId),
description = _description(templateBundle.resources, resourceId, isResourceAttributeRequired), description = _description(templateBundle.resources, resourceId, isResourceAttributeRequired),
placeholders = _placeholders(templateBundle.resources, resourceId, isResourceAttributeRequired), placeholders = _placeholders(templateBundle.resources, resourceId, isResourceAttributeRequired),
@ -529,7 +525,6 @@ class Message {
// Represents the contents of one ARB file. // Represents the contents of one ARB file.
class AppResourceBundle { class AppResourceBundle {
factory AppResourceBundle(File file) { factory AppResourceBundle(File file) {
assert(file != null);
// Assuming that the caller has verified that the file exists and is readable. // Assuming that the caller has verified that the file exists and is readable.
Map<String, Object?> resources; Map<String, Object?> resources;
try { try {
@ -548,7 +543,7 @@ class AppResourceBundle {
for (int index = 0; index < fileName.length; index += 1) { for (int index = 0; index < fileName.length; index += 1) {
// If an underscore was found, check if locale string follows. // If an underscore was found, check if locale string follows.
if (fileName[index] == '_' && fileName[index + 1] != null) { if (fileName[index] == '_') {
// If Locale.tryParse fails, it returns null. // If Locale.tryParse fails, it returns null.
final Locale? parserResult = Locale.tryParse(fileName.substring(index + 1)); final Locale? parserResult = Locale.tryParse(fileName.substring(index + 1));
// If the parserResult is not an actual locale identifier, end the loop. // If the parserResult is not an actual locale identifier, end the loop.
@ -613,7 +608,6 @@ class AppResourceBundle {
// Represents all of the ARB files in [directory] as [AppResourceBundle]s. // Represents all of the ARB files in [directory] as [AppResourceBundle]s.
class AppResourceBundleCollection { class AppResourceBundleCollection {
factory AppResourceBundleCollection(Directory directory) { factory AppResourceBundleCollection(Directory directory) {
assert(directory != null);
// Assuming that the caller has verified that the directory is readable. // Assuming that the caller has verified that the directory is readable.
final RegExp filenameRE = RegExp(r'(\w+)\.arb$'); final RegExp filenameRE = RegExp(r'(\w+)\.arb$');

View File

@ -51,7 +51,7 @@ class LocaleInfo implements Comparable<LocaleInfo> {
scriptCode = codes[1].length > codes[2].length ? codes[1] : codes[2]; scriptCode = codes[1].length > codes[2].length ? codes[1] : codes[2];
countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2]; countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2];
} }
assert(codes[0] != null && codes[0].isNotEmpty); assert(codes[0].isNotEmpty);
assert(countryCode == null || countryCode.isNotEmpty); assert(countryCode == null || countryCode.isNotEmpty);
assert(scriptCode == null || scriptCode.isNotEmpty); assert(scriptCode == null || scriptCode.isNotEmpty);
@ -340,7 +340,7 @@ class LocalizationOptions {
this.format = false, this.format = false,
this.useEscaping = false, this.useEscaping = false,
this.suppressWarnings = false, this.suppressWarnings = false,
}) : assert(useSyntheticPackage != null); });
/// The `--arb-dir` argument. /// The `--arb-dir` argument.
/// ///

View File

@ -113,9 +113,9 @@ class Xcode {
final RunResult result = _processUtils.runSync( final RunResult result = _processUtils.runSync(
<String>[...xcrunCommand(), 'clang'], <String>[...xcrunCommand(), 'clang'],
); );
if (result.stdout != null && result.stdout.contains('license')) { if (result.stdout.contains('license')) {
_eulaSigned = false; _eulaSigned = false;
} else if (result.stderr != null && result.stderr.contains('license')) { } else if (result.stderr.contains('license')) {
_eulaSigned = false; _eulaSigned = false;
} else { } else {
_eulaSigned = true; _eulaSigned = true;
@ -181,7 +181,6 @@ class Xcode {
} }
Future<String> sdkLocation(EnvironmentType environmentType) async { Future<String> sdkLocation(EnvironmentType environmentType) async {
assert(environmentType != null);
final RunResult runResult = await _processUtils.run( final RunResult runResult = await _processUtils.run(
<String>[...xcrunCommand(), '--sdk', getSDKNameForIOSEnvironmentType(environmentType), '--show-sdk-path'], <String>[...xcrunCommand(), '--sdk', getSDKNameForIOSEnvironmentType(environmentType), '--show-sdk-path'],
); );
@ -202,7 +201,6 @@ class Xcode {
} }
EnvironmentType? environmentTypeFromSdkroot(String sdkroot, FileSystem fileSystem) { EnvironmentType? environmentTypeFromSdkroot(String sdkroot, FileSystem fileSystem) {
assert(sdkroot != null);
// iPhoneSimulator.sdk or iPhoneOS.sdk // iPhoneSimulator.sdk or iPhoneOS.sdk
final String sdkName = fileSystem.path.basename(sdkroot).toLowerCase(); final String sdkName = fileSystem.path.basename(sdkroot).toLowerCase();
if (sdkName.contains('iphone')) { if (sdkName.contains('iphone')) {

View File

@ -279,7 +279,7 @@ class MDnsVmServiceDiscovery {
ResourceRecordQuery.text(domainName), ResourceRecordQuery.text(domainName),
) )
.toList(); .toList();
if (txt == null || txt.isEmpty) { if (txt.isEmpty) {
results.add(MDnsVmServiceDiscoveryResult(domainName, srvRecord.port, '')); results.add(MDnsVmServiceDiscoveryResult(domainName, srvRecord.port, ''));
if (quitOnFind) { if (quitOnFind) {
return results; return results;

View File

@ -110,9 +110,6 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
bool hasDart() => dartPluginClass != null; bool hasDart() => dartPluginClass != null;
static bool validate(YamlMap yaml) { static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return (yaml['package'] is String && yaml[kPluginClass] is String) || return (yaml['package'] is String && yaml[kPluginClass] is String) ||
yaml[kDartPluginClass] is String || yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true || yaml[kFfiPlugin] == true ||
@ -161,7 +158,6 @@ class AndroidPlugin extends PluginPlatform implements NativeOrDartPlugin {
late final Set<String> _supportedEmbeddings = _getSupportedEmbeddings(); late final Set<String> _supportedEmbeddings = _getSupportedEmbeddings();
Set<String> _getSupportedEmbeddings() { Set<String> _getSupportedEmbeddings() {
assert(pluginPath != null);
final Set<String> supportedEmbeddings = <String>{}; final Set<String> supportedEmbeddings = <String>{};
final String baseMainPath = _fileSystem.path.join( final String baseMainPath = _fileSystem.path.join(
pluginPath, pluginPath,
@ -262,9 +258,6 @@ class IOSPlugin extends PluginPlatform implements NativeOrDartPlugin, DarwinPlug
} }
static bool validate(YamlMap yaml) { static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return yaml[kPluginClass] is String || return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String || yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true || yaml[kFfiPlugin] == true ||
@ -346,9 +339,6 @@ class MacOSPlugin extends PluginPlatform implements NativeOrDartPlugin, DarwinPl
} }
static bool validate(YamlMap yaml) { static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return yaml[kPluginClass] is String || return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String || yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true || yaml[kFfiPlugin] == true ||
@ -443,10 +433,6 @@ class WindowsPlugin extends PluginPlatform
} }
static bool validate(YamlMap yaml) { static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return yaml[kPluginClass] is String || return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String || yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true || yaml[kFfiPlugin] == true ||
@ -518,9 +504,6 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
} }
static bool validate(YamlMap yaml) { static bool validate(YamlMap yaml) {
if (yaml == null) {
return false;
}
return yaml[kPluginClass] is String || return yaml[kPluginClass] is String ||
yaml[kDartPluginClass] is String || yaml[kDartPluginClass] is String ||
yaml[kFfiPlugin] == true || yaml[kFfiPlugin] == true ||

View File

@ -20,13 +20,7 @@ class Plugin {
required this.dependencies, required this.dependencies,
required this.isDirectDependency, required this.isDirectDependency,
this.implementsPackage, this.implementsPackage,
}) : assert(name != null), });
assert(path != null),
assert(platforms != null),
assert(defaultPackagePlatforms != null),
assert(pluginDartClassPlatforms != null),
assert(dependencies != null),
assert(isDirectDependency != null);
/// Parses [Plugin] specification from the provided pluginYaml. /// Parses [Plugin] specification from the provided pluginYaml.
/// ///
@ -193,9 +187,9 @@ class Plugin {
bool isDirectDependency, bool isDirectDependency,
) { ) {
final Map<String, PluginPlatform> platforms = <String, PluginPlatform>{}; final Map<String, PluginPlatform> platforms = <String, PluginPlatform>{};
final String pluginClass = (pluginYaml as Map<dynamic, dynamic>)['pluginClass'] as String; final String? pluginClass = (pluginYaml as Map<dynamic, dynamic>)['pluginClass'] as String?;
if (pluginYaml != null && pluginClass != null) { if (pluginClass != null) {
final String androidPackage = pluginYaml['androidPackage'] as String; final String? androidPackage = pluginYaml['androidPackage'] as String?;
if (androidPackage != null) { if (androidPackage != null) {
platforms[AndroidPlugin.kConfigKey] = AndroidPlugin( platforms[AndroidPlugin.kConfigKey] = AndroidPlugin(
name: name, name: name,
@ -410,8 +404,7 @@ class PluginInterfaceResolution {
PluginInterfaceResolution({ PluginInterfaceResolution({
required this.plugin, required this.plugin,
required this.platform, required this.platform,
}) : assert(plugin != null), });
assert(platform != null);
/// The plugin. /// The plugin.
final Plugin plugin; final Plugin plugin;

View File

@ -56,7 +56,6 @@ class FlutterProjectFactory {
/// Returns a [FlutterProject] view of the given directory or a ToolExit error, /// Returns a [FlutterProject] view of the given directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
FlutterProject fromDirectory(Directory directory) { FlutterProject fromDirectory(Directory directory) {
assert(directory != null);
return projects.putIfAbsent(directory.path, () { return projects.putIfAbsent(directory.path, () {
final FlutterManifest manifest = FlutterProject._readManifest( final FlutterManifest manifest = FlutterProject._readManifest(
directory.childFile(bundle.defaultManifestPath).path, directory.childFile(bundle.defaultManifestPath).path,
@ -86,10 +85,7 @@ class FlutterProjectFactory {
/// cached. /// cached.
class FlutterProject { class FlutterProject {
@visibleForTesting @visibleForTesting
FlutterProject(this.directory, this.manifest, this._exampleManifest) FlutterProject(this.directory, this.manifest, this._exampleManifest);
: assert(directory != null),
assert(manifest != null),
assert(_exampleManifest != null);
/// Returns a [FlutterProject] view of the given directory or a ToolExit error, /// Returns a [FlutterProject] view of the given directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
@ -176,7 +172,7 @@ class FlutterProject {
} }
String? _organizationNameFromPackageName(String packageName) { String? _organizationNameFromPackageName(String packageName) {
if (packageName != null && 0 <= packageName.lastIndexOf('.')) { if (0 <= packageName.lastIndexOf('.')) {
return packageName.substring(0, packageName.lastIndexOf('.')); return packageName.substring(0, packageName.lastIndexOf('.'));
} }
return null; return null;
@ -645,7 +641,7 @@ The detected reason was:
// the v1 embedding, we should check for this once removal is further along. // the v1 embedding, we should check for this once removal is further along.
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is plugin'); return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is plugin');
} }
if (appManifestFile == null || !appManifestFile.existsSync()) { if (!appManifestFile.existsSync()) {
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, 'No `${appManifestFile.absolute.path}` file'); return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, 'No `${appManifestFile.absolute.path}` file');
} }
XmlDocument document; XmlDocument document;

View File

@ -22,8 +22,7 @@ class ProtocolDiscovery {
this.devicePort, this.devicePort,
required this.ipv6, required this.ipv6,
required Logger logger, required Logger logger,
}) : _logger = logger, }) : _logger = logger {
assert(logReader != null) {
_deviceLogSubscription = logReader.logLines.listen( _deviceLogSubscription = logReader.logLines.listen(
_handleLine, _handleLine,
onDone: _stopScrapingLogs, onDone: _stopScrapingLogs,
@ -217,7 +216,6 @@ class _BufferedStreamController<T> {
StreamTransformer<S, S> _throttle<S>({ StreamTransformer<S, S> _throttle<S>({
required Duration waitDuration, required Duration waitDuration,
}) { }) {
assert(waitDuration != null);
S latestLine; S latestLine;
int? lastExecution; int? lastExecution;

View File

@ -191,9 +191,7 @@ class BuildEvent extends UsageEvent {
/// An event that reports the result of a top-level command. /// An event that reports the result of a top-level command.
class CommandResultEvent extends UsageEvent { class CommandResultEvent extends UsageEvent {
CommandResultEvent(super.commandPath, super.result) CommandResultEvent(super.commandPath, super.result)
: assert(commandPath != null), : super(flutterUsage: globals.flutterUsage);
assert(result != null),
super(flutterUsage: globals.flutterUsage);
@override @override
void send() { void send() {

View File

@ -125,7 +125,7 @@ ${_projectMetadataInformation()}
} }
try { try {
final FlutterManifest manifest = project.manifest; final FlutterManifest manifest = project.manifest;
if (project == null || manifest == null || manifest.isEmpty) { if (manifest.isEmpty) {
return 'No pubspec in working directory.'; return 'No pubspec in working directory.';
} }
final FlutterProjectMetadata metadata = FlutterProjectMetadata(project.metadataFile, _logger); final FlutterProjectMetadata metadata = FlutterProjectMetadata(project.metadataFile, _logger);

View File

@ -53,8 +53,7 @@ class FlutterDevice {
this.userIdentifier, this.userIdentifier,
required this.developmentShaderCompiler, required this.developmentShaderCompiler,
this.developmentSceneImporter, this.developmentSceneImporter,
}) : assert(buildInfo.trackWidgetCreation != null), }) : generator = generator ?? ResidentCompiler(
generator = generator ?? ResidentCompiler(
globals.artifacts!.getArtifactPath( globals.artifacts!.getArtifactPath(
Artifact.flutterPatchedSdkPath, Artifact.flutterPatchedSdkPath,
platform: targetPlatform, platform: targetPlatform,
@ -396,10 +395,6 @@ class FlutterDevice {
return; return;
} }
final Stream<String> logStream = (await device!.getLogReader(app: package)).logLines; final Stream<String> logStream = (await device!.getLogReader(app: package)).logLines;
if (logStream == null) {
globals.printError('Failed to read device log stream');
return;
}
_loggingSubscription = logStream.listen((String line) { _loggingSubscription = logStream.listen((String line) {
if (!line.contains(globals.kVMServiceMessageRegExp)) { if (!line.contains(globals.kVMServiceMessageRegExp)) {
globals.printStatus(line, wrap: false); globals.printStatus(line, wrap: false);
@ -514,23 +509,13 @@ class FlutterDevice {
final String modeName = coldRunner.debuggingOptions.buildInfo.friendlyModeName; final String modeName = coldRunner.debuggingOptions.buildInfo.friendlyModeName;
final bool prebuiltMode = coldRunner.applicationBinary != null; final bool prebuiltMode = coldRunner.applicationBinary != null;
if (coldRunner.mainPath == null) { globals.printStatus(
assert(prebuiltMode); 'Launching ${getDisplayPath(coldRunner.mainPath, globals.fs)} '
globals.printStatus( 'on ${device!.name} in $modeName mode...',
'Launching ${applicationPackage.displayName} ' );
'on ${device!.name} in $modeName mode...',
);
} else {
globals.printStatus(
'Launching ${getDisplayPath(coldRunner.mainPath, globals.fs)} '
'on ${device!.name} in $modeName mode...',
);
}
final Map<String, dynamic> platformArgs = <String, dynamic>{}; final Map<String, dynamic> platformArgs = <String, dynamic>{};
if (coldRunner.traceStartup != null) { platformArgs['trace-startup'] = coldRunner.traceStartup;
platformArgs['trace-startup'] = coldRunner.traceStartup;
}
platformArgs['multidex'] = coldRunner.multidexEnabled; platformArgs['multidex'] = coldRunner.multidexEnabled;
await startEchoingDeviceLog(); await startEchoingDeviceLog();
@ -1433,7 +1418,6 @@ abstract class ResidentRunner extends ResidentHandlers {
Future<int> waitForAppToFinish() async { Future<int> waitForAppToFinish() async {
final int exitCode = await _finished.future; final int exitCode = await _finished.future;
assert(exitCode != null);
await cleanupAtFinish(); await cleanupAtFinish();
return exitCode; return exitCode;
} }
@ -1911,9 +1895,6 @@ class DevToolsServerAddress {
final int port; final int port;
Uri? get uri { Uri? get uri {
if (host == null || port == null) {
return null;
}
return Uri(scheme: 'http', host: host, port: port); return Uri(scheme: 'http', host: host, port: port);
} }
} }

View File

@ -1380,7 +1380,6 @@ String _describePausedIsolates(int pausedIsolatesFound, String serviceEventKind)
message.write('$pausedIsolatesFound isolates are '); message.write('$pausedIsolatesFound isolates are ');
plural = true; plural = true;
} }
assert(serviceEventKind != null);
switch (serviceEventKind) { switch (serviceEventKind) {
case vm_service.EventKind.kPauseStart: case vm_service.EventKind.kPauseStart:
message.write('paused (probably due to --start-paused)'); message.write('paused (probably due to --start-paused)');
@ -1453,8 +1452,6 @@ class ProjectFileInvalidator {
required PackageConfig packageConfig, required PackageConfig packageConfig,
bool asyncScanning = false, bool asyncScanning = false,
}) async { }) async {
assert(urisToMonitor != null);
assert(packagesPath != null);
if (lastCompiled == null) { if (lastCompiled == null) {
// Initial load. // Initial load.
@ -1484,7 +1481,7 @@ class ProjectFileInvalidator {
: _fileSystem.stat(uri.toFilePath(windows: _platform.isWindows))) : _fileSystem.stat(uri.toFilePath(windows: _platform.isWindows)))
.then((FileStat stat) { .then((FileStat stat) {
final DateTime updatedAt = stat.modified; final DateTime updatedAt = stat.modified;
if (updatedAt != null && updatedAt.isAfter(lastCompiled)) { if (updatedAt.isAfter(lastCompiled)) {
invalidatedFiles.add(uri); invalidatedFiles.add(uri);
} }
}) })
@ -1498,7 +1495,7 @@ class ProjectFileInvalidator {
final DateTime updatedAt = uri.hasScheme && uri.scheme != 'file' final DateTime updatedAt = uri.hasScheme && uri.scheme != 'file'
? _fileSystem.file(uri).statSync().modified ? _fileSystem.file(uri).statSync().modified
: _fileSystem.statSync(uri.toFilePath(windows: _platform.isWindows)).modified; : _fileSystem.statSync(uri.toFilePath(windows: _platform.isWindows)).modified;
if (updatedAt != null && updatedAt.isAfter(lastCompiled)) { if (updatedAt.isAfter(lastCompiled)) {
invalidatedFiles.add(uri); invalidatedFiles.add(uri);
} }
} }
@ -1507,7 +1504,7 @@ class ProjectFileInvalidator {
final File packageFile = _fileSystem.file(packagesPath); final File packageFile = _fileSystem.file(packagesPath);
final Uri packageUri = packageFile.uri; final Uri packageUri = packageFile.uri;
final DateTime updatedAt = packageFile.statSync().modified; final DateTime updatedAt = packageFile.statSync().modified;
if (updatedAt != null && updatedAt.isAfter(lastCompiled)) { if (updatedAt.isAfter(lastCompiled)) {
invalidatedFiles.add(packageUri); invalidatedFiles.add(packageUri);
packageConfig = await _createPackageConfig(packagesPath); packageConfig = await _createPackageConfig(packagesPath);
// The frontend_server might be monitoring the package_config.json file, // The frontend_server might be monitoring the package_config.json file,

View File

@ -1344,17 +1344,12 @@ abstract class FlutterCommand extends Command<void> {
DateTime startTime, DateTime startTime,
DateTime endTime, DateTime endTime,
) { ) {
if (commandPath == null) {
return;
}
assert(commandResult != null);
// Send command result. // Send command result.
CommandResultEvent(commandPath, commandResult.toString()).send(); CommandResultEvent(commandPath, commandResult.toString()).send();
// Send timing. // Send timing.
final List<String?> labels = <String?>[ final List<String?> labels = <String?>[
if (commandResult.exitStatus != null) getEnumName(commandResult.exitStatus),
getEnumName(commandResult.exitStatus),
if (commandResult.timingLabelParts?.isNotEmpty ?? false) if (commandResult.timingLabelParts?.isNotEmpty ?? false)
...?commandResult.timingLabelParts, ...?commandResult.timingLabelParts,
]; ];
@ -1752,4 +1747,4 @@ DevelopmentArtifact? artifactFromTargetPlatform(TargetPlatform targetPlatform) {
} }
/// Returns true if s is either null, empty or is solely made of whitespace characters (as defined by String.trim). /// Returns true if s is either null, empty or is solely made of whitespace characters (as defined by String.trim).
bool _isBlank(String s) => s == null || s.trim().isEmpty; bool _isBlank(String s) => s.trim().isEmpty;

View File

@ -274,9 +274,7 @@ class FlutterCommandRunner extends CommandRunner<void> {
String status; String status;
if (machineFlag) { if (machineFlag) {
final Map<String, Object> jsonOut = globals.flutterVersion.toJson(); final Map<String, Object> jsonOut = globals.flutterVersion.toJson();
if (jsonOut != null) { jsonOut['flutterRoot'] = Cache.flutterRoot!;
jsonOut['flutterRoot'] = Cache.flutterRoot!;
}
status = const JsonEncoder.withIndent(' ').convert(jsonOut); status = const JsonEncoder.withIndent(' ').convert(jsonOut);
} else { } else {
status = globals.flutterVersion.toString(); status = globals.flutterVersion.toString();

View File

@ -142,7 +142,7 @@ class LocalEngineLocator {
.parent .parent
.parent .parent
.path; .path;
if (engineSourcePath != null && (engineSourcePath == _fileSystem.path.dirname(engineSourcePath) || engineSourcePath.isEmpty)) { if (engineSourcePath == _fileSystem.path.dirname(engineSourcePath) || engineSourcePath.isEmpty) {
engineSourcePath = null; engineSourcePath = null;
throwToolExit( throwToolExit(
_userMessages.runnerNoEngineSrcDir( _userMessages.runnerNoEngineSrcDir(

View File

@ -228,7 +228,7 @@ class Template {
.replaceAll(testTemplateExtension, '') .replaceAll(testTemplateExtension, '')
.replaceAll(templateExtension, ''); .replaceAll(templateExtension, '');
if (android != null && android && androidIdentifier != null) { if (android && androidIdentifier != null) {
finalDestinationPath = finalDestinationPath finalDestinationPath = finalDestinationPath
.replaceAll('androidIdentifier', androidIdentifier.replaceAll('.', pathSeparator)); .replaceAll('androidIdentifier', androidIdentifier.replaceAll('.', pathSeparator));
} }

View File

@ -104,9 +104,6 @@ class CoverageCollector extends TestWatcher {
_logMessage('collecting coverage data from $observatoryUri...'); _logMessage('collecting coverage data from $observatoryUri...');
final Map<String, dynamic> data = await collect( final Map<String, dynamic> data = await collect(
observatoryUri, libraryNames, branchCoverage: branchCoverage); observatoryUri, libraryNames, branchCoverage: branchCoverage);
if (data == null) {
throw Exception('Failed to collect coverage.');
}
_logMessage('($observatoryUri): collected coverage data; merging...'); _logMessage('($observatoryUri): collected coverage data; merging...');
_addHitmap(await coverage.HitMap.parseJson( _addHitmap(await coverage.HitMap.parseJson(
@ -146,9 +143,6 @@ class CoverageCollector extends TestWatcher {
observatoryUri!, libraryNames, serviceOverride: serviceOverride, observatoryUri!, libraryNames, serviceOverride: serviceOverride,
branchCoverage: branchCoverage) branchCoverage: branchCoverage)
.then<void>((Map<String, dynamic> result) { .then<void>((Map<String, dynamic> result) {
if (result == null) {
throw Exception('Failed to collect coverage.');
}
_logMessage('Collected coverage data.'); _logMessage('Collected coverage data.');
data = result; data = result;
}); });

View File

@ -68,7 +68,6 @@ FlutterPlatform installHook({
TestTimeRecorder? testTimeRecorder, TestTimeRecorder? testTimeRecorder,
UriConverter? uriConverter, UriConverter? uriConverter,
}) { }) {
assert(testWrapper != null);
assert(enableObservatory || (!debuggingOptions.startPaused && debuggingOptions.hostVmServicePort == null)); assert(enableObservatory || (!debuggingOptions.startPaused && debuggingOptions.hostVmServicePort == null));
// registerPlatformPlugin can be injected for testing since it's not very mock-friendly. // registerPlatformPlugin can be injected for testing since it's not very mock-friendly.
@ -134,9 +133,6 @@ String generateTestBootstrap({
bool flutterTestDep = true, bool flutterTestDep = true,
bool integrationTest = false, bool integrationTest = false,
}) { }) {
assert(testUrl != null);
assert(host != null);
assert(updateGoldens != null);
final String websocketUrl = host.type == InternetAddressType.IPv4 final String websocketUrl = host.type == InternetAddressType.IPv4
? 'ws://${host.address}' ? 'ws://${host.address}'
@ -294,7 +290,7 @@ class FlutterPlatform extends PlatformPlugin {
this.integrationTestUserIdentifier, this.integrationTestUserIdentifier,
this.testTimeRecorder, this.testTimeRecorder,
this.uriConverter, this.uriConverter,
}) : assert(shellPath != null); });
final String shellPath; final String shellPath;
final DebuggingOptions debuggingOptions; final DebuggingOptions debuggingOptions;

View File

@ -44,8 +44,7 @@ class FlutterTesterTestDevice extends TestDevice {
required this.compileExpression, required this.compileExpression,
required this.fontConfigManager, required this.fontConfigManager,
required this.uriConverter, required this.uriConverter,
}) : assert(shellPath != null), // Please provide the path to the shell in the SKY_SHELL environment variable. }) : assert(!debuggingOptions.startPaused || enableObservatory),
assert(!debuggingOptions.startPaused || enableObservatory),
_gotProcessObservatoryUri = enableObservatory _gotProcessObservatoryUri = enableObservatory
? Completer<Uri?>() : (Completer<Uri?>()..complete()); ? Completer<Uri?>() : (Completer<Uri?>()..complete());
@ -200,7 +199,6 @@ class FlutterTesterTestDevice extends TestDevice {
@override @override
Future<Uri?> get observatoryUri { Future<Uri?> get observatoryUri {
assert(_gotProcessObservatoryUri != null);
return _gotProcessObservatoryUri.future; return _gotProcessObservatoryUri.future;
} }
@ -303,15 +301,14 @@ class FlutterTesterTestDevice extends TestDevice {
if (match != null) { if (match != null) {
try { try {
final Uri uri = Uri.parse(match[1]!); final Uri uri = Uri.parse(match[1]!);
if (reportObservatoryUri != null) { await reportObservatoryUri(uri);
await reportObservatoryUri(uri);
}
} on Exception catch (error) { } on Exception catch (error) {
logger.printError('Could not parse shell observatory port message: $error'); logger.printError('Could not parse shell observatory port message: $error');
} }
} else if (line != null) { } else {
logger.printStatus('Shell: $line'); logger.printStatus('Shell: $line');
} }
}, },
onError: (dynamic error) { onError: (dynamic error) {
logger.printError('shell console stream for process pid ${process.pid} experienced an unexpected error: $error'); logger.printError('shell console stream for process pid ${process.pid} experienced an unexpected error: $error');

View File

@ -108,12 +108,7 @@ class TestGoldenComparator {
process.sendCommand(imageFile, goldenKey, updateGoldens); process.sendCommand(imageFile, goldenKey, updateGoldens);
final Map<String, dynamic> result = await process.getResponse(); final Map<String, dynamic> result = await process.getResponse();
return (result['success'] as bool) ? null : ((result['message'] as String?) ?? 'does not match');
if (result == null) {
return 'unknown error';
} else {
return (result['success'] as bool) ? null : ((result['message'] as String?) ?? 'does not match');
}
} }
} }

View File

@ -396,10 +396,6 @@ class FlutterWebPlatform extends PlatformPlugin {
return shelf.Response.ok('Caught exception: $ex'); return shelf.Response.ok('Caught exception: $ex');
} }
if (bytes == null) {
return shelf.Response.ok('Unknown error, bytes is null');
}
final String? errorMessage = await _testGoldenComparator.compareGoldens(testUri, bytes, goldenKey, updateGoldens); final String? errorMessage = await _testGoldenComparator.compareGoldens(testUri, bytes, goldenKey, updateGoldens);
return shelf.Response.ok(errorMessage ?? 'true'); return shelf.Response.ok(errorMessage ?? 'true');
} else { } else {

View File

@ -3,7 +3,6 @@
// found in the LICENSE file. // found in the LICENSE file.
import '../artifacts.dart'; import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/io.dart'; import '../base/io.dart';
import '../device.dart'; import '../device.dart';
@ -144,9 +143,6 @@ class _FlutterTestRunnerImpl implements FlutterTestRunner {
testFiles: testFiles, testFiles: testFiles,
buildInfo: debuggingOptions.buildInfo, buildInfo: debuggingOptions.buildInfo,
); );
if (result == null) {
throwToolExit('Failed to compile tests');
}
testArgs testArgs
..add('--platform=chrome') ..add('--platform=chrome')
..add('--') ..add('--')

View File

@ -1009,7 +1009,6 @@ class FlutterVmService {
/// Set the VM timeline flags. /// Set the VM timeline flags.
Future<void> setTimelineFlags(List<String> recordedStreams) async { Future<void> setTimelineFlags(List<String> recordedStreams) async {
assert(recordedStreams != null);
await _checkedCallServiceExtension( await _checkedCallServiceExtension(
'setVMTimelineFlags', 'setVMTimelineFlags',
args: <String, Object?>{ args: <String, Object?>{

View File

@ -73,9 +73,6 @@ String findChromeExecutable(Platform platform, FileSystem fileSystem) {
platform.environment['PROGRAMFILES(X86)']!, platform.environment['PROGRAMFILES(X86)']!,
]; ];
final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) { final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
if (prefix == null) {
return false;
}
final String path = fileSystem.path.join(prefix, kWindowsExecutable); final String path = fileSystem.path.join(prefix, kWindowsExecutable);
return fileSystem.file(path).existsSync(); return fileSystem.file(path).existsSync();
}, orElse: () => '.'); }, orElse: () => '.');
@ -102,9 +99,6 @@ String findEdgeExecutable(Platform platform, FileSystem fileSystem) {
platform.environment['PROGRAMFILES(X86)']!, platform.environment['PROGRAMFILES(X86)']!,
]; ];
final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) { final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
if (prefix == null) {
return false;
}
final String path = fileSystem.path.join(prefix, kWindowsEdgeExecutable); final String path = fileSystem.path.join(prefix, kWindowsEdgeExecutable);
return fileSystem.file(path).existsSync(); return fileSystem.file(path).existsSync();
}, orElse: () => '.'); }, orElse: () => '.');

View File

@ -67,10 +67,9 @@ Future<void> buildWeb(
kBaseHref : baseHref, kBaseHref : baseHref,
kSourceMapsEnabled: sourceMaps.toString(), kSourceMapsEnabled: sourceMaps.toString(),
kNativeNullAssertions: nativeNullAssertions.toString(), kNativeNullAssertions: nativeNullAssertions.toString(),
if (serviceWorkerStrategy != null)
kServiceWorkerStrategy: serviceWorkerStrategy, kServiceWorkerStrategy: serviceWorkerStrategy,
if (dart2jsOptimization != null) if (dart2jsOptimization != null)
kDart2jsOptimization: dart2jsOptimization, kDart2jsOptimization: dart2jsOptimization,
kDart2jsDumpInfo: dumpInfo.toString(), kDart2jsDumpInfo: dumpInfo.toString(),
kDart2jsNoFrequencyBasedMinification: noFrequencyBasedMinification.toString(), kDart2jsNoFrequencyBasedMinification: noFrequencyBasedMinification.toString(),
...buildInfo.toBuildSystemEnvironment(), ...buildInfo.toBuildSystemEnvironment(),

View File

@ -37,9 +37,6 @@ class WebMemoryFS {
final Map<String, dynamic> manifest = final Map<String, dynamic> manifest =
castStringKeyedMap(json.decode(manifestFile.readAsStringSync()))!; castStringKeyedMap(json.decode(manifestFile.readAsStringSync()))!;
for (final String filePath in manifest.keys) { for (final String filePath in manifest.keys) {
if (filePath == null) {
continue;
}
final Map<String, dynamic> offsets = final Map<String, dynamic> offsets =
castStringKeyedMap(manifest[filePath])!; castStringKeyedMap(manifest[filePath])!;
final List<int> codeOffsets = final List<int> codeOffsets =

View File

@ -153,7 +153,7 @@ abstract class ChromiumDevice extends Device {
); );
} }
_logger.sendEvent('app.webLaunchUrl', <String, Object>{'url': url, 'launched': launchChrome}); _logger.sendEvent('app.webLaunchUrl', <String, Object>{'url': url, 'launched': launchChrome});
return LaunchResult.succeeded(observatoryUri: url != null ? Uri.parse(url): null); return LaunchResult.succeeded(observatoryUri: Uri.parse(url));
} }
@override @override

View File

@ -329,7 +329,7 @@ class IosProject extends XcodeBasedProject {
xcodeProject.path, xcodeProject.path,
buildContext: buildContext, buildContext: buildContext,
); );
if (buildSettings != null && buildSettings.isNotEmpty) { if (buildSettings.isNotEmpty) {
// No timeouts, flakes, or errors. // No timeouts, flakes, or errors.
return buildSettings; return buildSettings;
} }

View File

@ -257,10 +257,7 @@ class FakeCommandRunner extends FlutterCommandRunner {
}) : _platform = platform, }) : _platform = platform,
_fileSystem = fileSystem, _fileSystem = fileSystem,
_logger = logger, _logger = logger,
_userMessages = userMessages ?? UserMessages(), _userMessages = userMessages ?? UserMessages();
assert(platform != null),
assert(fileSystem != null),
assert(logger != null);
final Platform _platform; final Platform _platform;
final FileSystem _fileSystem; final FileSystem _fileSystem;

View File

@ -86,9 +86,7 @@ void main() {
}); });
tearDown(() async { tearDown(() async {
if (daemon != null) { await daemon.shutdown();
return daemon.shutdown();
}
notifyingLogger.dispose(); notifyingLogger.dispose();
await daemonConnection.dispose(); await daemonConnection.dispose();
}); });

View File

@ -64,7 +64,6 @@ void main() {
String stderr = '', String stderr = '',
required CompleterIOSink stdinSink, required CompleterIOSink stdinSink,
}) { }) {
assert(stdinSink != null);
stdinSink.clear(); stdinSink.clear();
processManager.addCommand(FakeCommand( processManager.addCommand(FakeCommand(
command: fontSubsetArgs, command: fontSubsetArgs,

View File

@ -202,8 +202,7 @@ class TestFlutterDevice extends FlutterDevice {
required Device device, required Device device,
required this.exception, required this.exception,
required ResidentCompiler generator, required ResidentCompiler generator,
}) : assert(exception != null), }) : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
/// The exception to throw when the connect method is called. /// The exception to throw when the connect method is called.
final Exception exception; final Exception exception;

View File

@ -19,13 +19,11 @@ void main() {
}); });
testWithoutContext('Decode a normal string', () async { testWithoutContext('Decode a normal string', () async {
assert(passedString != null);
expect(decoder.convert(passedString.codeUnits), passedString); expect(decoder.convert(passedString.codeUnits), passedString);
}); });
testWithoutContext('Decode a malformed string', () async { testWithoutContext('Decode a malformed string', () async {
assert(nonpassString != null);
expect( expect(
() => decoder.convert(nonpassString.codeUnits), () => decoder.convert(nonpassString.codeUnits),

View File

@ -371,7 +371,7 @@ class FakeDesktopDevice extends DesktopDevice {
if (nullExecutablePathForDevice) { if (nullExecutablePathForDevice) {
return null; return null;
} }
return buildMode == null ? 'null' : getNameForBuildMode(buildMode); return getNameForBuildMode(buildMode);
} }
} }

View File

@ -448,7 +448,6 @@ FlutterDriverService setUpDriverService({
Device? device, Device? device,
required Logger logger, required Logger logger,
}) async { }) async {
assert(logger != null);
if (httpUri.scheme != 'http') { if (httpUri.scheme != 'http') {
fail('Expected an HTTP scheme, found $httpUri'); fail('Expected an HTTP scheme, found $httpUri');
} }

View File

@ -667,8 +667,7 @@ class TestFlutterDevice extends FlutterDevice {
required Device device, required Device device,
required this.exception, required this.exception,
required ResidentCompiler generator, required ResidentCompiler generator,
}) : assert(exception != null), }) : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
/// The exception to throw when the connect method is called. /// The exception to throw when the connect method is called.
final Exception exception; final Exception exception;

View File

@ -379,8 +379,6 @@ flutter:
required String name, required String name,
required List<String> dependencies, required List<String> dependencies,
}) { }) {
assert(name != null);
assert(dependencies != null);
final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.'); final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.');
pluginDirectory pluginDirectory
@ -412,8 +410,6 @@ dependencies:
required Map<String, _PluginPlatformInfo> platforms, required Map<String, _PluginPlatformInfo> platforms,
List<String> dependencies = const <String>[], List<String> dependencies = const <String>[],
}) { }) {
assert(name != null);
assert(dependencies != null);
final Iterable<String> platformSections = platforms.entries.map((MapEntry<String, _PluginPlatformInfo> entry) => ''' final Iterable<String> platformSections = platforms.entries.map((MapEntry<String, _PluginPlatformInfo> entry) => '''
${entry.key}: ${entry.key}:

View File

@ -389,10 +389,8 @@ analyzer:
} }
void assertContains(String text, List<String> patterns) { void assertContains(String text, List<String> patterns) {
if (patterns != null) { for (final String pattern in patterns) {
for (final String pattern in patterns) { expect(text, contains(pattern));
expect(text, contains(pattern));
}
} }
} }

Some files were not shown because too many files have changed in this diff Show More