Declare locals final where not reassigned (flutter_tools) (#8570)
diff --git a/packages/flutter_tools/lib/executable.dart b/packages/flutter_tools/lib/executable.dart
index 6e67c60..bfdcded 100644
--- a/packages/flutter_tools/lib/executable.dart
+++ b/packages/flutter_tools/lib/executable.dart
@@ -60,10 +60,10 @@
///
/// This function is intended to be used from the `flutter` command line tool.
Future<Null> main(List<String> args) async {
- bool verbose = args.contains('-v') || args.contains('--verbose');
- bool help = args.contains('-h') || args.contains('--help') ||
+ final bool verbose = args.contains('-v') || args.contains('--verbose');
+ final bool help = args.contains('-h') || args.contains('--help') ||
(args.isNotEmpty && args.first == 'help') || (args.length == 1 && verbose);
- bool verboseHelp = help && verbose;
+ final bool verboseHelp = help && verbose;
await run(args, <FlutterCommand>[
new AnalyzeCommand(verboseHelp: verboseHelp),
@@ -104,11 +104,11 @@
args.removeWhere((String option) => option == '-v' || option == '--verbose');
}
- FlutterCommandRunner runner = new FlutterCommandRunner(verboseHelp: verboseHelp);
+ final FlutterCommandRunner runner = new FlutterCommandRunner(verboseHelp: verboseHelp);
subCommands.forEach(runner.addCommand);
// Construct a context.
- AppContext _executableContext = new AppContext();
+ final AppContext _executableContext = new AppContext();
// Make the context current.
return await _executableContext.runInZone(() async {
@@ -140,7 +140,7 @@
// Initialize the system locale.
await intl.findSystemLocale();
- Completer<int> runCompleter = new Completer<int>();
+ final Completer<int> runCompleter = new Completer<int>();
Chain.capture<Future<Null>>(() async {
await runner.run(args);
await _exit(0);
@@ -206,7 +206,7 @@
flutterVersion: flutterVersion,
);
try {
- File file = await _createLocalCrashReport(args, error, chain);
+ final File file = await _createLocalCrashReport(args, error, chain);
stderr.writeln(
'Crash report written to ${file.path};\n'
'please let us know at https://github.com/flutter/flutter/issues.',
@@ -235,7 +235,7 @@
Future<File> _createLocalCrashReport(List<String> args, dynamic error, Chain chain) async {
File crashFile = getUniqueFile(crashFileSystem.currentDirectory, 'flutter', 'log');
- StringBuffer buffer = new StringBuffer();
+ final StringBuffer buffer = new StringBuffer();
buffer.writeln('Flutter crash report; please file at https://github.com/flutter/flutter/issues.\n');
@@ -267,8 +267,8 @@
Future<String> _doctorText() async {
try {
- BufferLogger logger = new BufferLogger();
- AppContext appContext = new AppContext();
+ final BufferLogger logger = new BufferLogger();
+ final AppContext appContext = new AppContext();
appContext.setVariable(Logger, logger);
@@ -287,7 +287,7 @@
// Send any last analytics calls that are in progress without overly delaying
// the tool's exit (we wait a maximum of 250ms).
if (flutterUsage.enabled) {
- Stopwatch stopwatch = new Stopwatch()..start();
+ final Stopwatch stopwatch = new Stopwatch()..start();
await flutterUsage.ensureAnalyticsSent();
printTrace('ensureAnalyticsSent: ${stopwatch.elapsedMilliseconds}ms');
}
@@ -295,7 +295,7 @@
// Run shutdown hooks before flushing logs
await runShutdownHooks();
- Completer<Null> completer = new Completer<Null>();
+ final Completer<Null> completer = new Completer<Null>();
// Give the task / timer queue one cycle through before we hard exit.
Timer.run(() {
diff --git a/packages/flutter_tools/lib/src/android/adb.dart b/packages/flutter_tools/lib/src/android/adb.dart
index 1c539a2..922c1a9 100644
--- a/packages/flutter_tools/lib/src/android/adb.dart
+++ b/packages/flutter_tools/lib/src/android/adb.dart
@@ -51,7 +51,7 @@
/// Ask the ADB server for its internal version number.
Future<String> getServerVersion() {
return _sendAdbServerCommand('host:version').then((String response) {
- _AdbServerResponse adbResponse = new _AdbServerResponse(response);
+ final _AdbServerResponse adbResponse = new _AdbServerResponse(response);
if (adbResponse.isOkay)
return adbResponse.message;
throw adbResponse.message;
@@ -60,11 +60,11 @@
/// Queries the adb server for the list of connected adb devices.
Future<List<AdbDevice>> listDevices() async {
- String stringResponse = await _sendAdbServerCommand('host:devices-l');
- _AdbServerResponse response = new _AdbServerResponse(stringResponse);
+ final String stringResponse = await _sendAdbServerCommand('host:devices-l');
+ final _AdbServerResponse response = new _AdbServerResponse(stringResponse);
if (response.isFail)
throw response.message;
- String message = response.message.trim();
+ final String message = response.message.trim();
if (message.isEmpty)
return <AdbDevice>[];
return message.split('\n').map(
@@ -73,16 +73,16 @@
}
Future<String> _sendAdbServerCommand(String command) async {
- Socket socket = await Socket.connect(InternetAddress.LOOPBACK_IP_V4, adbServerPort);
+ final Socket socket = await Socket.connect(InternetAddress.LOOPBACK_IP_V4, adbServerPort);
try {
printTrace('--> $command');
socket.add(_createAdbRequest(command));
- List<List<int>> result = await socket.toList();
- List<int> data = result.fold(<int>[], (List<int> previous, List<int> element) {
+ final List<List<int>> result = await socket.toList();
+ final List<int> data = result.fold(<int>[], (List<int> previous, List<int> element) {
return previous..addAll(element);
});
- String stringResult = new String.fromCharCodes(data);
+ final String stringResult = new String.fromCharCodes(data);
printTrace('<-- ${stringResult.trim()}');
return stringResult;
} finally {
@@ -97,7 +97,7 @@
// 'TA95000FQA device usb:340787200X product:peregrine_retus model:XT1045 device:peregrine'
// '015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper'
- Match match = kDeviceRegex.firstMatch(deviceInfo);
+ final Match match = kDeviceRegex.firstMatch(deviceInfo);
id = match[1];
status = match[2];
@@ -106,7 +106,7 @@
rest = rest.trim();
for (String data in rest.split(' ')) {
if (data.contains(':')) {
- List<String> fields = data.split(':');
+ final List<String> fields = data.split(':');
_info[fields[0]] = fields[1];
}
}
@@ -183,11 +183,11 @@
}
List<int> _createAdbRequest(String payload) {
- List<int> data = payload.codeUnits;
+ final List<int> data = payload.codeUnits;
// A 4-byte hexadecimal string giving the length of the payload.
- String prefix = data.length.toRadixString(16).padLeft(4, '0');
- List<int> result = <int>[];
+ final String prefix = data.length.toRadixString(16).padLeft(4, '0');
+ final List<int> result = <int>[];
result.addAll(prefix.codeUnits);
result.addAll(data);
return result;
diff --git a/packages/flutter_tools/lib/src/android/android_device.dart b/packages/flutter_tools/lib/src/android/android_device.dart
index 2c1fc8f..5982a4b 100644
--- a/packages/flutter_tools/lib/src/android/android_device.dart
+++ b/packages/flutter_tools/lib/src/android/android_device.dart
@@ -56,13 +56,13 @@
if (_properties == null) {
_properties = <String, String>{};
- List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
+ final List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
printTrace(propCommand.join(' '));
try {
// We pass an encoding of LATIN1 so that we don't try and interpret the
// `adb shell getprop` result as UTF8.
- ProcessResult result = processManager.runSync(
+ final ProcessResult result = processManager.runSync(
propCommand,
stdoutEncoding: LATIN1
);
@@ -82,7 +82,7 @@
@override
bool get isLocalEmulator {
if (_isLocalEmulator == null) {
- String characteristics = _getProperty('ro.build.characteristics');
+ final String characteristics = _getProperty('ro.build.characteristics');
_isLocalEmulator = characteristics != null && characteristics.contains('emulator');
}
return _isLocalEmulator;
@@ -124,11 +124,11 @@
bool _isValidAdbVersion(String adbVersion) {
// Sample output: 'Android Debug Bridge version 1.0.31'
- Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
+ final Match versionFields = new RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
if (versionFields != null) {
- int majorVersion = int.parse(versionFields[1]);
- int minorVersion = int.parse(versionFields[2]);
- int patchVersion = int.parse(versionFields[3]);
+ final int majorVersion = int.parse(versionFields[1]);
+ final int minorVersion = int.parse(versionFields[2]);
+ final int patchVersion = int.parse(versionFields[3]);
if (majorVersion > 1) {
return true;
}
@@ -150,7 +150,7 @@
return false;
try {
- String adbVersion = runCheckedSync(<String>[getAdbPath(androidSdk), 'version']);
+ final String adbVersion = runCheckedSync(<String>[getAdbPath(androidSdk), 'version']);
if (_isValidAdbVersion(adbVersion))
return true;
printError('The ADB at "${getAdbPath(androidSdk)}" is too old; please install version 1.0.32 or later.');
@@ -170,9 +170,9 @@
runCheckedSync(<String>[getAdbPath(androidSdk), 'start-server']);
// Sample output: '22'
- String sdkVersion = _getProperty('ro.build.version.sdk');
+ final String sdkVersion = _getProperty('ro.build.version.sdk');
- int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
+ final int sdkVersionParsed = int.parse(sdkVersion, onError: (String source) => null);
if (sdkVersionParsed == null) {
printError('Unexpected response from getprop: "$sdkVersion"');
return false;
@@ -201,8 +201,8 @@
}
String _getSourceSha1(ApplicationPackage app) {
- AndroidApk apk = app;
- File shaFile = fs.file('${apk.apkPath}.sha1');
+ final AndroidApk apk = app;
+ final File shaFile = fs.file('${apk.apkPath}.sha1');
return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
}
@@ -212,19 +212,19 @@
@override
bool isAppInstalled(ApplicationPackage app) {
// This call takes 400ms - 600ms.
- String listOut = runCheckedSync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
+ final String listOut = runCheckedSync(adbCommandForDevice(<String>['shell', 'pm', 'list', 'packages', app.id]));
return LineSplitter.split(listOut).contains("package:${app.id}");
}
@override
bool isLatestBuildInstalled(ApplicationPackage app) {
- String installedSha1 = _getDeviceApkSha1(app);
+ final String installedSha1 = _getDeviceApkSha1(app);
return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app);
}
@override
bool installApp(ApplicationPackage app) {
- AndroidApk apk = app;
+ final AndroidApk apk = app;
if (!fs.isFileSync(apk.apkPath)) {
printError('"${apk.apkPath}" does not exist.');
return false;
@@ -233,11 +233,11 @@
if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
return false;
- Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true);
- String installOut = runCheckedSync(adbCommandForDevice(<String>['install', '-r', apk.apkPath]));
+ final Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true);
+ final String installOut = runCheckedSync(adbCommandForDevice(<String>['install', '-r', apk.apkPath]));
status.stop();
- RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
- String failure = failureExp.stringMatch(installOut);
+ final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
+ final String failure = failureExp.stringMatch(installOut);
if (failure != null) {
printError('Package install error: $failure');
return false;
@@ -252,9 +252,9 @@
if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion())
return false;
- String uninstallOut = runCheckedSync(adbCommandForDevice(<String>['uninstall', app.id]));
- RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
- String failure = failureExp.stringMatch(uninstallOut);
+ final String uninstallOut = runCheckedSync(adbCommandForDevice(<String>['uninstall', app.id]));
+ final RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true);
+ final String failure = failureExp.stringMatch(uninstallOut);
if (failure != null) {
printError('Package uninstall error: $failure');
return false;
@@ -352,7 +352,7 @@
cmd.addAll(<String>['--ez', 'start-paused', 'true']);
}
cmd.add(apk.launchActivity);
- String result = runCheckedSync(cmd);
+ final String result = runCheckedSync(cmd);
// This invocation returns 0 even when it fails.
if (result.contains('Error: ')) {
printError(result.trim());
@@ -373,7 +373,7 @@
Uri observatoryUri, diagnosticUri;
if (debuggingOptions.buildMode == BuildMode.debug) {
- List<Uri> deviceUris = await Future.wait(
+ final List<Uri> deviceUris = await Future.wait(
<Future<Uri>>[observatoryDiscovery.nextUri(), diagnosticDiscovery.nextUri()]
);
observatoryUri = deviceUris[0];
@@ -400,7 +400,7 @@
@override
Future<bool> stopApp(ApplicationPackage app) {
- List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
+ final List<String> command = adbCommandForDevice(<String>['shell', 'am', 'force-stop', app.id]);
return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0);
}
@@ -429,11 +429,11 @@
/// Return the most recent timestamp in the Android log or `null` if there is
/// no available timestamp. The format can be passed to logcat's -T option.
String get lastLogcatTimestamp {
- String output = runCheckedSync(adbCommandForDevice(<String>[
+ final String output = runCheckedSync(adbCommandForDevice(<String>[
'logcat', '-v', 'time', '-t', '1'
]));
- Match timeMatch = _timeRegExp.firstMatch(output);
+ final Match timeMatch = _timeRegExp.firstMatch(output);
return timeMatch?.group(0);
}
@@ -454,12 +454,12 @@
@override
Future<List<DiscoveredApp>> discoverApps() {
- RegExp discoverExp = new RegExp(r'DISCOVER: (.*)');
- List<DiscoveredApp> result = <DiscoveredApp>[];
- StreamSubscription<String> logs = getLogReader().logLines.listen((String line) {
- Match match = discoverExp.firstMatch(line);
+ final RegExp discoverExp = new RegExp(r'DISCOVER: (.*)');
+ final List<DiscoveredApp> result = <DiscoveredApp>[];
+ final StreamSubscription<String> logs = getLogReader().logLines.listen((String line) {
+ final Match match = discoverExp.firstMatch(line);
if (match != null) {
- Map<String, dynamic> app = JSON.decode(match.group(1));
+ final Map<String, dynamic> app = JSON.decode(match.group(1));
result.add(new DiscoveredApp(app['id'], app['observatoryPort'], app['diagnosticPort']));
}
});
@@ -476,7 +476,7 @@
}
Map<String, String> parseAdbDeviceProperties(String str) {
- Map<String, String> properties = <String, String>{};
+ final Map<String, String> properties = <String, String>{};
final RegExp propertyExp = new RegExp(r'\[(.*?)\]: \[(.*?)\]');
for (Match match in propertyExp.allMatches(str))
properties[match.group(1)] = match.group(2);
@@ -490,11 +490,11 @@
///
/// [mockAdbOutput] is public for testing.
List<AndroidDevice> getAdbDevices({ String mockAdbOutput }) {
- List<AndroidDevice> devices = <AndroidDevice>[];
+ final List<AndroidDevice> devices = <AndroidDevice>[];
String text;
if (mockAdbOutput == null) {
- String adbPath = getAdbPath(androidSdk);
+ final String adbPath = getAdbPath(androidSdk);
if (adbPath == null)
return <AndroidDevice>[];
text = runSync(<String>[adbPath, 'devices', '-l']);
@@ -517,18 +517,18 @@
continue;
if (_kDeviceRegex.hasMatch(line)) {
- Match match = _kDeviceRegex.firstMatch(line);
+ final Match match = _kDeviceRegex.firstMatch(line);
- String deviceID = match[1];
- String deviceState = match[2];
+ final String deviceID = match[1];
+ final String deviceState = match[2];
String rest = match[3];
- Map<String, String> info = <String, String>{};
+ final Map<String, String> info = <String, String>{};
if (rest != null && rest.isNotEmpty) {
rest = rest.trim();
for (String data in rest.split(' ')) {
if (data.contains(':')) {
- List<String> fields = data.split(':');
+ final List<String> fields = data.split(':');
info[fields[0]] = fields[1];
}
}
@@ -595,8 +595,8 @@
void _start() {
// Start the adb logcat process.
- List<String> args = <String>['logcat', '-v', 'time'];
- String lastTimestamp = device.lastLogcatTimestamp;
+ final List<String> args = <String>['logcat', '-v', 'time'];
+ final String lastTimestamp = device.lastLogcatTimestamp;
if (lastTimestamp != null)
_timeOrigin = _adbTimestampToDateTime(lastTimestamp);
else
@@ -637,7 +637,7 @@
}
if (_timeOrigin != null) {
final String timestamp = timeMatch.group(0);
- DateTime time = _adbTimestampToDateTime(timestamp);
+ final DateTime time = _adbTimestampToDateTime(timestamp);
if (!time.isAfter(_timeOrigin)) {
// Ignore log messages before the origin.
return;
@@ -692,22 +692,22 @@
List<ForwardedPort> get forwardedPorts {
final List<ForwardedPort> ports = <ForwardedPort>[];
- String stdout = runCheckedSync(device.adbCommandForDevice(
+ final String stdout = runCheckedSync(device.adbCommandForDevice(
<String>['forward', '--list']
));
- List<String> lines = LineSplitter.split(stdout).toList();
+ final List<String> lines = LineSplitter.split(stdout).toList();
for (String line in lines) {
if (line.startsWith(device.id)) {
- List<String> splitLine = line.split("tcp:");
+ final List<String> splitLine = line.split("tcp:");
// Sanity check splitLine.
if (splitLine.length != 3)
continue;
// Attempt to extract ports.
- int hostPort = _extractPort(splitLine[1]);
- int devicePort = _extractPort(splitLine[2]);
+ final int hostPort = _extractPort(splitLine[1]);
+ final int devicePort = _extractPort(splitLine[2]);
// Failed, skip.
if ((hostPort == null) || (devicePort == null))
diff --git a/packages/flutter_tools/lib/src/android/android_sdk.dart b/packages/flutter_tools/lib/src/android/android_sdk.dart
index e80eb26..0a7389f 100644
--- a/packages/flutter_tools/lib/src/android/android_sdk.dart
+++ b/packages/flutter_tools/lib/src/android/android_sdk.dart
@@ -44,7 +44,7 @@
if (existingSdk?.adbPath != null)
return existingSdk.adbPath;
- AndroidSdk sdk = AndroidSdk.locateAndroidSdk();
+ final AndroidSdk sdk = AndroidSdk.locateAndroidSdk();
if (sdk?.latestVersion == null) {
return os.which('adb')?.path;
@@ -89,7 +89,7 @@
if (aaptBin != null) {
// Make sure we're using the aapt from the SDK.
aaptBin = fs.file(aaptBin.resolveSymbolicLinksSync());
- String dir = aaptBin.parent.parent.parent.path;
+ final String dir = aaptBin.parent.parent.parent.path;
if (validSdkDirectory(dir))
return new AndroidSdk(dir);
}
@@ -98,7 +98,7 @@
if (adbBin != null) {
// Make sure we're using the adb from the SDK.
adbBin = fs.file(adbBin.resolveSymbolicLinksSync());
- String dir = adbBin.parent.parent.path;
+ final String dir = adbBin.parent.parent.path;
if (validSdkDirectory(dir))
return new AndroidSdk(dir);
}
@@ -137,7 +137,7 @@
void _init() {
List<String> platforms = <String>[]; // android-22, ...
- Directory platformsDir = fs.directory(fs.path.join(directory, 'platforms'));
+ final Directory platformsDir = fs.directory(fs.path.join(directory, 'platforms'));
if (platformsDir.existsSync()) {
platforms = platformsDir
.listSync()
@@ -148,7 +148,7 @@
List<Version> buildTools = <Version>[]; // 19.1.0, 22.0.1, ...
- Directory buildToolsDir = fs.directory(fs.path.join(directory, 'build-tools'));
+ final Directory buildToolsDir = fs.directory(fs.path.join(directory, 'build-tools'));
if (buildToolsDir.existsSync()) {
buildTools = buildToolsDir
.listSync()
diff --git a/packages/flutter_tools/lib/src/android/android_studio.dart b/packages/flutter_tools/lib/src/android/android_studio.dart
index f9eeb42..186db70 100644
--- a/packages/flutter_tools/lib/src/android/android_studio.dart
+++ b/packages/flutter_tools/lib/src/android/android_studio.dart
@@ -34,7 +34,7 @@
/// Locate Gradle.
String get gradleExecutable {
// See if the user has explicitly configured gradle-dir.
- String gradleDir = config.getValue('gradle-dir');
+ final String gradleDir = config.getValue('gradle-dir');
if (gradleDir != null) {
if (fs.isFileSync(gradleDir))
return gradleDir;
@@ -58,9 +58,9 @@
List<String> _validationMessages = <String>[];
factory AndroidStudio.fromMacOSBundle(String bundlePath) {
- String studioPath = fs.path.join(bundlePath, 'Contents');
- String plistFile = fs.path.join(studioPath, 'Info.plist');
- String versionString =
+ final String studioPath = fs.path.join(bundlePath, 'Contents');
+ final String plistFile = fs.path.join(studioPath, 'Info.plist');
+ final String versionString =
getValueFromFile(plistFile, kCFBundleShortVersionStringKey);
Version version;
if (versionString != null)
@@ -69,12 +69,12 @@
}
factory AndroidStudio.fromHomeDot(Directory homeDotDir) {
- Match versionMatch =
+ final Match versionMatch =
_dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename);
if (versionMatch?.groupCount != 2) {
return null;
}
- Version version = new Version.parse(versionMatch[2]);
+ final Version version = new Version.parse(versionMatch[2]);
if (version == null) {
return null;
}
@@ -103,7 +103,7 @@
@override
int compareTo(AndroidStudio other) {
- int result = version.compareTo(other.version);
+ final int result = version.compareTo(other.version);
if (result == 0)
return directory.compareTo(other.directory);
return result;
@@ -111,7 +111,7 @@
/// Locates the newest, valid version of Android Studio.
static AndroidStudio latestValid() {
- String configuredStudio = config.getValue('android-studio-dir');
+ final String configuredStudio = config.getValue('android-studio-dir');
if (configuredStudio != null) {
String configuredStudioPath = configuredStudio;
if (platform.isMacOS && !configuredStudioPath.endsWith('Contents'))
@@ -121,7 +121,7 @@
}
// Find all available Studio installations.
- List<AndroidStudio> studios = allInstalled();
+ final List<AndroidStudio> studios = allInstalled();
if (studios.isEmpty) {
return null;
}
@@ -134,13 +134,13 @@
platform.isMacOS ? _allMacOS() : _allLinuxOrWindows();
static List<AndroidStudio> _allMacOS() {
- List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
+ final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
void _checkForStudio(String path) {
if (!fs.isDirectorySync(path))
return;
try {
- Iterable<Directory> directories = fs
+ final Iterable<Directory> directories = fs
.directory(path)
.listSync()
.where((FileSystemEntity e) => e is Directory);
@@ -159,7 +159,7 @@
_checkForStudio('/Applications');
_checkForStudio(fs.path.join(homeDirPath, 'Applications'));
- String configuredStudioDir = config.getValue('android-studio-dir');
+ final String configuredStudioDir = config.getValue('android-studio-dir');
if (configuredStudioDir != null) {
FileSystemEntity configuredStudio = fs.file(configuredStudioDir);
if (configuredStudio.basename == 'Contents') {
@@ -178,7 +178,7 @@
}
static List<AndroidStudio> _allLinuxOrWindows() {
- List<AndroidStudio> studios = <AndroidStudio>[];
+ final List<AndroidStudio> studios = <AndroidStudio>[];
bool _hasStudioAt(String path, {Version newerThan}) {
return studios.any((AndroidStudio studio) {
@@ -194,7 +194,7 @@
// pointing to the same installation, so we grab only the latest one.
for (FileSystemEntity entity in fs.directory(homeDirPath).listSync()) {
if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) {
- AndroidStudio studio = new AndroidStudio.fromHomeDot(entity);
+ final AndroidStudio studio = new AndroidStudio.fromHomeDot(entity);
if (studio != null &&
!_hasStudioAt(studio.directory, newerThan: studio.version)) {
studios.removeWhere(
@@ -204,7 +204,7 @@
}
}
- String configuredStudioDir = config.getValue('android-studio-dir');
+ final String configuredStudioDir = config.getValue('android-studio-dir');
if (configuredStudioDir != null && !_hasStudioAt(configuredStudioDir)) {
studios.add(new AndroidStudio(configuredStudioDir,
configured: configuredStudioDir));
@@ -244,7 +244,7 @@
gradlePaths = fs.directory(fs.path.join(directory, 'gradle')).listSync();
for (FileSystemEntity entry in gradlePaths.where((FileSystemEntity e) =>
e.basename.startsWith('gradle-') && e is Directory)) {
- Version version =
+ final Version version =
new Version.parse(entry.basename.substring('gradle-'.length)) ??
Version.unknown;
if (latestGradleVersion == null || version > latestGradleVersion) {
diff --git a/packages/flutter_tools/lib/src/android/android_studio_validator.dart b/packages/flutter_tools/lib/src/android/android_studio_validator.dart
index a30b732..d141b29 100644
--- a/packages/flutter_tools/lib/src/android/android_studio_validator.dart
+++ b/packages/flutter_tools/lib/src/android/android_studio_validator.dart
@@ -19,15 +19,15 @@
AndroidStudioValidator(this._studio) : super('Android Studio');
static List<DoctorValidator> get allValidators {
- List<DoctorValidator> validators = <DoctorValidator>[];
- List<AndroidStudio> studios = AndroidStudio.allInstalled();
+ final List<DoctorValidator> validators = <DoctorValidator>[];
+ final List<AndroidStudio> studios = AndroidStudio.allInstalled();
if (studios.isEmpty) {
validators.add(new NoAndroidStudioValidator());
} else {
validators.addAll(studios
.map((AndroidStudio studio) => new AndroidStudioValidator(studio)));
}
- String cfgGradleDir = config.getValue('gradle-dir');
+ final String cfgGradleDir = config.getValue('gradle-dir');
if (cfgGradleDir != null) {
validators.add(new ConfiguredGradleValidator(cfgGradleDir));
}
@@ -36,9 +36,9 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType type = ValidationType.missing;
- String studioVersionText = 'version ${_studio.version}';
+ final String studioVersionText = 'version ${_studio.version}';
messages
.add(new ValidationMessage('Android Studio at ${_studio.directory}'));
if (_studio.isValid) {
@@ -66,9 +66,9 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
- String cfgAndroidStudio = config.getValue('android-studio-dir');
+ final String cfgAndroidStudio = config.getValue('android-studio-dir');
if (cfgAndroidStudio != null) {
messages.add(
new ValidationMessage.error('android-studio-dir = $cfgAndroidStudio\n'
@@ -91,7 +91,7 @@
@override
Future<ValidationResult> validate() async {
ValidationType type = ValidationType.missing;
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
messages.add(new ValidationMessage('gradle-dir = $cfgGradleDir'));
@@ -103,7 +103,7 @@
String versionString;
if (processManager.canRun(gradleExecutable)) {
type = ValidationType.partial;
- ProcessResult result =
+ final ProcessResult result =
processManager.runSync(<String>[gradleExecutable, '--version']);
if (result.exitCode == 0) {
versionString = result.stdout
@@ -111,7 +111,7 @@
.split('\n')
.firstWhere((String s) => s.startsWith('Gradle '))
.substring('Gradle '.length);
- Version version = new Version.parse(versionString) ?? Version.unknown;
+ final Version version = new Version.parse(versionString) ?? Version.unknown;
if (version >= minGradleVersion) {
type = ValidationType.installed;
} else {
diff --git a/packages/flutter_tools/lib/src/android/android_workflow.dart b/packages/flutter_tools/lib/src/android/android_workflow.dart
index 35ebf87..e9977a3 100644
--- a/packages/flutter_tools/lib/src/android/android_workflow.dart
+++ b/packages/flutter_tools/lib/src/android/android_workflow.dart
@@ -25,13 +25,13 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType type = ValidationType.missing;
String sdkVersionText;
if (androidSdk == null) {
if (platform.environment.containsKey(kAndroidHome)) {
- String androidHomeDir = platform.environment[kAndroidHome];
+ final String androidHomeDir = platform.environment[kAndroidHome];
messages.add(new ValidationMessage.error(
'$kAndroidHome = $androidHomeDir\n'
'but Android SDK not found at this location.'
@@ -57,11 +57,11 @@
}
if (platform.environment.containsKey(kAndroidHome)) {
- String androidHomeDir = platform.environment[kAndroidHome];
+ final String androidHomeDir = platform.environment[kAndroidHome];
messages.add(new ValidationMessage('$kAndroidHome = $androidHomeDir'));
}
- List<String> validationResult = androidSdk.validateSdkWellFormed();
+ final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isEmpty) {
// Empty result means SDK is well formed.
@@ -72,10 +72,10 @@
try {
printTrace('java -version');
- ProcessResult result = processManager.runSync(<String>['java', '-version']);
+ final ProcessResult result = processManager.runSync(<String>['java', '-version']);
if (result.exitCode == 0) {
javaVersion = result.stderr;
- List<String> versionLines = javaVersion.split('\n');
+ final List<String> versionLines = javaVersion.split('\n');
javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
}
} catch (error) {
diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart
index 948befa..02b9382 100644
--- a/packages/flutter_tools/lib/src/android/gradle.dart
+++ b/packages/flutter_tools/lib/src/android/gradle.dart
@@ -35,15 +35,15 @@
}
FlutterPluginVersion get flutterPluginVersion {
- File plugin = fs.file('android/buildSrc/src/main/groovy/FlutterPlugin.groovy');
+ final File plugin = fs.file('android/buildSrc/src/main/groovy/FlutterPlugin.groovy');
if (plugin.existsSync()) {
- String packageLine = plugin.readAsLinesSync().skip(4).first;
+ final String packageLine = plugin.readAsLinesSync().skip(4).first;
if (packageLine == "package io.flutter.gradle") {
return FlutterPluginVersion.v2;
}
return FlutterPluginVersion.v1;
}
- File appGradle = fs.file('android/app/build.gradle');
+ final File appGradle = fs.file('android/app/build.gradle');
if (appGradle.existsSync()) {
for (String line in appGradle.readAsLinesSync()) {
if (line.contains(new RegExp(r"apply from: .*/flutter.gradle"))) {
@@ -69,9 +69,9 @@
}
String locateSystemGradle({ bool ensureExecutable: true }) {
- String gradle = gradleExecutable;
+ final String gradle = gradleExecutable;
if (ensureExecutable && gradle != null) {
- File file = fs.file(gradle);
+ final File file = fs.file(gradle);
if (file.existsSync())
os.makeExecutable(file);
}
@@ -104,7 +104,7 @@
Future<Null> buildGradleProject(BuildMode buildMode, String target) async {
// Create android/local.properties.
- File localProperties = fs.file('android/local.properties');
+ final File localProperties = fs.file('android/local.properties');
if (!localProperties.existsSync()) {
localProperties.writeAsStringSync(
'sdk.dir=${_escapePath(androidSdk.directory)}\n'
@@ -115,12 +115,12 @@
// FlutterPlugin v1 reads local.properties to determine build mode. Plugin v2
// uses the standard Android way to determine what to build, but we still
// update local.properties, in case we want to use it in the future.
- String buildModeName = getModeName(buildMode);
- SettingsFile settings = new SettingsFile.parseFromFile(localProperties);
+ final String buildModeName = getModeName(buildMode);
+ final SettingsFile settings = new SettingsFile.parseFromFile(localProperties);
settings.values['flutter.buildMode'] = buildModeName;
settings.writeContents(localProperties);
- String gradle = await ensureGradle();
+ final String gradle = await ensureGradle();
switch (flutterPluginVersion) {
case FlutterPluginVersion.none:
@@ -138,8 +138,8 @@
Future<Null> buildGradleProjectV1(String gradle) async {
// Run 'gradle build'.
- Status status = logger.startProgress('Running \'gradle build\'...', expectSlowOperation: true);
- int exitcode = await runCommandAndStreamOutput(
+ final Status status = logger.startProgress('Running \'gradle build\'...', expectSlowOperation: true);
+ final int exitcode = await runCommandAndStreamOutput(
<String>[fs.file(gradle).absolute.path, 'build'],
workingDirectory: 'android',
allowReentrantFlutter: true
@@ -149,22 +149,22 @@
if (exitcode != 0)
throwToolExit('Gradle build failed: $exitcode', exitCode: exitcode);
- File apkFile = fs.file(gradleAppOutV1);
+ final File apkFile = fs.file(gradleAppOutV1);
printStatus('Built $gradleAppOutV1 (${getSizeAsMB(apkFile.lengthSync())}).');
}
Future<Null> buildGradleProjectV2(String gradle, String buildModeName, String target) async {
- String assembleTask = "assemble${toTitleCase(buildModeName)}";
+ final String assembleTask = "assemble${toTitleCase(buildModeName)}";
// Run 'gradle assemble<BuildMode>'.
- Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true);
- String gradlePath = fs.file(gradle).absolute.path;
- List<String> command = <String>[gradlePath];
+ final Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true);
+ final String gradlePath = fs.file(gradle).absolute.path;
+ final List<String> command = <String>[gradlePath];
if (!logger.isVerbose) {
command.add('-q');
}
if (artifacts is LocalEngineArtifacts) {
- LocalEngineArtifacts localEngineArtifacts = artifacts;
+ final LocalEngineArtifacts localEngineArtifacts = artifacts;
printTrace('Using local engine: ${localEngineArtifacts.engineOutPath}');
command.add('-PlocalEngineOut=${localEngineArtifacts.engineOutPath}');
}
@@ -172,7 +172,7 @@
command.add('-Ptarget=$target');
}
command.add(assembleTask);
- int exitcode = await runCommandAndStreamOutput(
+ final int exitcode = await runCommandAndStreamOutput(
command,
workingDirectory: 'android',
allowReentrantFlutter: true
@@ -182,13 +182,13 @@
if (exitcode != 0)
throwToolExit('Gradle build failed: $exitcode', exitCode: exitcode);
- String apkFilename = 'app-$buildModeName.apk';
- File apkFile = fs.file('$gradleAppOutDir/$apkFilename');
+ final String apkFilename = 'app-$buildModeName.apk';
+ final File apkFile = fs.file('$gradleAppOutDir/$apkFilename');
// Copy the APK to app.apk, so `flutter run`, `flutter install`, etc. can find it.
apkFile.copySync('$gradleAppOutDir/app.apk');
printTrace('calculateSha: $gradleAppOutDir/app.apk');
- File apkShaFile = fs.file('$gradleAppOutDir/app.apk.sha1');
+ final File apkShaFile = fs.file('$gradleAppOutDir/app.apk.sha1');
apkShaFile.writeAsStringSync(calculateSha(apkFile));
printStatus('Built $apkFilename (${getSizeAsMB(apkFile.lengthSync())}).');
diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart
index 8f837a0..6d998c5 100644
--- a/packages/flutter_tools/lib/src/application_package.dart
+++ b/packages/flutter_tools/lib/src/application_package.dart
@@ -50,14 +50,14 @@
/// Creates a new AndroidApk from an existing APK.
factory AndroidApk.fromApk(String applicationBinary) {
- String aaptPath = androidSdk?.latestVersion?.aaptPath;
+ final String aaptPath = androidSdk?.latestVersion?.aaptPath;
if (aaptPath == null) {
printError('Unable to locate the Android SDK; please run \'flutter doctor\'.');
return null;
}
- List<String> aaptArgs = <String>[aaptPath, 'dump', 'badging', applicationBinary];
- ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs));
+ final List<String> aaptArgs = <String>[aaptPath, 'dump', 'badging', applicationBinary];
+ final ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs));
if (data == null) {
printError('Unable to read manifest info from $applicationBinary.');
@@ -100,19 +100,19 @@
if (!fs.isFileSync(manifestPath))
return null;
- String manifestString = fs.file(manifestPath).readAsStringSync();
- xml.XmlDocument document = xml.parse(manifestString);
+ final String manifestString = fs.file(manifestPath).readAsStringSync();
+ final xml.XmlDocument document = xml.parse(manifestString);
- Iterable<xml.XmlElement> manifests = document.findElements('manifest');
+ final Iterable<xml.XmlElement> manifests = document.findElements('manifest');
if (manifests.isEmpty)
return null;
- String packageId = manifests.first.getAttribute('package');
+ final String packageId = manifests.first.getAttribute('package');
String launchActivity;
for (xml.XmlElement category in document.findAllElements('category')) {
if (category.getAttribute('android:name') == 'android.intent.category.LAUNCHER') {
- xml.XmlElement activity = category.parent.parent;
- String activityName = activity.getAttribute('android:name');
+ final xml.XmlElement activity = category.parent.parent;
+ final String activityName = activity.getAttribute('android:name');
launchActivity = "$packageId/$activityName";
break;
}
@@ -146,18 +146,18 @@
factory IOSApp.fromIpa(String applicationBinary) {
Directory bundleDir;
try {
- Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
+ final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app_');
addShutdownHook(() async => await tempDir.delete(recursive: true));
os.unzip(fs.file(applicationBinary), tempDir);
- Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
+ final Directory payloadDir = fs.directory(fs.path.join(tempDir.path, 'Payload'));
bundleDir = payloadDir.listSync().singleWhere(_isBundleDirectory);
} on StateError catch (e, stackTrace) {
printError('Invalid prebuilt iOS binary: ${e.toString()}', stackTrace);
return null;
}
- String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
- String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
+ final String plistPath = fs.path.join(bundleDir.path, 'Info.plist');
+ final String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
if (id == null)
return null;
@@ -173,11 +173,11 @@
if (getCurrentHostPlatform() != HostPlatform.darwin_x64)
return null;
- String plistPath = fs.path.join('ios', 'Runner', 'Info.plist');
+ final String plistPath = fs.path.join('ios', 'Runner', 'Info.plist');
String id = plist.getValueFromFile(plistPath, plist.kCFBundleIdentifierKey);
if (id == null)
return null;
- String projectPath = fs.path.join('ios', 'Runner.xcodeproj');
+ final String projectPath = fs.path.join('ios', 'Runner.xcodeproj');
id = substituteXcodeVariables(id, projectPath, 'Runner');
return new BuildableIOSApp(
@@ -299,22 +299,22 @@
// package: name='io.flutter.gallery' versionCode='1' versionName='0.0.1' platformBuildVersionName='NMR1'
// launchable-activity: name='io.flutter.app.FlutterActivity' label='' icon=''
- Map<String, Map<String, String>> map = <String, Map<String, String>>{};
+ final Map<String, Map<String, String>> map = <String, Map<String, String>>{};
for (String line in data.split('\n')) {
- int index = line.indexOf(':');
+ final int index = line.indexOf(':');
if (index != -1) {
- String name = line.substring(0, index);
+ final String name = line.substring(0, index);
line = line.substring(index + 1).trim();
- Map<String, String> entries = <String, String>{};
+ final Map<String, String> entries = <String, String>{};
map[name] = entries;
for (String entry in line.split(' ')) {
entry = entry.trim();
if (entry.isNotEmpty && entry.contains('=')) {
- int split = entry.indexOf('=');
- String key = entry.substring(0, split);
+ final int split = entry.indexOf('=');
+ final String key = entry.substring(0, split);
String value = entry.substring(split + 1);
if (value.startsWith("'") && value.endsWith("'"))
value = value.substring(1, value.length - 1);
diff --git a/packages/flutter_tools/lib/src/artifacts.dart b/packages/flutter_tools/lib/src/artifacts.dart
index 2655019..a311e0f 100644
--- a/packages/flutter_tools/lib/src/artifacts.dart
+++ b/packages/flutter_tools/lib/src/artifacts.dart
@@ -105,7 +105,7 @@
}
String _getAndroidArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) {
- String engineDir = _getEngineArtifactsPath(platform, mode);
+ final String engineDir = _getEngineArtifactsPath(platform, mode);
switch (artifact) {
case Artifact.chromiumDebugKeyStore:
case Artifact.classesDexJar:
@@ -119,7 +119,7 @@
return fs.path.join(engineDir, _artifactToFileName(artifact));
case Artifact.genSnapshot:
assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.');
- String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform());
+ final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform());
return fs.path.join(engineDir, hostPlatform, _artifactToFileName(artifact));
default:
assert(false, 'Artifact $artifact not available for platform $platform.');
@@ -128,7 +128,7 @@
}
String _getIosArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) {
- String engineDir = _getEngineArtifactsPath(platform, mode);
+ final String engineDir = _getEngineArtifactsPath(platform, mode);
switch (artifact) {
case Artifact.dartIoEntriesTxt:
case Artifact.dartVmEntryPointsTxt:
@@ -157,8 +157,8 @@
continue returnResourcePath;
returnResourcePath:
case Artifact.icudtlDat:
- String engineArtifactsPath = cache.getArtifactDirectory('engine').path;
- String platformDirName = getNameForTargetPlatform(platform);
+ final String engineArtifactsPath = cache.getArtifactDirectory('engine').path;
+ final String platformDirName = getNameForTargetPlatform(platform);
return fs.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact));
default:
assert(false, 'Artifact $artifact not available for platform $platform.');
@@ -169,8 +169,8 @@
}
String _getEngineArtifactsPath(TargetPlatform platform, [BuildMode mode]) {
- String engineDir = cache.getArtifactDirectory('engine').path;
- String platformName = getNameForTargetPlatform(platform);
+ final String engineDir = cache.getArtifactDirectory('engine').path;
+ final String platformName = getNameForTargetPlatform(platform);
switch (platform) {
case TargetPlatform.linux_x64:
case TargetPlatform.darwin_x64:
@@ -182,7 +182,7 @@
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
assert(mode != null, 'Need to specify a build mode for platform $platform.');
- String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : '';
+ final String suffix = mode != BuildMode.debug ? '-${getModeName(mode)}' : '';
return fs.path.join(engineDir, platformName + suffix);
}
assert(false, 'Invalid platform $platform.');
@@ -222,7 +222,7 @@
case Artifact.classesDexJar:
return fs.path.join(engineOutPath, 'gen', 'flutter', 'shell', 'platform', 'android', 'android', _artifactToFileName(artifact));
case Artifact.libskyShellSo:
- String abi = _getAbiDirectory(platform);
+ final String abi = _getAbiDirectory(platform);
return fs.path.join(engineOutPath, 'gen', 'flutter', 'shell', 'platform', 'android', 'android', fs.path.join('android', 'libs', abi, _artifactToFileName(artifact)));
case Artifact.genSnapshot:
return _genSnapshotPath(platform);
@@ -257,7 +257,7 @@
}
String _skySnapshotPath() {
- String clangPath = fs.path.join(engineOutPath, 'clang_x64', _artifactToFileName(Artifact.skySnapshot));
+ final String clangPath = fs.path.join(engineOutPath, 'clang_x64', _artifactToFileName(Artifact.skySnapshot));
if (fs.isFileSync(clangPath))
return clangPath;
return fs.path.join(engineOutPath, _artifactToFileName(Artifact.skySnapshot));
diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart
index c69bc4d..f99d31e 100644
--- a/packages/flutter_tools/lib/src/asset.dart
+++ b/packages/flutter_tools/lib/src/asset.dart
@@ -41,7 +41,7 @@
if ((projectRoot == null) || (projectAssets == null))
return;
- List<String> assets = projectAssets.split(',');
+ final List<String> assets = projectAssets.split(',');
for (String asset in assets) {
if (asset == '')
continue;
@@ -57,7 +57,7 @@
if (_lastBuildTimestamp == null)
return true;
- FileStat stat = fs.file(manifestPath).statSync();
+ final FileStat stat = fs.file(manifestPath).statSync();
if (stat.type == FileSystemEntityType.NOT_FOUND)
return true;
@@ -88,19 +88,19 @@
return 0;
}
if (manifest != null) {
- int result = await _validateFlutterManifest(manifest);
+ final int result = await _validateFlutterManifest(manifest);
if (result != 0)
return result;
}
Map<String, dynamic> manifestDescriptor = manifest;
manifestDescriptor = manifestDescriptor['flutter'] ?? <String, dynamic>{};
- String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
+ final String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
_lastBuildTimestamp = new DateTime.now();
final PackageMap packageMap = new PackageMap(packagesPath);
- Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
+ final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
packageMap,
manifestDescriptor,
assetBasePath,
@@ -123,7 +123,7 @@
}
}
- List<_Asset> materialAssets = <_Asset>[];
+ final List<_Asset> materialAssets = <_Asset>[];
if (usesMaterialDesign && includeDefaultFonts) {
materialAssets.addAll(_getMaterialAssets(_kFontSetMaterial));
if (includeRobotoFonts)
@@ -136,7 +136,7 @@
entries[_kAssetManifestJson] = _createAssetManifest(assetVariants);
- DevFSContent fontManifest =
+ final DevFSContent fontManifest =
_createFontManifest(manifestDescriptor, usesMaterialDesign, includeDefaultFonts, includeRobotoFonts);
if (fontManifest != null)
entries[_kFontManifestJson] = fontManifest;
@@ -183,7 +183,7 @@
String get symbolicPrefix {
if (_assetEntry == null || _assetEntry == relativePath)
return null;
- int index = _assetEntry.indexOf(relativePath);
+ final int index = _assetEntry.indexOf(relativePath);
return index == -1 ? null : _assetEntry.substring(0, index);
}
@@ -192,7 +192,7 @@
}
Map<String, dynamic> _readMaterialFontsManifest() {
- String fontsPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
+ final String fontsPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
'packages', 'flutter_tools', 'schema', 'material_fonts.yaml');
return loadYaml(fs.file(fontsPath).readAsStringSync());
@@ -205,11 +205,11 @@
}
List<_Asset> _getMaterialAssets(String fontSet) {
- List<_Asset> result = <_Asset>[];
+ final List<_Asset> result = <_Asset>[];
for (Map<String, dynamic> family in _getMaterialFonts(fontSet)) {
for (Map<String, dynamic> font in family['fonts']) {
- String assetKey = font['asset'];
+ final String assetKey = font['asset'];
result.add(new _Asset(
base: fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'),
source: fs.path.basename(assetKey),
@@ -281,7 +281,7 @@
final List<String> combinedLicensesList = packageLicenses.keys.map(
(String license) {
- List<String> packageNames = packageLicenses[license].toList()
+ final List<String> packageNames = packageLicenses[license].toList()
..sort();
return packageNames.join('\n') + '\n\n' + license;
}
@@ -294,9 +294,9 @@
}
DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
- Map<String, List<String>> json = <String, List<String>>{};
+ final Map<String, List<String>> json = <String, List<String>>{};
for (_Asset main in assetVariants.keys) {
- List<String> variants = <String>[];
+ final List<String> variants = <String>[];
for (_Asset variant in assetVariants[main])
variants.add(variant.relativePath);
json[main.relativePath] = variants;
@@ -308,7 +308,7 @@
bool usesMaterialDesign,
bool includeDefaultFonts,
bool includeRobotoFonts) {
- List<Map<String, dynamic>> fonts = <Map<String, dynamic>>[];
+ final List<Map<String, dynamic>> fonts = <Map<String, dynamic>>[];
if (usesMaterialDesign && includeDefaultFonts) {
fonts.addAll(_getMaterialFonts(AssetBundle._kFontSetMaterial));
if (includeRobotoFonts)
@@ -331,7 +331,7 @@
String assetBase, {
List<String> excludeDirs: const <String>[]
}) {
- Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
+ final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
if (manifestDescriptor == null)
return result;
@@ -342,22 +342,22 @@
if (manifestDescriptor.containsKey('assets')) {
for (String asset in manifestDescriptor['assets']) {
- _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
+ final _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
if (!baseAsset.assetFileExists) {
printError('Error: unable to locate asset entry in pubspec.yaml: "$asset".');
return null;
}
- List<_Asset> variants = <_Asset>[];
+ final List<_Asset> variants = <_Asset>[];
result[baseAsset] = variants;
// Find asset variants
- String assetPath = baseAsset.assetFile.path;
- String assetFilename = fs.path.basename(assetPath);
- Directory assetDir = fs.directory(fs.path.dirname(assetPath));
+ final String assetPath = baseAsset.assetFile.path;
+ final String assetFilename = fs.path.basename(assetPath);
+ final Directory assetDir = fs.directory(fs.path.dirname(assetPath));
- List<FileSystemEntity> files = assetDir.listSync(recursive: true);
+ final List<FileSystemEntity> files = assetDir.listSync(recursive: true);
for (FileSystemEntity entity in files) {
if (!fs.isFileSync(entity.path))
@@ -368,7 +368,7 @@
continue;
if (fs.path.basename(entity.path) == assetFilename && entity.path != assetPath) {
- String key = fs.path.relative(entity.path, from: baseAsset.base);
+ final String key = fs.path.relative(entity.path, from: baseAsset.base);
String assetEntry;
if (baseAsset.symbolicPrefix != null)
assetEntry = fs.path.join(baseAsset.symbolicPrefix, key);
@@ -381,14 +381,14 @@
// Add assets referenced in the fonts section of the manifest.
if (manifestDescriptor.containsKey('fonts')) {
for (Map<String, dynamic> family in manifestDescriptor['fonts']) {
- List<Map<String, dynamic>> fonts = family['fonts'];
+ final List<Map<String, dynamic>> fonts = family['fonts'];
if (fonts == null) continue;
for (Map<String, dynamic> font in fonts) {
- String asset = font['asset'];
+ final String asset = font['asset'];
if (asset == null) continue;
- _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
+ final _Asset baseAsset = _resolveAsset(packageMap, assetBase, asset);
if (!baseAsset.assetFileExists) {
printError('Error: unable to locate asset entry in pubspec.yaml: "$asset".');
return null;
@@ -412,15 +412,15 @@
String packageKey = asset.substring(9);
String relativeAsset = asset;
- int index = packageKey.indexOf('/');
+ final int index = packageKey.indexOf('/');
if (index != -1) {
relativeAsset = packageKey.substring(index + 1);
packageKey = packageKey.substring(0, index);
}
- Uri uri = packageMap.map[packageKey];
+ final Uri uri = packageMap.map[packageKey];
if (uri != null && uri.scheme == 'file') {
- File file = fs.file(uri);
+ final File file = fs.file(uri);
return new _Asset(base: file.path, assetEntry: asset, relativePath: relativeAsset);
}
}
@@ -431,16 +431,16 @@
dynamic _loadFlutterManifest(String manifestPath) {
if (manifestPath == null || !fs.isFileSync(manifestPath))
return null;
- String manifestDescriptor = fs.file(manifestPath).readAsStringSync();
+ final String manifestDescriptor = fs.file(manifestPath).readAsStringSync();
return loadYaml(manifestDescriptor);
}
Future<int> _validateFlutterManifest(Object manifest) async {
- String schemaPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
+ final String schemaPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
'packages', 'flutter_tools', 'schema', 'pubspec_yaml.json');
- Schema schema = await Schema.createSchemaFromUrl(fs.path.toUri(schemaPath).toString());
+ final Schema schema = await Schema.createSchemaFromUrl(fs.path.toUri(schemaPath).toString());
- Validator validator = new Validator(schema);
+ final Validator validator = new Validator(schema);
if (validator.validate(manifest)) {
return 0;
} else {
diff --git a/packages/flutter_tools/lib/src/base/config.dart b/packages/flutter_tools/lib/src/base/config.dart
index 729bdd5..832280f 100644
--- a/packages/flutter_tools/lib/src/base/config.dart
+++ b/packages/flutter_tools/lib/src/base/config.dart
@@ -44,7 +44,7 @@
}
String _userHomeDir() {
- String envKey = platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
- String value = platform.environment[envKey];
+ final String envKey = platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
+ final String value = platform.environment[envKey];
return value == null ? '.' : value;
}
diff --git a/packages/flutter_tools/lib/src/base/context.dart b/packages/flutter_tools/lib/src/base/context.dart
index bb28b6e..c96c5bc 100644
--- a/packages/flutter_tools/lib/src/base/context.dart
+++ b/packages/flutter_tools/lib/src/base/context.dart
@@ -20,7 +20,7 @@
if (_instances.containsKey(type))
return true;
- AppContext parent = _calcParent(_zone);
+ final AppContext parent = _calcParent(_zone);
return parent != null ? parent.isSet(type) : false;
}
@@ -28,7 +28,7 @@
if (_instances.containsKey(type))
return _instances[type];
- AppContext parent = _calcParent(_zone);
+ final AppContext parent = _calcParent(_zone);
return parent?.getVariable(type);
}
@@ -49,11 +49,11 @@
}
AppContext _calcParent(Zone zone) {
- Zone parentZone = zone.parent;
+ final Zone parentZone = zone.parent;
if (parentZone == null)
return null;
- AppContext parentContext = parentZone['context'];
+ final AppContext parentContext = parentZone['context'];
return parentContext == this
? _calcParent(parentZone)
: parentContext;
@@ -70,7 +70,7 @@
}
Future<dynamic> _run(dynamic method()) async {
- Zone previousZone = _zone;
+ final Zone previousZone = _zone;
try {
_zone = Zone.current;
return await method();
diff --git a/packages/flutter_tools/lib/src/base/file_system.dart b/packages/flutter_tools/lib/src/base/file_system.dart
index 0cf12d5..6a4e7ef 100644
--- a/packages/flutter_tools/lib/src/base/file_system.dart
+++ b/packages/flutter_tools/lib/src/base/file_system.dart
@@ -34,9 +34,9 @@
/// It is permissible for [location] to represent an existing non-empty
/// directory as long as there is no collision with the `"file"` subdirectory.
void enableRecordingFileSystem(String location) {
- FileSystem originalFileSystem = fs;
- Directory dir = getRecordingSink(location, _kRecordingType);
- RecordingFileSystem fileSystem = new RecordingFileSystem(
+ final FileSystem originalFileSystem = fs;
+ final Directory dir = getRecordingSink(location, _kRecordingType);
+ final RecordingFileSystem fileSystem = new RecordingFileSystem(
delegate: _kLocalFs, destination: dir);
addShutdownHook(() async {
await fileSystem.recording.flush();
@@ -54,13 +54,13 @@
/// been recorded (i.e. the result of having been previously passed to
/// [enableRecordingFileSystem]), or a [ToolExit] will be thrown.
void enableReplayFileSystem(String location) {
- Directory dir = getReplaySource(location, _kRecordingType);
+ final Directory dir = getReplaySource(location, _kRecordingType);
context.setVariable(FileSystem, new ReplayFileSystem(recording: dir));
}
/// Create the ancestor directories of a file path if they do not already exist.
void ensureDirectoryExists(String filePath) {
- String dirPath = fs.path.dirname(filePath);
+ final String dirPath = fs.path.dirname(filePath);
if (fs.isDirectorySync(dirPath))
return;
try {
@@ -81,9 +81,9 @@
destDir.createSync(recursive: true);
srcDir.listSync().forEach((FileSystemEntity entity) {
- String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename);
+ final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename);
if (entity is File) {
- File newFile = destDir.fileSystem.file(newPath);
+ final File newFile = destDir.fileSystem.file(newPath);
newFile.writeAsBytesSync(entity.readAsBytesSync());
} else if (entity is Directory) {
copyDirectorySync(
@@ -105,7 +105,7 @@
/// directory exists as an entity other than a directory, a [ToolExit] will
/// also be thrown.
Directory getRecordingSink(String dirname, String basename) {
- String location = _kLocalFs.path.join(dirname, basename);
+ final String location = _kLocalFs.path.join(dirname, basename);
switch (_kLocalFs.typeSync(location, followLinks: false)) {
case FileSystemEntityType.FILE:
case FileSystemEntityType.LINK:
@@ -129,7 +129,7 @@
///
/// If the target directory does not exist, a [ToolExit] will be thrown.
Directory getReplaySource(String dirname, String basename) {
- Directory dir = _kLocalFs.directory(_kLocalFs.path.join(dirname, basename));
+ final Directory dir = _kLocalFs.directory(_kLocalFs.path.join(dirname, basename));
if (!dir.existsSync())
throwToolExit('Invalid replay-from location: $dirname ("$basename" does not exist)');
return dir;
diff --git a/packages/flutter_tools/lib/src/base/logger.dart b/packages/flutter_tools/lib/src/base/logger.dart
index a9d3eef..b5821b3 100644
--- a/packages/flutter_tools/lib/src/base/logger.dart
+++ b/packages/flutter_tools/lib/src/base/logger.dart
@@ -206,7 +206,7 @@
if (message.trim().isEmpty)
return;
- int millis = stopwatch.elapsedMilliseconds;
+ final int millis = stopwatch.elapsedMilliseconds;
stopwatch.reset();
String prefix;
@@ -220,8 +220,8 @@
}
prefix = '[$prefix] ';
- String indent = ''.padLeft(prefix.length);
- String indentMessage = message.replaceAll('\n', '\n$indent');
+ final String indent = ''.padLeft(prefix.length);
+ final String indentMessage = message.replaceAll('\n', '\n$indent');
if (type == _LogType.error) {
stderr.writeln(prefix + terminal.bolden(indentMessage));
@@ -243,9 +243,9 @@
class AnsiTerminal {
AnsiTerminal() {
- String term = platform.environment['TERM'];
+ final String term = platform.environment['TERM'];
// FLUTTER_ANSI_TERMINAL is a work-around for https://github.com/dart-lang/sdk/issues/28614
- bool flutterAnsiTerm = platform.environment.containsKey('FLUTTER_ANSI_TERMINAL');
+ final bool flutterAnsiTerm = platform.environment.containsKey('FLUTTER_ANSI_TERMINAL');
supportsColor = (term != null && term != 'dumb') || flutterAnsiTerm;
}
@@ -326,7 +326,7 @@
live = false;
if (expectSlowOperation) {
- double seconds = stopwatch.elapsedMilliseconds / Duration.MILLISECONDS_PER_SECOND;
+ final double seconds = stopwatch.elapsedMilliseconds / Duration.MILLISECONDS_PER_SECOND;
print('\b\b\b\b\b${secondsFormat.format(seconds).padLeft(4)}s');
} else {
print('\b\b\b\b\b${millisecondsFormat.format(stopwatch.elapsedMilliseconds).padLeft(3)}ms');
diff --git a/packages/flutter_tools/lib/src/base/net.dart b/packages/flutter_tools/lib/src/base/net.dart
index 0fd3b70..abce281 100644
--- a/packages/flutter_tools/lib/src/base/net.dart
+++ b/packages/flutter_tools/lib/src/base/net.dart
@@ -14,9 +14,9 @@
Future<List<int>> fetchUrl(Uri url) async {
printTrace('Downloading $url.');
- HttpClient httpClient = new HttpClient();
- HttpClientRequest request = await httpClient.getUrl(url);
- HttpClientResponse response = await request.close();
+ final HttpClient httpClient = new HttpClient();
+ final HttpClientRequest request = await httpClient.getUrl(url);
+ final HttpClientResponse response = await request.close();
printTrace('Received response statusCode=${response.statusCode}');
if (response.statusCode != 200) {
@@ -28,7 +28,7 @@
}
try {
- BytesBuilder responseBody = new BytesBuilder(copy: false);
+ final BytesBuilder responseBody = new BytesBuilder(copy: false);
await for (List<int> chunk in response)
responseBody.add(chunk);
diff --git a/packages/flutter_tools/lib/src/base/os.dart b/packages/flutter_tools/lib/src/base/os.dart
index 3441bc3..0d94547 100644
--- a/packages/flutter_tools/lib/src/base/os.dart
+++ b/packages/flutter_tools/lib/src/base/os.dart
@@ -54,10 +54,10 @@
/// to locate the binary.
@override
File which(String execName) {
- ProcessResult result = processManager.runSync(<String>['which', execName]);
+ final ProcessResult result = processManager.runSync(<String>['which', execName]);
if (result.exitCode != 0)
return null;
- String path = result.stdout.trim().split('\n').first.trim();
+ final String path = result.stdout.trim().split('\n').first.trim();
return fs.file(path);
}
@@ -90,7 +90,7 @@
@override
File which(String execName) {
- ProcessResult result = processManager.runSync(<String>['where', execName]);
+ final ProcessResult result = processManager.runSync(<String>['where', execName]);
if (result.exitCode != 0)
return null;
return fs.file(result.stdout.trim().split('\n').first.trim());
@@ -98,14 +98,14 @@
@override
void zip(Directory data, File zipFile) {
- Archive archive = new Archive();
+ final Archive archive = new Archive();
for (FileSystemEntity entity in data.listSync(recursive: true)) {
if (entity is! File) {
continue;
}
- File file = entity;
- String path = file.fileSystem.path.relative(file.path, from: data.path);
- List<int> bytes = file.readAsBytesSync();
+ final File file = entity;
+ final String path = file.fileSystem.path.relative(file.path, from: data.path);
+ final List<int> bytes = file.readAsBytesSync();
archive.addFile(new ArchiveFile(path, bytes.length, bytes));
}
zipFile.writeAsBytesSync(new ZipEncoder().encode(archive), flush: true);
@@ -113,14 +113,14 @@
@override
void unzip(File file, Directory targetDirectory) {
- Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync());
+ final Archive archive = new ZipDecoder().decodeBytes(file.readAsBytesSync());
for (ArchiveFile archiveFile in archive.files) {
// The archive package doesn't correctly set isFile.
if (!archiveFile.isFile || archiveFile.name.endsWith('/'))
continue;
- File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
+ final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name));
if (!destFile.parent.existsSync())
destFile.parent.createSync(recursive: true);
destFile.writeAsBytesSync(archiveFile.content);
@@ -134,8 +134,8 @@
}
Future<int> findAvailablePort() async {
- ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
- int port = socket.port;
+ final ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0);
+ final int port = socket.port;
await socket.close();
return port;
}
@@ -148,7 +148,7 @@
int iterationCount = 0;
while (iterationCount < _kMaxSearchIterations) {
- int port = defaultPort + iterationCount * searchStep;
+ final int port = defaultPort + iterationCount * searchStep;
if (await _isPortAvailable(port))
return port;
iterationCount++;
@@ -160,7 +160,7 @@
Future<bool> _isPortAvailable(int port) async {
try {
// TODO(ianh): This is super racy.
- ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port);
+ final ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port);
await socket.close();
return true;
} catch (error) {
@@ -178,7 +178,7 @@
while (true) {
if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel)))
return directory;
- String parent = fs.path.dirname(directory);
+ final String parent = fs.path.dirname(directory);
if (directory == parent) return null;
directory = parent;
}
diff --git a/packages/flutter_tools/lib/src/base/platform.dart b/packages/flutter_tools/lib/src/base/platform.dart
index 2645a94..dd96240 100644
--- a/packages/flutter_tools/lib/src/base/platform.dart
+++ b/packages/flutter_tools/lib/src/base/platform.dart
@@ -24,19 +24,19 @@
/// non-empty directory as long as there is no collision with the `"platform"`
/// subdirectory.
Future<Null> enableRecordingPlatform(String location) async {
- Directory dir = getRecordingSink(location, _kRecordingType);
- File file = _getPlatformManifest(dir);
+ final Directory dir = getRecordingSink(location, _kRecordingType);
+ final File file = _getPlatformManifest(dir);
await file.writeAsString(platform.toJson(), flush: true);
}
Future<Null> enableReplayPlatform(String location) async {
- Directory dir = getReplaySource(location, _kRecordingType);
- File file = _getPlatformManifest(dir);
- String json = await file.readAsString();
+ final Directory dir = getReplaySource(location, _kRecordingType);
+ final File file = _getPlatformManifest(dir);
+ final String json = await file.readAsString();
context.setVariable(Platform, new FakePlatform.fromJson(json));
}
File _getPlatformManifest(Directory dir) {
- String path = dir.fileSystem.path.join(dir.path, 'MANIFEST.txt');
+ final String path = dir.fileSystem.path.join(dir.path, 'MANIFEST.txt');
return dir.fileSystem.file(path);
}
diff --git a/packages/flutter_tools/lib/src/base/process.dart b/packages/flutter_tools/lib/src/base/process.dart
index 829ac3f..0620769 100644
--- a/packages/flutter_tools/lib/src/base/process.dart
+++ b/packages/flutter_tools/lib/src/base/process.dart
@@ -69,8 +69,8 @@
_shutdownHooksRunning = true;
try {
for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) {
- List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
- List<Future<dynamic>> futures = <Future<dynamic>>[];
+ final List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
+ final List<Future<dynamic>> futures = <Future<dynamic>>[];
for (ShutdownHook shutdownHook in hooks)
futures.add(shutdownHook());
await Future.wait<dynamic>(futures);
@@ -100,7 +100,7 @@
Map<String, String> environment
}) async {
_traceCommand(cmd, workingDirectory: workingDirectory);
- Process process = await processManager.start(
+ final Process process = await processManager.start(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter, environment)
@@ -119,13 +119,13 @@
StringConverter mapFunction,
Map<String, String> environment
}) async {
- Process process = await runCommand(
+ final Process process = await runCommand(
cmd,
workingDirectory: workingDirectory,
allowReentrantFlutter: allowReentrantFlutter,
environment: environment
);
- StreamSubscription<String> subscription = process.stdout
+ final StreamSubscription<String> subscription = process.stdout
.transform(UTF8.decoder)
.transform(const LineSplitter())
.where((String line) => filter == null ? true : filter.hasMatch(line))
@@ -133,7 +133,7 @@
if (mapFunction != null)
line = mapFunction(line);
if (line != null) {
- String message = '$prefix$line';
+ final String message = '$prefix$line';
if (trace)
printTrace(message);
else
@@ -160,7 +160,7 @@
}
Future<Null> runAndKill(List<String> cmd, Duration timeout) {
- Future<Process> proc = runDetached(cmd);
+ final Future<Process> proc = runDetached(cmd);
return new Future<Null>.delayed(timeout, () async {
printTrace('Intentionally killing ${cmd[0]}');
processManager.killPid((await proc).pid);
@@ -169,7 +169,7 @@
Future<Process> runDetached(List<String> cmd) {
_traceCommand(cmd);
- Future<Process> proc = processManager.start(
+ final Future<Process> proc = processManager.start(
cmd,
mode: ProcessStartMode.DETACHED,
);
@@ -181,12 +181,12 @@
bool allowReentrantFlutter: false
}) async {
_traceCommand(cmd, workingDirectory: workingDirectory);
- ProcessResult results = await processManager.run(
+ final ProcessResult results = await processManager.run(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter),
);
- RunResult runResults = new RunResult(results);
+ final RunResult runResults = new RunResult(results);
printTrace(runResults.toString());
return runResults;
}
@@ -241,7 +241,7 @@
}
void _traceCommand(List<String> args, { String workingDirectory }) {
- String argsText = args.join(' ');
+ final String argsText = args.join(' ');
if (workingDirectory == null)
printTrace(argsText);
else
@@ -257,7 +257,7 @@
bool hideStdout: false,
}) {
_traceCommand(cmd, workingDirectory: workingDirectory);
- ProcessResult results = processManager.runSync(
+ final ProcessResult results = processManager.runSync(
cmd,
workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter),
@@ -312,7 +312,7 @@
@override
String toString() {
- StringBuffer out = new StringBuffer();
+ final StringBuffer out = new StringBuffer();
if (processResult.stdout.isNotEmpty)
out.writeln(processResult.stdout);
if (processResult.stderr.isNotEmpty)
diff --git a/packages/flutter_tools/lib/src/base/process_manager.dart b/packages/flutter_tools/lib/src/base/process_manager.dart
index de9a8ba..41e85f6 100644
--- a/packages/flutter_tools/lib/src/base/process_manager.dart
+++ b/packages/flutter_tools/lib/src/base/process_manager.dart
@@ -28,10 +28,10 @@
/// directory as long as there is no collision with the `"process"`
/// subdirectory.
void enableRecordingProcessManager(String location) {
- ProcessManager originalProcessManager = processManager;
- Directory dir = getRecordingSink(location, _kRecordingType);
- ProcessManager delegate = const LocalProcessManager();
- RecordingProcessManager manager = new RecordingProcessManager(delegate, dir);
+ final ProcessManager originalProcessManager = processManager;
+ final Directory dir = getRecordingSink(location, _kRecordingType);
+ final ProcessManager delegate = const LocalProcessManager();
+ final RecordingProcessManager manager = new RecordingProcessManager(delegate, dir);
addShutdownHook(() async {
await manager.flush(finishRunningProcesses: true);
context.setVariable(ProcessManager, originalProcessManager);
@@ -48,7 +48,7 @@
/// recorded (i.e. the result of having been previously passed to
/// [enableRecordingProcessManager]), or a [ToolExit] will be thrown.
Future<Null> enableReplayProcessManager(String location) async {
- Directory dir = getReplaySource(location, _kRecordingType);
+ final Directory dir = getReplaySource(location, _kRecordingType);
ProcessManager manager;
try {
diff --git a/packages/flutter_tools/lib/src/base/utils.dart b/packages/flutter_tools/lib/src/base/utils.dart
index cfc216c..209b70c 100644
--- a/packages/flutter_tools/lib/src/base/utils.dart
+++ b/packages/flutter_tools/lib/src/base/utils.dart
@@ -22,7 +22,7 @@
}
String hex(List<int> bytes) {
- StringBuffer result = new StringBuffer();
+ final StringBuffer result = new StringBuffer();
for (int part in bytes)
result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
return result.toString();
@@ -55,18 +55,18 @@
/// Return the name of an enum item.
String getEnumName(dynamic enumItem) {
- String name = '$enumItem';
- int index = name.indexOf('.');
+ final String name = '$enumItem';
+ final int index = name.indexOf('.');
return index == -1 ? name : name.substring(index + 1);
}
File getUniqueFile(Directory dir, String baseName, String ext) {
- FileSystem fs = dir.fileSystem;
+ final FileSystem fs = dir.fileSystem;
int i = 1;
while (true) {
- String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
- File file = fs.file(fs.path.join(dir.path, name));
+ final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
+ final File file = fs.file(fs.path.join(dir.path, name));
if (!file.existsSync())
return file;
i++;
@@ -87,7 +87,7 @@
/// Return a relative path if [fullPath] is contained by the cwd, else return an
/// absolute path.
String getDisplayPath(String fullPath) {
- String cwd = fs.currentDirectory.path + fs.path.separator;
+ final String cwd = fs.currentDirectory.path + fs.path.separator;
return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath;
}
@@ -114,10 +114,10 @@
List<T> get items => _items.toList();
void updateWithNewList(List<T> updatedList) {
- Set<T> updatedSet = new Set<T>.from(updatedList);
+ final Set<T> updatedSet = new Set<T>.from(updatedList);
- Set<T> addedItems = updatedSet.difference(_items);
- Set<T> removedItems = _items.difference(updatedSet);
+ final Set<T> addedItems = updatedSet.difference(_items);
+ final Set<T> removedItems = _items.difference(updatedSet);
_items = updatedSet;
@@ -140,7 +140,7 @@
line = line.trim();
if (line.startsWith('#') || line.isEmpty)
continue;
- int index = line.indexOf('=');
+ final int index = line.indexOf('=');
if (index != -1)
values[line.substring(0, index)] = line.substring(index + 1);
}
@@ -174,7 +174,7 @@
/// random numbers as the source of the generated uuid.
String generateV4() {
// Generate xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx / 8-4-4-4-12.
- int special = 8 + _random.nextInt(4);
+ final int special = 8 + _random.nextInt(4);
return
'${_bitsDigits(16, 4)}${_bitsDigits(16, 4)}-'
diff --git a/packages/flutter_tools/lib/src/base/version.dart b/packages/flutter_tools/lib/src/base/version.dart
index 60887b3..5ef31f6 100644
--- a/packages/flutter_tools/lib/src/base/version.dart
+++ b/packages/flutter_tools/lib/src/base/version.dart
@@ -43,15 +43,15 @@
/// Creates a new [Version] by parsing [text].
factory Version.parse(String text) {
- Match match = versionPattern.firstMatch(text);
+ final Match match = versionPattern.firstMatch(text);
if (match == null) {
return null;
}
try {
- int major = int.parse(match[1] ?? '0');
- int minor = int.parse(match[3] ?? '0');
- int patch = int.parse(match[5] ?? '0');
+ final int major = int.parse(match[1] ?? '0');
+ final int minor = int.parse(match[3] ?? '0');
+ final int patch = int.parse(match[5] ?? '0');
return new Version._(major, minor, patch, text);
} on FormatException {
return null;
diff --git a/packages/flutter_tools/lib/src/build_info.dart b/packages/flutter_tools/lib/src/build_info.dart
index 5facec6..8c0bcc5 100644
--- a/packages/flutter_tools/lib/src/build_info.dart
+++ b/packages/flutter_tools/lib/src/build_info.dart
@@ -130,7 +130,7 @@
if (context == null || config == null)
return 'build';
- String buildDir = config.getValue('build-dir') ?? 'build';
+ final String buildDir = config.getValue('build-dir') ?? 'build';
if (fs.path.isAbsolute(buildDir)) {
throw new Exception(
'build-dir config setting in ${config.configPath} must be relative');
diff --git a/packages/flutter_tools/lib/src/cache.dart b/packages/flutter_tools/lib/src/cache.dart
index bbcafa7..17cfca1 100644
--- a/packages/flutter_tools/lib/src/cache.dart
+++ b/packages/flutter_tools/lib/src/cache.dart
@@ -89,7 +89,7 @@
static String get engineRevision {
if (_engineRevision == null) {
- File revisionFile = fs.file(fs.path.join(flutterRoot, 'bin', 'internal', 'engine.version'));
+ final File revisionFile = fs.file(fs.path.join(flutterRoot, 'bin', 'internal', 'engine.version'));
if (revisionFile.existsSync())
_engineRevision = revisionFile.readAsStringSync().trim();
}
@@ -108,7 +108,7 @@
/// Return a directory in the cache dir. For `pkg`, this will return `bin/cache/pkg`.
Directory getCacheDir(String name) {
- Directory dir = fs.directory(fs.path.join(getRoot().path, name));
+ final Directory dir = fs.directory(fs.path.join(getRoot().path, name));
if (!dir.existsSync())
dir.createSync(recursive: true);
return dir;
@@ -124,12 +124,12 @@
}
String getVersionFor(String artifactName) {
- File versionFile = fs.file(fs.path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version'));
+ final File versionFile = fs.file(fs.path.join(_rootOverride?.path ?? flutterRoot, 'bin', 'internal', '$artifactName.version'));
return versionFile.existsSync() ? versionFile.readAsStringSync().trim() : null;
}
String getStampFor(String artifactName) {
- File stampFile = getStampFileFor(artifactName);
+ final File stampFile = getStampFileFor(artifactName);
return stampFile.existsSync() ? stampFile.readAsStringSync().trim() : null;
}
@@ -142,8 +142,8 @@
}
bool isUpToDate() {
- MaterialFonts materialFonts = new MaterialFonts(cache);
- FlutterEngine engine = new FlutterEngine(cache);
+ final MaterialFonts materialFonts = new MaterialFonts(cache);
+ final FlutterEngine engine = new FlutterEngine(cache);
return materialFonts.isUpToDate() && engine.isUpToDate();
}
@@ -151,14 +151,14 @@
Future<String> getThirdPartyFile(String urlStr, String serviceName, {
bool unzip: false
}) async {
- Uri url = Uri.parse(urlStr);
- Directory thirdPartyDir = getArtifactDirectory('third_party');
+ final Uri url = Uri.parse(urlStr);
+ final Directory thirdPartyDir = getArtifactDirectory('third_party');
- Directory serviceDir = fs.directory(fs.path.join(thirdPartyDir.path, serviceName));
+ final Directory serviceDir = fs.directory(fs.path.join(thirdPartyDir.path, serviceName));
if (!serviceDir.existsSync())
serviceDir.createSync(recursive: true);
- File cachedFile = fs.file(fs.path.join(serviceDir.path, url.pathSegments.last));
+ final File cachedFile = fs.file(fs.path.join(serviceDir.path, url.pathSegments.last));
if (!cachedFile.existsSync()) {
try {
await _downloadFileToCache(url, cachedFile, unzip);
@@ -174,11 +174,11 @@
Future<Null> updateAll() async {
if (!_lockEnabled)
return null;
- MaterialFonts materialFonts = new MaterialFonts(cache);
+ final MaterialFonts materialFonts = new MaterialFonts(cache);
if (!materialFonts.isUpToDate())
await materialFonts.download();
- FlutterEngine engine = new FlutterEngine(cache);
+ final FlutterEngine engine = new FlutterEngine(cache);
if (!engine.isUpToDate())
await engine.download();
}
@@ -190,17 +190,17 @@
if (!location.parent.existsSync())
location.parent.createSync(recursive: true);
- List<int> fileBytes = await fetchUrl(url);
+ final List<int> fileBytes = await fetchUrl(url);
if (unzip) {
if (location is Directory && !location.existsSync())
location.createSync(recursive: true);
- File tempFile = fs.file(fs.path.join(fs.systemTempDirectory.path, '${url.toString().hashCode}.zip'));
+ final File tempFile = fs.file(fs.path.join(fs.systemTempDirectory.path, '${url.toString().hashCode}.zip'));
tempFile.writeAsBytesSync(fileBytes, flush: true);
os.unzip(tempFile, location);
tempFile.deleteSync();
} else {
- File file = location;
+ final File file = location;
file.writeAsBytesSync(fileBytes, flush: true);
}
}
@@ -220,9 +220,9 @@
}
Future<Null> download() {
- Status status = logger.startProgress('Downloading Material fonts...', expectSlowOperation: true);
+ final Status status = logger.startProgress('Downloading Material fonts...', expectSlowOperation: true);
- Directory fontsDir = cache.getArtifactDirectory(kName);
+ final Directory fontsDir = cache.getArtifactDirectory(kName);
if (fontsDir.existsSync())
fontsDir.deleteSync(recursive: true);
@@ -250,7 +250,7 @@
// Return a list of (cache directory path, download URL path) tuples.
List<List<String>> _getBinaryDirs() {
- List<List<String>> binaryDirs = <List<String>>[];
+ final List<List<String>> binaryDirs = <List<String>>[];
if (cache.includeAllPlatforms)
binaryDirs
@@ -309,16 +309,16 @@
];
bool isUpToDate() {
- Directory pkgDir = cache.getCacheDir('pkg');
+ final Directory pkgDir = cache.getCacheDir('pkg');
for (String pkgName in _getPackageDirs()) {
- String pkgPath = fs.path.join(pkgDir.path, pkgName);
+ final String pkgPath = fs.path.join(pkgDir.path, pkgName);
if (!fs.directory(pkgPath).existsSync())
return false;
}
- Directory engineDir = cache.getArtifactDirectory(kName);
+ final Directory engineDir = cache.getArtifactDirectory(kName);
for (List<String> toolsDir in _getBinaryDirs()) {
- Directory dir = fs.directory(fs.path.join(engineDir.path, toolsDir[0]));
+ final Directory dir = fs.directory(fs.path.join(engineDir.path, toolsDir[0]));
if (!dir.existsSync())
return false;
}
@@ -327,33 +327,33 @@
}
Future<Null> download() async {
- String engineVersion = cache.getVersionFor(kName);
- String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/';
+ final String engineVersion = cache.getVersionFor(kName);
+ final String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/';
- Directory pkgDir = cache.getCacheDir('pkg');
+ final Directory pkgDir = cache.getCacheDir('pkg');
for (String pkgName in _getPackageDirs()) {
- String pkgPath = fs.path.join(pkgDir.path, pkgName);
- Directory dir = fs.directory(pkgPath);
+ final String pkgPath = fs.path.join(pkgDir.path, pkgName);
+ final Directory dir = fs.directory(pkgPath);
if (dir.existsSync())
dir.deleteSync(recursive: true);
await _downloadItem('Downloading package $pkgName...', url + pkgName + '.zip', pkgDir);
}
- Directory engineDir = cache.getArtifactDirectory(kName);
+ final Directory engineDir = cache.getArtifactDirectory(kName);
if (engineDir.existsSync())
engineDir.deleteSync(recursive: true);
for (List<String> toolsDir in _getBinaryDirs()) {
- String cacheDir = toolsDir[0];
- String urlPath = toolsDir[1];
- Directory dir = fs.directory(fs.path.join(engineDir.path, cacheDir));
+ final String cacheDir = toolsDir[0];
+ final String urlPath = toolsDir[1];
+ final Directory dir = fs.directory(fs.path.join(engineDir.path, cacheDir));
await _downloadItem('Downloading $cacheDir tools...', url + urlPath, dir);
_makeFilesExecutable(dir);
- File frameworkZip = fs.file(fs.path.join(dir.path, 'Flutter.framework.zip'));
+ final File frameworkZip = fs.file(fs.path.join(dir.path, 'Flutter.framework.zip'));
if (frameworkZip.existsSync()) {
- Directory framework = fs.directory(fs.path.join(dir.path, 'Flutter.framework'));
+ final Directory framework = fs.directory(fs.path.join(dir.path, 'Flutter.framework'));
framework.createSync();
os.unzip(frameworkZip, framework);
}
@@ -365,7 +365,7 @@
void _makeFilesExecutable(Directory dir) {
for (FileSystemEntity entity in dir.listSync()) {
if (entity is File) {
- String name = fs.path.basename(entity.path);
+ final String name = fs.path.basename(entity.path);
if (name == 'sky_snapshot' || name == 'sky_shell')
os.makeExecutable(entity);
}
@@ -373,7 +373,7 @@
}
Future<Null> _downloadItem(String message, String url, Directory dest) {
- Status status = logger.startProgress(message, expectSlowOperation: true);
+ final Status status = logger.startProgress(message, expectSlowOperation: true);
return Cache._downloadFileToCache(Uri.parse(url), dest, true).then<Null>((Null value) {
status.stop();
}).whenComplete(() {
diff --git a/packages/flutter_tools/lib/src/commands/analyze_base.dart b/packages/flutter_tools/lib/src/commands/analyze_base.dart
index c31d0cb..ec5191c 100644
--- a/packages/flutter_tools/lib/src/commands/analyze_base.dart
+++ b/packages/flutter_tools/lib/src/commands/analyze_base.dart
@@ -39,7 +39,7 @@
void writeBenchmark(Stopwatch stopwatch, int errorCount, int membersMissingDocumentation) {
final String benchmarkOut = 'analysis_benchmark.json';
- Map<String, dynamic> data = <String, dynamic>{
+ final Map<String, dynamic> data = <String, dynamic>{
'time': (stopwatch.elapsedMilliseconds / 1000.0),
'issues': errorCount,
'missingDartDocs': membersMissingDocumentation
@@ -56,8 +56,8 @@
bool inRepo(List<String> fileList) {
if (fileList == null || fileList.isEmpty)
fileList = <String>[fs.path.current];
- String root = fs.path.normalize(fs.path.absolute(Cache.flutterRoot));
- String prefix = root + fs.path.separator;
+ final String root = fs.path.normalize(fs.path.absolute(Cache.flutterRoot));
+ final String prefix = root + fs.path.separator;
for (String file in fileList) {
file = fs.path.normalize(fs.path.absolute(file));
if (file == root || file.startsWith(prefix))
diff --git a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart
index daccb39..2d92ad9 100644
--- a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart
+++ b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart
@@ -46,7 +46,7 @@
analysisTarget = fs.currentDirectory.path;
}
- AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
+ final AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing));
server.onErrors.listen(_handleAnalysisErrors);
@@ -55,7 +55,7 @@
await server.start();
final int exitCode = await server.onExit;
- String message = 'Analysis server exited with code $exitCode.';
+ final String message = 'Analysis server exited with code $exitCode.';
if (exitCode != 0)
throwToolExit(message, exitCode: exitCode);
printStatus(message);
@@ -98,8 +98,8 @@
// Print an analysis summary.
String errorsMessage;
- int issueCount = errors.length;
- int issueDiff = issueCount - lastErrorCount;
+ final int issueCount = errors.length;
+ final int issueDiff = issueCount - lastErrorCount;
lastErrorCount = issueCount;
if (firstAnalysis)
@@ -113,8 +113,8 @@
else
errorsMessage = 'no issues found';
- String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}';
- String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
+ final String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}';
+ final String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
printStatus('$errorsMessage • analyzed $files, $seconds seconds');
if (firstAnalysis && isBenchmarking) {
@@ -156,8 +156,8 @@
int _id = 0;
Future<Null> start() async {
- String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot');
- List<String> command = <String>[
+ final String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot');
+ final List<String> command = <String>[
fs.path.join(dartSdkPath, 'bin', 'dart'),
snapshot,
'--sdk',
@@ -168,10 +168,10 @@
_process = await processManager.start(command);
_process.exitCode.whenComplete(() => _process = null);
- Stream<String> errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter());
+ final Stream<String> errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter());
errorStream.listen((String error) => printError(error));
- Stream<String> inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter());
+ final Stream<String> inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter());
inStream.listen(_handleServerResponse);
// Available options (many of these are obsolete):
@@ -199,7 +199,7 @@
Future<int> get onExit => _process.exitCode;
void _sendCommand(String method, Map<String, dynamic> params) {
- String message = JSON.encode(<String, dynamic> {
+ final String message = JSON.encode(<String, dynamic> {
'id': (++_id).toString(),
'method': method,
'params': params
@@ -211,12 +211,12 @@
void _handleServerResponse(String line) {
printTrace('<== $line');
- dynamic response = JSON.decode(line);
+ final dynamic response = JSON.decode(line);
if (response is Map<dynamic, dynamic>) {
if (response['event'] != null) {
- String event = response['event'];
- dynamic params = response['params'];
+ final String event = response['event'];
+ final dynamic params = response['params'];
if (params is Map<dynamic, dynamic>) {
if (event == 'server.status')
@@ -228,7 +228,7 @@
}
} else if (response['error'] != null) {
// Fields are 'code', 'message', and 'stackTrace'.
- Map<String, dynamic> error = response['error'];
+ final Map<String, dynamic> error = response['error'];
printError('Error response from the server: ${error['code']} ${error['message']}');
if (error['stackTrace'] != null)
printError(error['stackTrace']);
@@ -239,7 +239,7 @@
void _handleStatus(Map<String, dynamic> statusInfo) {
// {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}}
if (statusInfo['analysis'] != null) {
- bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
+ final bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
_analyzingController.add(isAnalyzing);
}
}
@@ -253,8 +253,8 @@
void _handleAnalysisIssues(Map<String, dynamic> issueInfo) {
// {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
- String file = issueInfo['file'];
- List<AnalysisError> errors = issueInfo['errors'].map((Map<String, dynamic> json) => new AnalysisError(json)).toList();
+ final String file = issueInfo['file'];
+ final List<AnalysisError> errors = issueInfo['errors'].map((Map<String, dynamic> json) => new AnalysisError(json)).toList();
_errorsController.add(new FileAnalysisErrors(file, errors));
}
@@ -299,7 +299,7 @@
if (offset != other.offset)
return offset - other.offset;
- int diff = other.severityLevel - severityLevel;
+ final int diff = other.severityLevel - severityLevel;
if (diff != 0)
return diff;
@@ -308,7 +308,7 @@
@override
String toString() {
- String relativePath = fs.path.relative(file);
+ final String relativePath = fs.path.relative(file);
return '${severity.toLowerCase().padLeft(7)} • $message • $relativePath:$startLine:$startColumn';
}
diff --git a/packages/flutter_tools/lib/src/commands/analyze_once.dart b/packages/flutter_tools/lib/src/commands/analyze_once.dart
index f0a8c50..2212c15 100644
--- a/packages/flutter_tools/lib/src/commands/analyze_once.dart
+++ b/packages/flutter_tools/lib/src/commands/analyze_once.dart
@@ -28,13 +28,13 @@
@override
Future<Null> analyze() async {
- Stopwatch stopwatch = new Stopwatch()..start();
- Set<Directory> pubSpecDirectories = new HashSet<Directory>();
- List<File> dartFiles = <File>[];
+ final Stopwatch stopwatch = new Stopwatch()..start();
+ final Set<Directory> pubSpecDirectories = new HashSet<Directory>();
+ final List<File> dartFiles = <File>[];
for (String file in argResults.rest.toList()) {
file = fs.path.normalize(fs.path.absolute(file));
- String root = fs.path.rootPrefix(file);
+ final String root = fs.path.rootPrefix(file);
dartFiles.add(fs.file(file));
while (file != root) {
file = fs.path.dirname(file);
@@ -45,15 +45,15 @@
}
}
- bool currentDirectory = argResults['current-directory'] && (argResults.wasParsed('current-directory') || dartFiles.isEmpty);
- bool currentPackage = argResults['current-package'] && (argResults.wasParsed('current-package') || dartFiles.isEmpty);
- bool flutterRepo = argResults['flutter-repo'] || inRepo(argResults.rest);
+ final bool currentDirectory = argResults['current-directory'] && (argResults.wasParsed('current-directory') || dartFiles.isEmpty);
+ final bool currentPackage = argResults['current-package'] && (argResults.wasParsed('current-package') || dartFiles.isEmpty);
+ final bool flutterRepo = argResults['flutter-repo'] || inRepo(argResults.rest);
//TODO (pq): revisit package and directory defaults
if (currentDirectory && !flutterRepo) {
// ./*.dart
- Directory currentDirectory = fs.directory('.');
+ final Directory currentDirectory = fs.directory('.');
bool foundOne = false;
for (FileSystemEntity entry in currentDirectory.listSync()) {
if (isDartFile(entry)) {
@@ -67,7 +67,7 @@
if (currentPackage && !flutterRepo) {
// **/.*dart
- Directory currentDirectory = fs.directory('.');
+ final Directory currentDirectory = fs.directory('.');
_collectDartFiles(currentDirectory, dartFiles);
pubSpecDirectories.add(currentDirectory);
}
@@ -80,21 +80,21 @@
}
// determine what all the various .packages files depend on
- PackageDependencyTracker dependencies = new PackageDependencyTracker();
+ final PackageDependencyTracker dependencies = new PackageDependencyTracker();
for (Directory directory in pubSpecDirectories) {
- String pubSpecYamlPath = fs.path.join(directory.path, 'pubspec.yaml');
- File pubSpecYamlFile = fs.file(pubSpecYamlPath);
+ final String pubSpecYamlPath = fs.path.join(directory.path, 'pubspec.yaml');
+ final File pubSpecYamlFile = fs.file(pubSpecYamlPath);
if (pubSpecYamlFile.existsSync()) {
// we are analyzing the actual canonical source for this package;
// make sure we remember that, in case all the packages are actually
// pointing elsewhere somehow.
- yaml.YamlMap pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync());
- String packageName = pubSpecYaml['name'];
- String packagePath = fs.path.normalize(fs.path.absolute(fs.path.join(directory.path, 'lib')));
+ final yaml.YamlMap pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync());
+ final String packageName = pubSpecYaml['name'];
+ final String packagePath = fs.path.normalize(fs.path.absolute(fs.path.join(directory.path, 'lib')));
dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath);
}
- String dotPackagesPath = fs.path.join(directory.path, '.packages');
- File dotPackages = fs.file(dotPackagesPath);
+ final String dotPackagesPath = fs.path.join(directory.path, '.packages');
+ final File dotPackages = fs.file(dotPackagesPath);
if (dotPackages.existsSync()) {
// this directory has opinions about what we should be using
dotPackages
@@ -102,10 +102,10 @@
.split('\n')
.where((String line) => !line.startsWith(new RegExp(r'^ *#')))
.forEach((String line) {
- int colon = line.indexOf(':');
+ final int colon = line.indexOf(':');
if (colon > 0) {
- String packageName = line.substring(0, colon);
- String packagePath = fs.path.fromUri(line.substring(colon+1));
+ final String packageName = line.substring(0, colon);
+ final String packagePath = fs.path.fromUri(line.substring(colon+1));
// Ensure that we only add the `analyzer` package defined in the vended SDK (and referred to with a local fs.path. directive).
// Analyzer package versions reached via transitive dependencies (e.g., via `test`) are ignored since they would produce
// spurious conflicts.
@@ -118,7 +118,7 @@
// prepare a union of all the .packages files
if (dependencies.hasConflicts) {
- StringBuffer message = new StringBuffer();
+ final StringBuffer message = new StringBuffer();
message.writeln(dependencies.generateConflictReport());
message.writeln('Make sure you have run "pub upgrade" in all the directories mentioned above.');
if (dependencies.hasConflictsAffectingFlutterRepo) {
@@ -131,7 +131,7 @@
'"pub deps --style=list" and "pub upgrade --verbosity=solver" in the affected directories.');
throwToolExit(message.toString());
}
- Map<String, String> packages = dependencies.asPackageMap();
+ final Map<String, String> packages = dependencies.asPackageMap();
Cache.releaseLockEarly();
@@ -142,16 +142,16 @@
logger.printStatus('Analyzing ${dartFiles.length} files...');
}
}
- DriverOptions options = new DriverOptions();
+ final DriverOptions options = new DriverOptions();
options.dartSdkPath = argResults['dart-sdk'];
options.packageMap = packages;
options.analysisOptionsFile = flutterRepo
? fs.path.join(Cache.flutterRoot, '.analysis_options_repo')
: fs.path.join(Cache.flutterRoot, 'packages', 'flutter', 'lib', 'analysis_options_user.yaml');
- AnalysisDriver analyzer = new AnalysisDriver(options);
+ final AnalysisDriver analyzer = new AnalysisDriver(options);
// TODO(pq): consider error handling
- List<AnalysisErrorDescription> errors = analyzer.analyze(dartFiles);
+ final List<AnalysisErrorDescription> errors = analyzer.analyze(dartFiles);
int errorCount = 0;
int membersMissingDocumentation = 0;
@@ -176,7 +176,7 @@
dumpErrors(errors.map<String>((AnalysisErrorDescription error) => error.asString()));
stopwatch.stop();
- String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
+ final String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
if (isBenchmarking)
writeBenchmark(stopwatch, errorCount, membersMissingDocumentation);
@@ -200,7 +200,7 @@
List<String> flutterRootComponents;
bool isFlutterLibrary(String filename) {
flutterRootComponents ??= fs.path.normalize(fs.path.absolute(Cache.flutterRoot)).split(fs.path.separator);
- List<String> filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.path.separator);
+ final List<String> filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.path.separator);
if (filenameComponents.length < flutterRootComponents.length + 4) // the 4: 'packages', package_name, 'lib', file_name
return false;
for (int index = 0; index < flutterRootComponents.length; index += 1) {
@@ -225,7 +225,7 @@
if (isDartFile(entity))
collected.add(entity);
if (entity is Directory) {
- String name = fs.path.basename(entity.path);
+ final String name = fs.path.basename(entity.path);
if (!name.startsWith('.') && name != 'packages')
_collectDartFiles(entity, collected);
}
@@ -262,10 +262,10 @@
}
void describeConflict(StringBuffer result) {
assert(hasConflict);
- List<String> targets = values.keys.toList();
+ final List<String> targets = values.keys.toList();
targets.sort((String a, String b) => values[b].length.compareTo(values[a].length));
for (String target in targets) {
- int count = values[target].length;
+ final int count = values[target].length;
result.writeln(' $count ${count == 1 ? 'source wants' : 'sources want'} "$target":');
bool canonical = false;
for (String source in values[target]) {
@@ -308,7 +308,7 @@
String generateConflictReport() {
assert(hasConflicts);
- StringBuffer result = new StringBuffer();
+ final StringBuffer result = new StringBuffer();
for (String package in packages.keys.where((String package) => packages[package].hasConflict)) {
result.writeln('Package "$package" has conflicts:');
packages[package].describeConflict(result);
@@ -317,7 +317,7 @@
}
Map<String, String> asPackageMap() {
- Map<String, String> result = <String, String>{};
+ final Map<String, String> result = <String, String>{};
for (String package in packages.keys)
result[package] = packages[package].target;
return result;
diff --git a/packages/flutter_tools/lib/src/commands/build.dart b/packages/flutter_tools/lib/src/commands/build.dart
index cd7ac3f..aef95a3 100644
--- a/packages/flutter_tools/lib/src/commands/build.dart
+++ b/packages/flutter_tools/lib/src/commands/build.dart
@@ -54,14 +54,14 @@
@mustCallSuper
Future<Null> runCommand() async {
if (isRunningOnBot) {
- File dotPackages = fs.file('.packages');
+ final File dotPackages = fs.file('.packages');
printStatus('Contents of .packages:');
if (dotPackages.existsSync())
printStatus(dotPackages.readAsStringSync());
else
printError('File not found: ${dotPackages.absolute.path}');
- File pubspecLock = fs.file('pubspec.lock');
+ final File pubspecLock = fs.file('pubspec.lock');
printStatus('Contents of pubspec.lock:');
if (pubspecLock.existsSync())
printStatus(pubspecLock.readAsStringSync());
@@ -86,7 +86,7 @@
@override
Future<Null> runCommand() async {
- Directory buildDir = fs.directory(getBuildDirectory());
+ final Directory buildDir = fs.directory(getBuildDirectory());
printStatus("Deleting '${buildDir.path}${fs.path.separator}'.");
if (!buildDir.existsSync())
diff --git a/packages/flutter_tools/lib/src/commands/build_aot.dart b/packages/flutter_tools/lib/src/commands/build_aot.dart
index 4a7337b..6441115 100644
--- a/packages/flutter_tools/lib/src/commands/build_aot.dart
+++ b/packages/flutter_tools/lib/src/commands/build_aot.dart
@@ -45,15 +45,15 @@
@override
Future<Null> runCommand() async {
await super.runCommand();
- String targetPlatform = argResults['target-platform'];
- TargetPlatform platform = getTargetPlatformForName(targetPlatform);
+ final String targetPlatform = argResults['target-platform'];
+ final TargetPlatform platform = getTargetPlatformForName(targetPlatform);
if (platform == null)
throwToolExit('Unknown platform: $targetPlatform');
- String typeName = artifacts.getEngineType(platform, getBuildMode());
- Status status = logger.startProgress('Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
+ final String typeName = artifacts.getEngineType(platform, getBuildMode());
+ final Status status = logger.startProgress('Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
expectSlowOperation: true);
- String outputPath = await buildAotSnapshot(
+ final String outputPath = await buildAotSnapshot(
findMainDartFile(targetFile),
platform,
getBuildMode(),
@@ -116,31 +116,31 @@
return null;
}
- String genSnapshot = artifacts.getArtifactPath(Artifact.genSnapshot, platform, buildMode);
+ final String genSnapshot = artifacts.getArtifactPath(Artifact.genSnapshot, platform, buildMode);
- Directory outputDir = fs.directory(outputPath);
+ final Directory outputDir = fs.directory(outputPath);
outputDir.createSync(recursive: true);
- String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');
- String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');
- String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');
- String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');
+ final String vmSnapshotData = fs.path.join(outputDir.path, 'vm_snapshot_data');
+ final String vmSnapshotInstructions = fs.path.join(outputDir.path, 'vm_snapshot_instr');
+ final String isolateSnapshotData = fs.path.join(outputDir.path, 'isolate_snapshot_data');
+ final String isolateSnapshotInstructions = fs.path.join(outputDir.path, 'isolate_snapshot_instr');
- String vmEntryPoints = artifacts.getArtifactPath(Artifact.dartVmEntryPointsTxt, platform, buildMode);
- String ioEntryPoints = artifacts.getArtifactPath(Artifact.dartIoEntriesTxt, platform, buildMode);
+ final String vmEntryPoints = artifacts.getArtifactPath(Artifact.dartVmEntryPointsTxt, platform, buildMode);
+ final String ioEntryPoints = artifacts.getArtifactPath(Artifact.dartIoEntriesTxt, platform, buildMode);
- PackageMap packageMap = new PackageMap(PackageMap.globalPackagesPath);
- String packageMapError = packageMap.checkValid();
+ final PackageMap packageMap = new PackageMap(PackageMap.globalPackagesPath);
+ final String packageMapError = packageMap.checkValid();
if (packageMapError != null) {
printError(packageMapError);
return null;
}
- String skyEnginePkg = _getSdkExtensionPath(packageMap, 'sky_engine');
- String uiPath = fs.path.join(skyEnginePkg, 'dart_ui', 'ui.dart');
- String jniPath = fs.path.join(skyEnginePkg, 'dart_jni', 'jni.dart');
- String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
+ final String skyEnginePkg = _getSdkExtensionPath(packageMap, 'sky_engine');
+ final String uiPath = fs.path.join(skyEnginePkg, 'dart_ui', 'ui.dart');
+ final String jniPath = fs.path.join(skyEnginePkg, 'dart_jni', 'jni.dart');
+ final String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
- List<String> filePaths = <String>[
+ final List<String> filePaths = <String>[
vmEntryPoints,
ioEntryPoints,
uiPath,
@@ -177,7 +177,7 @@
assert(false);
}
- List<String> missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList();
+ final List<String> missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList();
if (missingFiles.isNotEmpty) {
printError('Missing files: $missingFiles');
return null;
@@ -187,7 +187,7 @@
return null;
}
- List<String> genSnapshotCmd = <String>[
+ final List<String> genSnapshotCmd = <String>[
genSnapshot,
'--assert_initializer',
'--await_is_keyword',
@@ -242,7 +242,7 @@
genSnapshotCmd.add(mainPath);
- RunResult results = await runAsync(genSnapshotCmd);
+ final RunResult results = await runAsync(genSnapshotCmd);
if (results.exitCode != 0) {
printError('Dart snapshot generator failed with exit code ${results.exitCode}');
printError(results.toString());
@@ -255,16 +255,16 @@
printStatus('Building app.dylib...');
// These names are known to from the engine.
- String kVmSnapshotData = 'kDartVmSnapshotData';
- String kIsolateSnapshotData = 'kDartIsolateSnapshotData';
+ final String kVmSnapshotData = 'kDartVmSnapshotData';
+ final String kIsolateSnapshotData = 'kDartIsolateSnapshotData';
- String kVmSnapshotDataC = fs.path.join(outputDir.path, '$kVmSnapshotData.c');
- String kIsolateSnapshotDataC = fs.path.join(outputDir.path, '$kIsolateSnapshotData.c');
- String kVmSnapshotDataO = fs.path.join(outputDir.path, '$kVmSnapshotData.o');
- String kIsolateSnapshotDataO = fs.path.join(outputDir.path, '$kIsolateSnapshotData.o');
- String assemblyO = fs.path.join(outputDir.path, 'snapshot_assembly.o');
+ final String kVmSnapshotDataC = fs.path.join(outputDir.path, '$kVmSnapshotData.c');
+ final String kIsolateSnapshotDataC = fs.path.join(outputDir.path, '$kIsolateSnapshotData.c');
+ final String kVmSnapshotDataO = fs.path.join(outputDir.path, '$kVmSnapshotData.o');
+ final String kIsolateSnapshotDataO = fs.path.join(outputDir.path, '$kIsolateSnapshotData.o');
+ final String assemblyO = fs.path.join(outputDir.path, 'snapshot_assembly.o');
- List<String> commonBuildOptions = <String>['-arch', 'arm64', '-miphoneos-version-min=8.0'];
+ final List<String> commonBuildOptions = <String>['-arch', 'arm64', '-miphoneos-version-min=8.0'];
if (interpreter) {
runCheckedSync(<String>['mv', vmSnapshotData, fs.path.join(outputDir.path, kVmSnapshotData)]);
@@ -289,9 +289,9 @@
..addAll(<String>['-c', assembly, '-o', assemblyO]));
}
- String appSo = fs.path.join(outputDir.path, 'app.dylib');
+ final String appSo = fs.path.join(outputDir.path, 'app.dylib');
- List<String> linkCommand = <String>['xcrun', 'clang']
+ final List<String> linkCommand = <String>['xcrun', 'clang']
..addAll(commonBuildOptions)
..addAll(<String>[
'-dynamiclib',
diff --git a/packages/flutter_tools/lib/src/commands/build_apk.dart b/packages/flutter_tools/lib/src/commands/build_apk.dart
index 50031aa..44ac978 100644
--- a/packages/flutter_tools/lib/src/commands/build_apk.dart
+++ b/packages/flutter_tools/lib/src/commands/build_apk.dart
@@ -53,7 +53,7 @@
}
void add(File asset, String relativePath) {
- String destPath = fs.path.join(_assetDir.path, relativePath);
+ final String destPath = fs.path.join(_assetDir.path, relativePath);
ensureDirectoryExists(destPath);
asset.copySync(destPath);
}
@@ -94,7 +94,7 @@
}
void compileClassesDex(File classesDex, List<File> jars) {
- List<String> packageArgs = <String>[_dx.path,
+ final List<String> packageArgs = <String>[_dx.path,
'--dex',
'--force-jumbo',
'--output', classesDex.path
@@ -106,7 +106,7 @@
}
void package(File outputApk, File androidManifest, Directory assets, Directory artifacts, Directory resources, BuildMode buildMode) {
- List<String> packageArgs = <String>[_aapt.path,
+ final List<String> packageArgs = <String>[_aapt.path,
'package',
'-M', androidManifest.path,
'-A', assets.path,
@@ -222,8 +222,8 @@
Future<Null> runCommand() async {
await super.runCommand();
- TargetPlatform targetPlatform = _getTargetPlatform(argResults['target-arch']);
- BuildMode buildMode = getBuildMode();
+ final TargetPlatform targetPlatform = _getTargetPlatform(argResults['target-arch']);
+ final BuildMode buildMode = getBuildMode();
if (targetPlatform != TargetPlatform.android_arm && buildMode != BuildMode.debug)
throwToolExit('Profile and release builds are only supported on ARM targets.');
@@ -277,7 +277,7 @@
String resources,
Map<String, File> extraFiles
) async {
- _ApkComponents components = new _ApkComponents();
+ final _ApkComponents components = new _ApkComponents();
components.manifest = fs.file(manifest);
components.resources = resources == null ? null : fs.directory(resources);
components.extraFiles = extraFiles != null ? extraFiles : <String, File>{};
@@ -290,7 +290,7 @@
await parseServiceConfigs(components.services, jars: components.jars);
- List<File> allFiles = <File>[
+ final List<File> allFiles = <File>[
components.manifest, components.icuData, components.libSkyShell, components.debugKeystore
]..addAll(components.jars)
..addAll(components.extraFiles.values);
@@ -316,52 +316,52 @@
assert(platform != null);
assert(buildMode != null);
- Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
+ final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
printTrace('Building APK; buildMode: ${getModeName(buildMode)}.');
try {
- _ApkBuilder builder = new _ApkBuilder(androidSdk.latestVersion);
- String error = builder.checkDependencies();
+ final _ApkBuilder builder = new _ApkBuilder(androidSdk.latestVersion);
+ final String error = builder.checkDependencies();
if (error != null) {
printError(error);
return 1;
}
- File classesDex = fs.file('${tempDir.path}/classes.dex');
+ final File classesDex = fs.file('${tempDir.path}/classes.dex');
builder.compileClassesDex(classesDex, components.jars);
- File servicesConfig =
+ final File servicesConfig =
generateServiceDefinitions(tempDir.path, components.services);
- _AssetBuilder assetBuilder = new _AssetBuilder(tempDir, 'assets');
+ final _AssetBuilder assetBuilder = new _AssetBuilder(tempDir, 'assets');
assetBuilder.add(components.icuData, 'icudtl.dat');
assetBuilder.add(fs.file(flxPath), 'app.flx');
assetBuilder.add(servicesConfig, 'services.json');
- _AssetBuilder artifactBuilder = new _AssetBuilder(tempDir, 'artifacts');
+ final _AssetBuilder artifactBuilder = new _AssetBuilder(tempDir, 'artifacts');
artifactBuilder.add(classesDex, 'classes.dex');
- String abiDir = getAbiDirectory(platform);
+ final String abiDir = getAbiDirectory(platform);
artifactBuilder.add(components.libSkyShell, 'lib/$abiDir/libsky_shell.so');
for (String relativePath in components.extraFiles.keys)
artifactBuilder.add(components.extraFiles[relativePath], relativePath);
- File unalignedApk = fs.file('${tempDir.path}/app.apk.unaligned');
+ final File unalignedApk = fs.file('${tempDir.path}/app.apk.unaligned');
builder.package(
unalignedApk, components.manifest, assetBuilder.directory,
artifactBuilder.directory, components.resources, buildMode
);
- File finalApk = fs.file(outputFile);
+ final File finalApk = fs.file(outputFile);
ensureDirectoryExists(finalApk.path);
builder.align(unalignedApk, finalApk);
- int signResult = _signApk(builder, components, finalApk, keystore, buildMode);
+ final int signResult = _signApk(builder, components, finalApk, keystore, buildMode);
if (signResult != 0)
return signResult;
printTrace('calculateSha: $outputFile');
- File apkShaFile = fs.file('$outputFile.sha1');
+ final File apkShaFile = fs.file('$outputFile.sha1');
apkShaFile.writeAsStringSync(calculateSha(finalApk));
return 0;
@@ -419,17 +419,17 @@
BuildMode buildMode,
Map<String, File> extraFiles
) {
- FileStat apkStat = fs.statSync(apkPath);
+ final FileStat apkStat = fs.statSync(apkPath);
// Note: This list of dependencies is imperfect, but will do for now. We
// purposely don't include the .dart files, because we can load those
// over the network without needing to rebuild (at least on Android).
- List<String> dependencies = <String>[
+ final List<String> dependencies = <String>[
manifest,
_kFlutterManifestPath,
_kPackagesStatusPath
];
dependencies.addAll(extraFiles.values.map((File file) => file.path));
- Iterable<FileStat> dependenciesStat =
+ final Iterable<FileStat> dependenciesStat =
dependencies.map((String path) => fs.statSync(path));
if (apkStat.type == FileSystemEntityType.NOT_FOUND)
@@ -443,8 +443,8 @@
if (!fs.isFileSync('$apkPath.sha1'))
return true;
- String lastBuildType = _readBuildMeta(fs.path.dirname(apkPath))['targetBuildType'];
- String targetBuildType = _getTargetBuildTypeToken(platform, buildMode, fs.file(apkPath));
+ final String lastBuildType = _readBuildMeta(fs.path.dirname(apkPath))['targetBuildType'];
+ final String targetBuildType = _getTargetBuildTypeToken(platform, buildMode, fs.file(apkPath));
if (lastBuildType != targetBuildType)
return true;
@@ -471,18 +471,18 @@
if (androidSdk == null)
throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.');
- List<String> validationResult = androidSdk.validateSdkWellFormed();
+ final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isNotEmpty) {
validationResult.forEach(printError);
throwToolExit('Try re-installing or updating your Android SDK.');
}
- Map<String, File> extraFiles = <String, File>{};
+ final Map<String, File> extraFiles = <String, File>{};
if (fs.isDirectorySync(_kDefaultAssetsPath)) {
- Directory assetsDir = fs.directory(_kDefaultAssetsPath);
+ final Directory assetsDir = fs.directory(_kDefaultAssetsPath);
for (FileSystemEntity entity in assetsDir.listSync(recursive: true)) {
if (entity is File) {
- String targetPath = entity.path.substring(assetsDir.path.length);
+ final String targetPath = entity.path.substring(assetsDir.path.length);
extraFiles["assets/$targetPath"] = entity;
}
}
@@ -508,13 +508,13 @@
resources = _kDefaultResourcesPath;
}
- _ApkComponents components = await _findApkComponents(platform, buildMode, manifest, resources, extraFiles);
+ final _ApkComponents components = await _findApkComponents(platform, buildMode, manifest, resources, extraFiles);
if (components == null)
throwToolExit('Failure building APK: unable to find components.');
- String typeName = artifacts.getEngineType(platform, buildMode);
- Status status = logger.startProgress('Building APK in ${getModeName(buildMode)} mode ($typeName)...',
+ final String typeName = artifacts.getEngineType(platform, buildMode);
+ final Status status = logger.startProgress('Building APK in ${getModeName(buildMode)} mode ($typeName)...',
expectSlowOperation: true);
if (flxPath != null && flxPath.isNotEmpty) {
@@ -547,20 +547,20 @@
if (!fs.isDirectorySync(aotPath))
throwToolExit('AOT snapshot does not exist: $aotPath');
for (String aotFilename in kAotSnapshotFiles) {
- String aotFilePath = fs.path.join(aotPath, aotFilename);
+ final String aotFilePath = fs.path.join(aotPath, aotFilename);
if (!fs.isFileSync(aotFilePath))
throwToolExit('Missing AOT snapshot file: $aotFilePath');
components.extraFiles['assets/$aotFilename'] = fs.file(aotFilePath);
}
}
- int result = _buildApk(platform, buildMode, components, flxPath, keystore, outputFile);
+ final int result = _buildApk(platform, buildMode, components, flxPath, keystore, outputFile);
status.stop();
if (result != 0)
throwToolExit('Build APK failed ($result)', exitCode: result);
- File apkFile = fs.file(outputFile);
+ final File apkFile = fs.file(outputFile);
printTrace('Built $outputFile (${getSizeAsMB(apkFile.lengthSync())}).');
_writeBuildMetaEntry(
@@ -583,7 +583,7 @@
if (androidSdk == null)
throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.');
- List<String> validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false);
+ final List<String> validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false);
if (validationResult.isNotEmpty) {
validationResult.forEach(printError);
throwToolExit('Try re-installing or updating your Android SDK.');
@@ -622,23 +622,23 @@
}
Map<String, dynamic> _readBuildMeta(String buildDirectoryPath) {
- File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
+ final File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
if (buildMetaFile.existsSync())
return JSON.decode(buildMetaFile.readAsStringSync());
return <String, dynamic>{};
}
void _writeBuildMetaEntry(String buildDirectoryPath, String key, dynamic value) {
- Map<String, dynamic> meta = _readBuildMeta(buildDirectoryPath);
+ final Map<String, dynamic> meta = _readBuildMeta(buildDirectoryPath);
meta[key] = value;
- File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
+ final File buildMetaFile = fs.file(fs.path.join(buildDirectoryPath, 'build_meta.json'));
buildMetaFile.writeAsStringSync(toPrettyJson(meta));
}
String _getTargetBuildTypeToken(TargetPlatform platform, BuildMode buildMode, File outputBinary) {
String buildType = getNameForTargetPlatform(platform) + '-' + getModeName(buildMode);
if (artifacts is LocalEngineArtifacts) {
- LocalEngineArtifacts localEngineArtifacts = artifacts;
+ final LocalEngineArtifacts localEngineArtifacts = artifacts;
buildType += ' [${localEngineArtifacts.engineOutPath}]';
}
if (outputBinary.existsSync())
diff --git a/packages/flutter_tools/lib/src/commands/build_flx.dart b/packages/flutter_tools/lib/src/commands/build_flx.dart
index 53927fc..ee652a0 100644
--- a/packages/flutter_tools/lib/src/commands/build_flx.dart
+++ b/packages/flutter_tools/lib/src/commands/build_flx.dart
@@ -39,7 +39,7 @@
@override
Future<Null> runCommand() async {
await super.runCommand();
- String outputPath = argResults['output-file'];
+ final String outputPath = argResults['output-file'];
await build(
mainPath: targetFile,
diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart
index 8796c51..1bf1a6c 100644
--- a/packages/flutter_tools/lib/src/commands/build_ios.dart
+++ b/packages/flutter_tools/lib/src/commands/build_ios.dart
@@ -39,19 +39,19 @@
@override
Future<Null> runCommand() async {
- bool forSimulator = argResults['simulator'];
+ final bool forSimulator = argResults['simulator'];
defaultBuildMode = forSimulator ? BuildMode.debug : BuildMode.release;
await super.runCommand();
if (getCurrentHostPlatform() != HostPlatform.darwin_x64)
throwToolExit('Building for iOS is only supported on the Mac.');
- IOSApp app = applicationPackages.getPackageForPlatform(TargetPlatform.ios);
+ final IOSApp app = applicationPackages.getPackageForPlatform(TargetPlatform.ios);
if (app == null)
throwToolExit('Application not configured for iOS');
- bool shouldCodesign = argResults['codesign'];
+ final bool shouldCodesign = argResults['codesign'];
if (!forSimulator && !shouldCodesign) {
printStatus('Warning: Building for device with codesigning disabled. You will '
@@ -61,12 +61,12 @@
if (forSimulator && !isEmulatorBuildMode(getBuildMode()))
throwToolExit('${toTitleCase(getModeName(getBuildMode()))} mode is not supported for emulators.');
- String logTarget = forSimulator ? 'simulator' : 'device';
+ final String logTarget = forSimulator ? 'simulator' : 'device';
- String typeName = artifacts.getEngineType(TargetPlatform.ios, getBuildMode());
- Status status = logger.startProgress('Building $app for $logTarget ($typeName)...',
+ final String typeName = artifacts.getEngineType(TargetPlatform.ios, getBuildMode());
+ final Status status = logger.startProgress('Building $app for $logTarget ($typeName)...',
expectSlowOperation: true);
- XcodeBuildResult result = await buildXcodeProject(
+ final XcodeBuildResult result = await buildXcodeProject(
app: app,
mode: getBuildMode(),
target: targetFile,
diff --git a/packages/flutter_tools/lib/src/commands/channel.dart b/packages/flutter_tools/lib/src/commands/channel.dart
index 30ec6a4..0c836e9 100644
--- a/packages/flutter_tools/lib/src/commands/channel.dart
+++ b/packages/flutter_tools/lib/src/commands/channel.dart
@@ -33,18 +33,18 @@
}
Future<Null> _listChannels() async {
- String currentBranch = runSync(
+ final String currentBranch = runSync(
<String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
workingDirectory: Cache.flutterRoot);
printStatus('Flutter channels:');
- int result = await runCommandAndStreamOutput(
+ final int result = await runCommandAndStreamOutput(
<String>['git', 'branch', '-r'],
workingDirectory: Cache.flutterRoot,
mapFunction: (String line) {
- List<String> split = line.split('/');
+ final List<String> split = line.split('/');
if (split.length < 2) return null;
- String branchName = split[1];
+ final String branchName = split[1];
if (branchName.startsWith('HEAD')) return null;
if (branchName == currentBranch) return '* $branchName';
return ' $branchName';
@@ -56,7 +56,7 @@
Future<Null> _switchChannel(String branchName) async {
printStatus('Switching to flutter channel named $branchName');
- int result = await runCommandAndStreamOutput(
+ final int result = await runCommandAndStreamOutput(
<String>['git', 'checkout', branchName],
workingDirectory: Cache.flutterRoot,
);
diff --git a/packages/flutter_tools/lib/src/commands/config.dart b/packages/flutter_tools/lib/src/commands/config.dart
index c00a24d..59484e5 100644
--- a/packages/flutter_tools/lib/src/commands/config.dart
+++ b/packages/flutter_tools/lib/src/commands/config.dart
@@ -49,7 +49,7 @@
@override
Future<Null> runCommand() async {
if (argResults.wasParsed('analytics')) {
- bool value = argResults['analytics'];
+ final bool value = argResults['analytics'];
flutterUsage.enabled = value;
printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.');
}
diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart
index fd4c56c..902670c 100644
--- a/packages/flutter_tools/lib/src/commands/create.dart
+++ b/packages/flutter_tools/lib/src/commands/create.dart
@@ -69,21 +69,21 @@
await Cache.instance.updateAll();
- String flutterRoot = fs.path.absolute(Cache.flutterRoot);
+ final String flutterRoot = fs.path.absolute(Cache.flutterRoot);
- String flutterPackagesDirectory = fs.path.join(flutterRoot, 'packages');
- String flutterPackagePath = fs.path.join(flutterPackagesDirectory, 'flutter');
+ final String flutterPackagesDirectory = fs.path.join(flutterRoot, 'packages');
+ final String flutterPackagePath = fs.path.join(flutterPackagesDirectory, 'flutter');
if (!fs.isFileSync(fs.path.join(flutterPackagePath, 'pubspec.yaml')))
throwToolExit('Unable to find package:flutter in $flutterPackagePath', exitCode: 2);
- String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver');
+ final String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver');
if (!fs.isFileSync(fs.path.join(flutterDriverPackagePath, 'pubspec.yaml')))
throwToolExit('Unable to find package:flutter_driver in $flutterDriverPackagePath', exitCode: 2);
- Directory projectDir = fs.directory(argResults.rest.first);
- String dirPath = fs.path.normalize(projectDir.absolute.path);
- String relativePath = fs.path.relative(dirPath);
- String projectName = _normalizeProjectName(fs.path.basename(dirPath));
+ final Directory projectDir = fs.directory(argResults.rest.first);
+ final String dirPath = fs.path.normalize(projectDir.absolute.path);
+ final String relativePath = fs.path.relative(dirPath);
+ final String projectName = _normalizeProjectName(fs.path.basename(dirPath));
String error =_validateProjectDir(dirPath, flutterRoot: flutterRoot);
if (error != null)
@@ -93,7 +93,7 @@
if (error != null)
throwToolExit(error);
- int generatedCount = _renderTemplates(
+ final int generatedCount = _renderTemplates(
projectName,
argResults['description'],
dirPath,
@@ -148,7 +148,7 @@
printStatus('Creating project ${fs.path.relative(dirPath)}...');
- Map<String, dynamic> templateContext = <String, dynamic>{
+ final Map<String, dynamic> templateContext = <String, dynamic>{
'projectName': projectName,
'androidIdentifier': _createAndroidIdentifier(projectName),
'iosIdentifier': _createUTIIdentifier(projectName),
@@ -161,7 +161,7 @@
templateContext['withDriverTest'] = renderDriverTest;
- Template createTemplate = new Template.fromName('create');
+ final Template createTemplate = new Template.fromName('create');
fileCount += createTemplate.render(
fs.directory(dirPath),
templateContext, overwriteExisting: false,
@@ -169,7 +169,7 @@
);
if (renderDriverTest) {
- Template driverTemplate = new Template.fromName('driver');
+ final Template driverTemplate = new Template.fromName('driver');
fileCount += driverTemplate.render(fs.directory(fs.path.join(dirPath, 'test_driver')),
templateContext, overwriteExisting: false);
}
@@ -192,7 +192,7 @@
String _createUTIIdentifier(String name) {
// Create a UTI (https://en.wikipedia.org/wiki/Uniform_Type_Identifier) from a base name
- RegExp disallowed = new RegExp(r"[^a-zA-Z0-9\-\.\u0080-\uffff]+");
+ final RegExp disallowed = new RegExp(r"[^a-zA-Z0-9\-\.\u0080-\uffff]+");
name = camelCase(name).replaceAll(disallowed, '');
name = name.isEmpty ? 'untitled' : name;
return 'com.yourcompany.$name';
@@ -236,7 +236,7 @@
"Target directory '$dirPath' is within the Flutter SDK at '$flutterRoot'.";
}
- FileSystemEntityType type = fs.typeSync(dirPath);
+ final FileSystemEntityType type = fs.typeSync(dirPath);
if (type != FileSystemEntityType.NOT_FOUND) {
switch(type) {
@@ -253,7 +253,7 @@
}
String _relativePath({ String from, String to }) {
- String result = fs.path.relative(to, from: from);
+ final String result = fs.path.relative(to, from: from);
// `fs.path.relative()` doesn't always return a correct result: dart-lang/path#12.
if (fs.isDirectorySync(fs.path.join(from, result)))
return result;
diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart
index 5309be1..ff72a23 100644
--- a/packages/flutter_tools/lib/src/commands/daemon.dart
+++ b/packages/flutter_tools/lib/src/commands/daemon.dart
@@ -48,18 +48,18 @@
Future<Null> runCommand() {
printStatus('Starting device daemon...');
- AppContext appContext = new AppContext();
- NotifyingLogger notifyingLogger = new NotifyingLogger();
+ final AppContext appContext = new AppContext();
+ final NotifyingLogger notifyingLogger = new NotifyingLogger();
appContext.setVariable(Logger, notifyingLogger);
Cache.releaseLockEarly();
return appContext.runInZone(() async {
- Daemon daemon = new Daemon(
+ final Daemon daemon = new Daemon(
stdinCommandStream, stdoutCommandResponse,
daemonCommand: this, notifyingLogger: notifyingLogger);
- int code = await daemon.onExit;
+ final int code = await daemon.onExit;
if (code != 0)
throwToolExit('Daemon exited with non-zero exit code: $code', exitCode: code);
}, onError: _handleError);
@@ -118,7 +118,7 @@
// {id, method, params}
// [id] is an opaque type to us.
- dynamic id = request['id'];
+ final dynamic id = request['id'];
if (id == null) {
stderr.writeln('no id for request: $request');
@@ -126,12 +126,12 @@
}
try {
- String method = request['method'];
+ final String method = request['method'];
if (!method.contains('.'))
throw 'method not understood: $method';
- String prefix = method.substring(0, method.indexOf('.'));
- String name = method.substring(method.indexOf('.') + 1);
+ final String prefix = method.substring(0, method.indexOf('.'));
+ final String name = method.substring(method.indexOf('.') + 1);
if (_domainMap[prefix] == null)
throw 'no domain for method: $method';
@@ -183,7 +183,7 @@
}
void sendEvent(String name, [dynamic args]) {
- Map<String, dynamic> map = <String, dynamic>{ 'event': name };
+ final Map<String, dynamic> map = <String, dynamic>{ 'event': name };
if (args != null)
map['params'] = _toJsonable(args);
_send(map);
@@ -194,7 +194,7 @@
String _getStringArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
- dynamic val = args[name];
+ final dynamic val = args[name];
if (val != null && val is! String)
throw "$name is not a String";
return val;
@@ -203,7 +203,7 @@
bool _getBoolArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
- dynamic val = args[name];
+ final dynamic val = args[name];
if (val != null && val is! bool)
throw "$name is not a bool";
return val;
@@ -212,7 +212,7 @@
int _getIntArg(Map<String, dynamic> args, String name, { bool required: false }) {
if (required && !args.containsKey(name))
throw "$name is required";
- dynamic val = args[name];
+ final dynamic val = args[name];
if (val != null && val is! int)
throw "$name is not an int";
return val;
@@ -293,24 +293,24 @@
List<AppInstance> _apps = <AppInstance>[];
Future<Map<String, dynamic>> start(Map<String, dynamic> args) async {
- String deviceId = _getStringArg(args, 'deviceId', required: true);
- String projectDirectory = _getStringArg(args, 'projectDirectory', required: true);
- bool startPaused = _getBoolArg(args, 'startPaused') ?? false;
- String route = _getStringArg(args, 'route');
- String mode = _getStringArg(args, 'mode');
- String target = _getStringArg(args, 'target');
- bool enableHotReload = _getBoolArg(args, 'hot') ?? kHotReloadDefault;
+ final String deviceId = _getStringArg(args, 'deviceId', required: true);
+ final String projectDirectory = _getStringArg(args, 'projectDirectory', required: true);
+ final bool startPaused = _getBoolArg(args, 'startPaused') ?? false;
+ final String route = _getStringArg(args, 'route');
+ final String mode = _getStringArg(args, 'mode');
+ final String target = _getStringArg(args, 'target');
+ final bool enableHotReload = _getBoolArg(args, 'hot') ?? kHotReloadDefault;
- Device device = daemon.deviceDomain._getOrLocateDevice(deviceId);
+ final Device device = daemon.deviceDomain._getOrLocateDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
if (!fs.isDirectorySync(projectDirectory))
throw "'$projectDirectory' does not exist";
- BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug;
+ final BuildMode buildMode = getBuildModeForName(mode) ?? BuildMode.debug;
- AppInstance app = await startApp(
+ final AppInstance app = await startApp(
device, projectDirectory, target, route,
buildMode, startPaused, enableHotReload);
@@ -348,7 +348,7 @@
throw '${toTitleCase(getModeName(buildMode))} mode is not supported for emulators.';
// We change the current working directory for the duration of the `start` command.
- Directory cwd = fs.currentDirectory;
+ final Directory cwd = fs.currentDirectory;
fs.currentDirectory = fs.directory(projectDirectory);
ResidentRunner runner;
@@ -374,7 +374,7 @@
);
}
- AppInstance app = new AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout);
+ final AppInstance app = new AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout);
_apps.add(app);
_sendAppEvent(app, 'start', <String, dynamic>{
'deviceId': device.id,
@@ -387,7 +387,7 @@
if (options.debuggingEnabled) {
connectionInfoCompleter = new Completer<DebugConnectionInfo>();
connectionInfoCompleter.future.then<Null>((DebugConnectionInfo info) {
- Map<String, dynamic> params = <String, dynamic>{
+ final Map<String, dynamic> params = <String, dynamic>{
'port': info.httpUri.port,
'wsUri': info.wsUri.toString(),
};
@@ -396,7 +396,7 @@
_sendAppEvent(app, 'debugPort', params);
});
}
- Completer<Null> appStartedCompleter = new Completer<Null>();
+ final Completer<Null> appStartedCompleter = new Completer<Null>();
appStartedCompleter.future.then<Null>((Null value) {
_sendAppEvent(app, 'started');
});
@@ -424,11 +424,11 @@
enableHotReload && device.supportsHotMode;
Future<OperationResult> restart(Map<String, dynamic> args) async {
- String appId = _getStringArg(args, 'appId', required: true);
- bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
- bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
+ final String appId = _getStringArg(args, 'appId', required: true);
+ final bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
+ final bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
- AppInstance app = _getApp(appId);
+ final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
@@ -438,16 +438,16 @@
}
Future<OperationResult> callServiceExtension(Map<String, dynamic> args) async {
- String appId = _getStringArg(args, 'appId', required: true);
- String methodName = _getStringArg(args, 'methodName');
- Map<String, String> params = args['params'] ?? <String, String>{};
+ final String appId = _getStringArg(args, 'appId', required: true);
+ final String methodName = _getStringArg(args, 'methodName');
+ final Map<String, String> params = args['params'] ?? <String, String>{};
- AppInstance app = _getApp(appId);
+ final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
- Isolate isolate = app.runner.currentView.uiIsolate;
- Map<String, dynamic> result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params);
+ final Isolate isolate = app.runner.currentView.uiIsolate;
+ final Map<String, dynamic> result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params);
if (result == null)
return new OperationResult(1, 'method not available: $methodName');
@@ -458,9 +458,9 @@
}
Future<bool> stop(Map<String, dynamic> args) async {
- String appId = _getStringArg(args, 'appId', required: true);
+ final String appId = _getStringArg(args, 'appId', required: true);
- AppInstance app = _getApp(appId);
+ final AppInstance app = _getApp(appId);
if (app == null)
throw "app '$appId' not found";
@@ -475,13 +475,13 @@
}
Future<List<Map<String, dynamic>>> discover(Map<String, dynamic> args) async {
- String deviceId = _getStringArg(args, 'deviceId', required: true);
+ final String deviceId = _getStringArg(args, 'deviceId', required: true);
- Device device = daemon.deviceDomain._getDevice(deviceId);
+ final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
- List<DiscoveredApp> apps = await device.discoverApps();
+ final List<DiscoveredApp> apps = await device.discoverApps();
return apps.map((DiscoveredApp app) {
return <String, dynamic>{
'id': app.id,
@@ -496,7 +496,7 @@
}
void _sendAppEvent(AppInstance app, String name, [Map<String, dynamic> args]) {
- Map<String, dynamic> eventArgs = <String, dynamic> { 'appId': app.id };
+ final Map<String, dynamic> eventArgs = <String, dynamic> { 'appId': app.id };
if (args != null)
eventArgs.addAll(args);
sendEvent('app.$name', eventArgs);
@@ -540,7 +540,7 @@
List<PollingDeviceDiscovery> _discoverers = <PollingDeviceDiscovery>[];
Future<List<Device>> getDevices([Map<String, dynamic> args]) {
- List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
+ final List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
return discoverer.devices;
}).toList();
return new Future<List<Device>>.value(devices);
@@ -562,11 +562,11 @@
/// Forward a host port to a device port.
Future<Map<String, dynamic>> forward(Map<String, dynamic> args) async {
- String deviceId = _getStringArg(args, 'deviceId', required: true);
- int devicePort = _getIntArg(args, 'devicePort', required: true);
+ final String deviceId = _getStringArg(args, 'deviceId', required: true);
+ final int devicePort = _getIntArg(args, 'devicePort', required: true);
int hostPort = _getIntArg(args, 'hostPort');
- Device device = daemon.deviceDomain._getDevice(deviceId);
+ final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
@@ -577,11 +577,11 @@
/// Removes a forwarded port.
Future<Null> unforward(Map<String, dynamic> args) async {
- String deviceId = _getStringArg(args, 'deviceId', required: true);
- int devicePort = _getIntArg(args, 'devicePort', required: true);
- int hostPort = _getIntArg(args, 'hostPort', required: true);
+ final String deviceId = _getStringArg(args, 'deviceId', required: true);
+ final int devicePort = _getIntArg(args, 'devicePort', required: true);
+ final int hostPort = _getIntArg(args, 'hostPort', required: true);
- Device device = daemon.deviceDomain._getDevice(deviceId);
+ final Device device = daemon.deviceDomain._getDevice(deviceId);
if (device == null)
throw "device '$deviceId' not found";
@@ -596,7 +596,7 @@
/// Return the device matching the deviceId field in the args.
Device _getDevice(String deviceId) {
- List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
+ final List<Device> devices = _discoverers.expand((PollingDeviceDiscovery discoverer) {
return discoverer.devices;
}).toList();
return devices.firstWhere((Device device) => device.id == deviceId, orElse: () => null);
@@ -605,13 +605,13 @@
/// Return a known matching device, or scan for devices if no known match is found.
Device _getOrLocateDevice(String deviceId) {
// Look for an already known device.
- Device device = _getDevice(deviceId);
+ final Device device = _getDevice(deviceId);
if (device != null)
return device;
// Scan the different device providers for a match.
for (PollingDeviceDiscovery discoverer in _discoverers) {
- List<Device> devices = discoverer.pollingGetDevices();
+ final List<Device> devices = discoverer.pollingGetDevices();
for (Device device in devices)
if (device.id == deviceId)
return device;
@@ -727,7 +727,7 @@
if (_logger == null)
_logger = new _AppRunLogger(domain, this, logToStdout: logToStdout);
- AppContext appContext = new AppContext();
+ final AppContext appContext = new AppContext();
appContext.setVariable(Logger, _logger);
return appContext.runInZone(method);
}
@@ -787,7 +787,7 @@
if (_status != null)
return new Status();
- int id = _nextProgressId++;
+ final int id = _nextProgressId++;
_sendProgressEvent(<String, dynamic>{
'id': id.toString(),
diff --git a/packages/flutter_tools/lib/src/commands/devices.dart b/packages/flutter_tools/lib/src/commands/devices.dart
index 4547ade..2982216 100644
--- a/packages/flutter_tools/lib/src/commands/devices.dart
+++ b/packages/flutter_tools/lib/src/commands/devices.dart
@@ -27,7 +27,7 @@
exitCode: 1);
}
- List<Device> devices = await deviceManager.getAllConnectedDevices();
+ final List<Device> devices = await deviceManager.getAllConnectedDevices();
if (devices.isEmpty) {
printStatus(
diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart
index cfc1cb3..0039474 100644
--- a/packages/flutter_tools/lib/src/commands/drive.dart
+++ b/packages/flutter_tools/lib/src/commands/drive.dart
@@ -85,7 +85,7 @@
@override
Future<Null> runCommand() async {
- String testFile = _getTestFile();
+ final String testFile = _getTestFile();
if (testFile == null)
throwToolExit(null);
@@ -110,7 +110,7 @@
);
}
- LaunchResult result = await appStarter(this);
+ final LaunchResult result = await appStarter(this);
if (result == null)
throwToolExit('Application failed to start. Will not run test. Quitting.', exitCode: 1);
observatoryUri = result.observatoryUri.toString();
@@ -141,7 +141,7 @@
String appFile = fs.path.normalize(targetFile);
// This command extends `flutter start` and therefore CWD == package dir
- String packageDir = fs.currentDirectory.path;
+ final String packageDir = fs.currentDirectory.path;
// Make appFile path relative to package directory because we are looking
// for the corresponding test file relative to it.
@@ -156,7 +156,7 @@
appFile = fs.path.relative(appFile, from: packageDir);
}
- List<String> parts = fs.path.split(appFile);
+ final List<String> parts = fs.path.split(appFile);
if (parts.length < 2) {
printError(
@@ -169,7 +169,7 @@
// Look for the test file inside `test_driver/` matching the sub-path, e.g.
// if the application is `lib/foo/bar.dart`, the test file is expected to
// be `test_driver/foo/bar_test.dart`.
- String pathWithNoExtension = fs.path.withoutExtension(fs.path.joinAll(
+ final String pathWithNoExtension = fs.path.withoutExtension(fs.path.joinAll(
<String>[packageDir, 'test_driver']..addAll(parts.skip(1))));
return '${pathWithNoExtension}_test${fs.path.extension(appFile)}';
}
@@ -183,7 +183,7 @@
}
Future<Device> findTargetDevice() async {
- List<Device> devices = await deviceManager.getDevices();
+ final List<Device> devices = await deviceManager.getDevices();
if (deviceManager.hasSpecifiedDeviceId) {
if (devices.isEmpty) {
@@ -203,7 +203,7 @@
// On Mac we look for the iOS Simulator. If available, we use that. Then
// we look for an Android device. If there's one, we use that. Otherwise,
// we launch a new iOS Simulator.
- Device reusableDevice = devices.firstWhere(
+ final Device reusableDevice = devices.firstWhere(
(Device d) => d.isLocalEmulator,
orElse: () {
return devices.firstWhere((Device d) => d is AndroidDevice,
@@ -218,7 +218,7 @@
// No running emulator found. Attempt to start one.
printStatus('Starting iOS Simulator, because did not find existing connected devices.');
- bool started = await SimControl.instance.boot();
+ final bool started = await SimControl.instance.boot();
if (started) {
return IOSSimulatorUtils.instance.getAttachedDevices().first;
} else {
@@ -251,7 +251,7 @@
}
Future<LaunchResult> _startApp(DriveCommand command) async {
- String mainPath = findMainDartFile(command.targetFile);
+ final String mainPath = findMainDartFile(command.targetFile);
if (await fs.type(mainPath) != FileSystemEntityType.FILE) {
printError('Tried to run $mainPath, but that file does not exist.');
return null;
@@ -261,13 +261,13 @@
await appStopper(command);
printTrace('Installing application package.');
- ApplicationPackage package = command.applicationPackages
+ final ApplicationPackage package = command.applicationPackages
.getPackageForPlatform(command.device.platform);
if (command.device.isAppInstalled(package))
command.device.uninstallApp(package);
command.device.installApp(package);
- Map<String, dynamic> platformArgs = <String, dynamic>{};
+ final Map<String, dynamic> platformArgs = <String, dynamic>{};
if (command.traceStartup)
platformArgs['trace-startup'] = command.traceStartup;
@@ -280,7 +280,7 @@
.logLines
.listen(printStatus);
- LaunchResult result = await command.device.startApp(
+ final LaunchResult result = await command.device.startApp(
package,
command.getBuildMode(),
mainPath: mainPath,
@@ -313,11 +313,11 @@
printTrace('Running driver tests.');
PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(PackageMap.globalPackagesPath));
- List<String> args = testArgs.toList()
+ final List<String> args = testArgs.toList()
..add('--packages=${PackageMap.globalPackagesPath}')
..add('-rexpanded');
- String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart');
- int result = await runCommandAndStreamOutput(
+ final String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart');
+ final int result = await runCommandAndStreamOutput(
<String>[dartVmPath]..addAll(args),
environment: <String, String>{ 'VM_SERVICE_URL': observatoryUri }
);
@@ -335,8 +335,8 @@
Future<bool> _stopApp(DriveCommand command) async {
printTrace('Stopping application.');
- ApplicationPackage package = command.applicationPackages.getPackageForPlatform(command.device.platform);
- bool stopped = await command.device.stopApp(package);
+ final ApplicationPackage package = command.applicationPackages.getPackageForPlatform(command.device.platform);
+ final bool stopped = await command.device.stopApp(package);
await command._deviceLogSubscription?.cancel();
return stopped;
}
diff --git a/packages/flutter_tools/lib/src/commands/format.dart b/packages/flutter_tools/lib/src/commands/format.dart
index 45d8c04..65bd408 100644
--- a/packages/flutter_tools/lib/src/commands/format.dart
+++ b/packages/flutter_tools/lib/src/commands/format.dart
@@ -36,9 +36,9 @@
);
}
- String dartfmt = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartfmt');
- List<String> cmd = <String>[dartfmt, '-w']..addAll(argResults.rest);
- int result = await runCommandAndStreamOutput(cmd);
+ final String dartfmt = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartfmt');
+ final List<String> cmd = <String>[dartfmt, '-w']..addAll(argResults.rest);
+ final int result = await runCommandAndStreamOutput(cmd);
if (result != 0)
throwToolExit('Formatting failed: $result', exitCode: result);
}
diff --git a/packages/flutter_tools/lib/src/commands/install.dart b/packages/flutter_tools/lib/src/commands/install.dart
index fc1de89..acfac12 100644
--- a/packages/flutter_tools/lib/src/commands/install.dart
+++ b/packages/flutter_tools/lib/src/commands/install.dart
@@ -31,7 +31,7 @@
@override
Future<Null> runCommand() async {
- ApplicationPackage package = applicationPackages.getPackageForPlatform(device.platform);
+ final ApplicationPackage package = applicationPackages.getPackageForPlatform(device.platform);
Cache.releaseLockEarly();
diff --git a/packages/flutter_tools/lib/src/commands/logs.dart b/packages/flutter_tools/lib/src/commands/logs.dart
index e7d0df5..891b704 100644
--- a/packages/flutter_tools/lib/src/commands/logs.dart
+++ b/packages/flutter_tools/lib/src/commands/logs.dart
@@ -42,16 +42,16 @@
if (argResults['clear'])
device.clearLogs();
- DeviceLogReader logReader = device.getLogReader();
+ final DeviceLogReader logReader = device.getLogReader();
Cache.releaseLockEarly();
printStatus('Showing $logReader logs:');
- Completer<int> exitCompleter = new Completer<int>();
+ final Completer<int> exitCompleter = new Completer<int>();
// Start reading.
- StreamSubscription<String> subscription = logReader.logLines.listen(
+ final StreamSubscription<String> subscription = logReader.logLines.listen(
printStatus,
onDone: () {
exitCompleter.complete(0);
@@ -75,7 +75,7 @@
}
// Wait for the log reader to be finished.
- int result = await exitCompleter.future;
+ final int result = await exitCompleter.future;
subscription.cancel();
if (result != 0)
throwToolExit('Error listening to $logReader logs.');
diff --git a/packages/flutter_tools/lib/src/commands/packages.dart b/packages/flutter_tools/lib/src/commands/packages.dart
index eace49a..5e2aabc 100644
--- a/packages/flutter_tools/lib/src/commands/packages.dart
+++ b/packages/flutter_tools/lib/src/commands/packages.dart
@@ -56,7 +56,7 @@
if (argResults.rest.length > 1)
throwToolExit('Too many arguments.\n$usage');
- String target = findProjectRoot(
+ final String target = findProjectRoot(
argResults.rest.length == 1 ? argResults.rest[0] : null);
if (target == null)
throwToolExit(
diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart
index d34b328..60b0677 100644
--- a/packages/flutter_tools/lib/src/commands/run.dart
+++ b/packages/flutter_tools/lib/src/commands/run.dart
@@ -148,7 +148,7 @@
@override
String get usagePath {
- String command = shouldUseHotMode() ? 'hotrun' : name;
+ final String command = shouldUseHotMode() ? 'hotrun' : name;
if (device == null)
return command;
@@ -180,7 +180,7 @@
}
bool shouldUseHotMode() {
- bool hotArg = argResults['hot'] ?? false;
+ final bool hotArg = argResults['hot'] ?? false;
final bool shouldUseHotMode = hotArg;
return (getBuildMode() == BuildMode.debug) && shouldUseHotMode;
}
@@ -209,7 +209,7 @@
final bool hotMode = shouldUseHotMode();
if (argResults['machine']) {
- Daemon daemon = new Daemon(stdinCommandStream, stdoutCommandResponse,
+ final Daemon daemon = new Daemon(stdinCommandStream, stdoutCommandResponse,
notifyingLogger: new NotifyingLogger(), logToStdout: true);
AppInstance app;
try {
@@ -223,7 +223,7 @@
} catch (error) {
throwToolExit(error.toString());
}
- int result = await app.runner.waitForAppToFinish();
+ final int result = await app.runner.waitForAppToFinish();
if (result != 0)
throwToolExit(null, exitCode: result);
return null;
@@ -250,7 +250,7 @@
throwToolExit('Hot mode is not supported by this device. Run with --no-hot.');
}
- String pidFile = argResults['pid-file'];
+ final String pidFile = argResults['pid-file'];
if (pidFile != null) {
// Write our pid to the file.
fs.file(pidFile).writeAsStringSync(pid.toString());
@@ -281,7 +281,7 @@
);
}
- int result = await runner.run(
+ final int result = await runner.run(
route: route,
shouldBuild: !runningWithPrebuiltApplication && argResults['build'],
);
diff --git a/packages/flutter_tools/lib/src/commands/screenshot.dart b/packages/flutter_tools/lib/src/commands/screenshot.dart
index 9dd14b8..b24d5eb 100644
--- a/packages/flutter_tools/lib/src/commands/screenshot.dart
+++ b/packages/flutter_tools/lib/src/commands/screenshot.dart
@@ -92,7 +92,7 @@
}
Future<Null> runSkia(File outputFile) async {
- Uri skpUri = new Uri(scheme: 'http', host: '127.0.0.1',
+ final Uri skpUri = new Uri(scheme: 'http', host: '127.0.0.1',
port: int.parse(argResults[_kSkia]),
path: '/skp');
@@ -108,28 +108,28 @@
throwToolExit('Skia screenshot failed: $skpUri\n$e\n\n$errorHelpText');
}
if (skpResponse.statusCode != HttpStatus.OK) {
- String error = await skpResponse.stream.toStringStream().join();
+ final String error = await skpResponse.stream.toStringStream().join();
throwToolExit('Error: $error\n\n$errorHelpText');
}
if (argResults[_kSkiaServe] != null) {
- Uri skiaserveUri = Uri.parse(argResults[_kSkiaServe]);
- Uri postUri = new Uri.http(skiaserveUri.authority, '/new');
- http.MultipartRequest postRequest = new http.MultipartRequest('POST', postUri);
+ final Uri skiaserveUri = Uri.parse(argResults[_kSkiaServe]);
+ final Uri postUri = new Uri.http(skiaserveUri.authority, '/new');
+ final http.MultipartRequest postRequest = new http.MultipartRequest('POST', postUri);
postRequest.files.add(new http.MultipartFile(
'file', skpResponse.stream, skpResponse.contentLength));
- http.StreamedResponse postResponse = await postRequest.send();
+ final http.StreamedResponse postResponse = await postRequest.send();
if (postResponse.statusCode != HttpStatus.OK)
throwToolExit('Failed to post Skia picture to skiaserve.\n\n$errorHelpText');
} else {
outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'skp');
- IOSink sink = outputFile.openWrite();
+ final IOSink sink = outputFile.openWrite();
await sink.addStream(skpResponse.stream);
await sink.close();
await showOutputFileInfo(outputFile);
if (await outputFile.length() < 1000) {
- String content = await outputFile.readAsString();
+ final String content = await outputFile.readAsString();
if (content.startsWith('{"jsonrpc":"2.0", "error"'))
throwToolExit('\nIt appears the output file contains an error message, not valid skia output.\n\n$errorHelpText');
}
@@ -137,7 +137,7 @@
}
Future<Null> showOutputFileInfo(File outputFile) async {
- int sizeKB = (await outputFile.length()) ~/ 1024;
+ final int sizeKB = (await outputFile.length()) ~/ 1024;
printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).');
}
}
diff --git a/packages/flutter_tools/lib/src/commands/stop.dart b/packages/flutter_tools/lib/src/commands/stop.dart
index 4a01ad2..6d31775 100644
--- a/packages/flutter_tools/lib/src/commands/stop.dart
+++ b/packages/flutter_tools/lib/src/commands/stop.dart
@@ -31,9 +31,9 @@
@override
Future<Null> runCommand() async {
- ApplicationPackage app = applicationPackages.getPackageForPlatform(device.platform);
+ final ApplicationPackage app = applicationPackages.getPackageForPlatform(device.platform);
if (app == null) {
- String platformName = getNameForTargetPlatform(device.platform);
+ final String platformName = getNameForTargetPlatform(device.platform);
throwToolExit('No Flutter application for $platformName found in the current directory.');
}
printStatus('Stopping apps on ${device.name}.');
diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart
index 6d3f2d8..1266a3a 100644
--- a/packages/flutter_tools/lib/src/commands/test.dart
+++ b/packages/flutter_tools/lib/src/commands/test.dart
@@ -78,7 +78,7 @@
}
Future<int> _runTests(List<String> testArgs, Directory testDirectory) async {
- Directory currentDirectory = fs.currentDirectory;
+ final Directory currentDirectory = fs.currentDirectory;
try {
if (testDirectory != null) {
printTrace('switching to directory $testDirectory to run tests');
@@ -96,8 +96,8 @@
}
Future<bool> _collectCoverageData(CoverageCollector collector, { bool mergeCoverageData: false }) async {
- Status status = logger.startProgress('Collecting coverage information...');
- String coverageData = await collector.finalizeCoverage(
+ final Status status = logger.startProgress('Collecting coverage information...');
+ final String coverageData = await collector.finalizeCoverage(
timeout: const Duration(seconds: 30),
);
status.stop();
@@ -105,13 +105,13 @@
if (coverageData == null)
return false;
- String coveragePath = argResults['coverage-path'];
- File coverageFile = fs.file(coveragePath)
+ final String coveragePath = argResults['coverage-path'];
+ final File coverageFile = fs.file(coveragePath)
..createSync(recursive: true)
..writeAsStringSync(coverageData, flush: true);
printTrace('wrote coverage data to $coveragePath (size=${coverageData.length})');
- String baseCoverageData = 'coverage/lcov.base.info';
+ final String baseCoverageData = 'coverage/lcov.base.info';
if (mergeCoverageData) {
if (!platform.isLinux) {
printError(
@@ -136,10 +136,10 @@
return false;
}
- Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
+ final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
try {
- File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
- ProcessResult result = processManager.runSync(<String>[
+ final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
+ final ProcessResult result = processManager.runSync(<String>[
'lcov',
'--add-tracefile', baseCoverageData,
'--add-tracefile', sourceFile.path,
@@ -163,7 +163,7 @@
);
}
- List<String> testArgs = <String>[];
+ final List<String> testArgs = <String>[];
commandValidator();
@@ -208,7 +208,7 @@
Cache.releaseLockEarly();
- int result = await _runTests(testArgs, testDir);
+ final int result = await _runTests(testArgs, testDir);
if (collector != null) {
if (!await _collectCoverageData(collector, mergeCoverageData: argResults['merge-coverage']))
diff --git a/packages/flutter_tools/lib/src/commands/trace.dart b/packages/flutter_tools/lib/src/commands/trace.dart
index 474d373..e9f1a20 100644
--- a/packages/flutter_tools/lib/src/commands/trace.dart
+++ b/packages/flutter_tools/lib/src/commands/trace.dart
@@ -51,11 +51,11 @@
@override
Future<Null> runCommand() async {
- int observatoryPort = int.parse(argResults['debug-port']);
+ final int observatoryPort = int.parse(argResults['debug-port']);
// TODO(danrubel): this will break if we move to the new observatory URL
// See https://github.com/flutter/flutter/issues/7038
- Uri observatoryUri = Uri.parse('http://127.0.0.1:$observatoryPort');
+ final Uri observatoryUri = Uri.parse('http://127.0.0.1:$observatoryPort');
Tracing tracing;
@@ -84,7 +84,7 @@
}
Future<Null> _stopTracing(Tracing tracing) async {
- Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline();
+ final Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline();
File localFile;
if (argResults['out'] != null) {
@@ -103,7 +103,7 @@
Tracing(this.vmService);
static Tracing connect(Uri uri) {
- VMService observatory = VMService.connect(uri);
+ final VMService observatory = VMService.connect(uri);
return new Tracing(observatory);
}
@@ -125,10 +125,10 @@
await vmService.vm.setVMTimelineFlags(<String>[]);
timeline = await vmService.vm.getVMTimeline();
} else {
- Completer<Null> whenFirstFrameRendered = new Completer<Null>();
+ final Completer<Null> whenFirstFrameRendered = new Completer<Null>();
vmService.onTimelineEvent.listen((ServiceEvent timelineEvent) {
- List<Map<String, dynamic>> events = timelineEvent.timelineEvents;
+ final List<Map<String, dynamic>> events = timelineEvent.timelineEvents;
for (Map<String, dynamic> event in events) {
if (event['name'] == kFirstUsefulFrameEventName)
whenFirstFrameRendered.complete();
@@ -159,8 +159,8 @@
/// Download the startup trace information from the given observatory client and
/// store it to build/start_up_info.json.
Future<Null> downloadStartupTrace(VMService observatory) async {
- String traceInfoFilePath = fs.path.join(getBuildDirectory(), 'start_up_info.json');
- File traceInfoFile = fs.file(traceInfoFilePath);
+ final String traceInfoFilePath = fs.path.join(getBuildDirectory(), 'start_up_info.json');
+ final File traceInfoFile = fs.file(traceInfoFilePath);
// Delete old startup data, if any.
if (await traceInfoFile.exists())
@@ -170,23 +170,23 @@
if (!(await traceInfoFile.parent.exists()))
await traceInfoFile.parent.create();
- Tracing tracing = new Tracing(observatory);
+ final Tracing tracing = new Tracing(observatory);
- Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline(
+ final Map<String, dynamic> timeline = await tracing.stopTracingAndDownloadTimeline(
waitForFirstFrame: true
);
int extractInstantEventTimestamp(String eventName) {
- List<Map<String, dynamic>> events = timeline['traceEvents'];
- Map<String, dynamic> event = events.firstWhere(
+ final List<Map<String, dynamic>> events = timeline['traceEvents'];
+ final Map<String, dynamic> event = events.firstWhere(
(Map<String, dynamic> event) => event['name'] == eventName, orElse: () => null
);
return event == null ? null : event['ts'];
}
- int engineEnterTimestampMicros = extractInstantEventTimestamp(kFlutterEngineMainEnterEventName);
- int frameworkInitTimestampMicros = extractInstantEventTimestamp(kFrameworkInitEventName);
- int firstFrameTimestampMicros = extractInstantEventTimestamp(kFirstUsefulFrameEventName);
+ final int engineEnterTimestampMicros = extractInstantEventTimestamp(kFlutterEngineMainEnterEventName);
+ final int frameworkInitTimestampMicros = extractInstantEventTimestamp(kFrameworkInitEventName);
+ final int firstFrameTimestampMicros = extractInstantEventTimestamp(kFirstUsefulFrameEventName);
if (engineEnterTimestampMicros == null) {
throw 'Engine start event is missing in the timeline. Cannot compute startup time.';
@@ -196,8 +196,8 @@
throw 'First frame event is missing in the timeline. Cannot compute startup time.';
}
- int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros;
- Map<String, dynamic> traceInfo = <String, dynamic>{
+ final int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros;
+ final Map<String, dynamic> traceInfo = <String, dynamic>{
'engineEnterTimestampMicros': engineEnterTimestampMicros,
'timeToFirstFrameMicros': timeToFirstFrameMicros,
};
diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart
index 2a3783b..b92c4e0 100644
--- a/packages/flutter_tools/lib/src/commands/update_packages.dart
+++ b/packages/flutter_tools/lib/src/commands/update_packages.dart
@@ -31,7 +31,7 @@
final bool hidden;
Future<Null> _downloadCoverageData() async {
- Status status = logger.startProgress("Downloading lcov data for package:flutter...", expectSlowOperation: true);
+ final Status status = logger.startProgress("Downloading lcov data for package:flutter...", expectSlowOperation: true);
final List<int> data = await fetchUrl(Uri.parse('https://storage.googleapis.com/flutter_infra/flutter/coverage/lcov.info'));
final String coverageDir = fs.path.join(Cache.flutterRoot, 'packages/flutter/coverage');
fs.file(fs.path.join(coverageDir, 'lcov.base.info'))
diff --git a/packages/flutter_tools/lib/src/commands/upgrade.dart b/packages/flutter_tools/lib/src/commands/upgrade.dart
index 73f7236..cbdf88c 100644
--- a/packages/flutter_tools/lib/src/commands/upgrade.dart
+++ b/packages/flutter_tools/lib/src/commands/upgrade.dart
@@ -32,7 +32,7 @@
throwToolExit('Unable to upgrade Flutter: no upstream repository configured.');
}
- FlutterVersion version = new FlutterVersion(Cache.flutterRoot);
+ final FlutterVersion version = new FlutterVersion(Cache.flutterRoot);
if (version.channel == 'alpha') {
// The alpha branch is deprecated. Rather than trying to pull the alpha
// branch, we should switch upstream to master.
@@ -68,7 +68,7 @@
printStatus('');
printStatus(FlutterVersion.getVersion(Cache.flutterRoot).toString());
- String projRoot = findProjectRoot();
+ final String projRoot = findProjectRoot();
if (projRoot != null) {
printStatus('');
await pubGet(directory: projRoot, upgrade: true, checkLastModified: false);
diff --git a/packages/flutter_tools/lib/src/crash_reporting.dart b/packages/flutter_tools/lib/src/crash_reporting.dart
index ee214e5..ae61ae5 100644
--- a/packages/flutter_tools/lib/src/crash_reporting.dart
+++ b/packages/flutter_tools/lib/src/crash_reporting.dart
@@ -85,20 +85,20 @@
printStatus('Sending crash report to Google.');
- Uri uri = _baseUri.replace(
+ final Uri uri = _baseUri.replace(
queryParameters: <String, String>{
'product': _kProductId,
'version': flutterVersion,
},
);
- _MultipartRequest req = new _MultipartRequest('POST', uri);
+ final _MultipartRequest req = new _MultipartRequest('POST', uri);
req.fields['product'] = _kProductId;
req.fields['version'] = flutterVersion;
req.fields['type'] = _kDartTypeId;
req.fields['error_runtime_type'] = '${error.runtimeType}';
- Chain chain = stackTrace is StackTrace
+ final Chain chain = stackTrace is StackTrace
? new Chain.forTrace(stackTrace)
: new Chain.parse(stackTrace.toString());
@@ -108,10 +108,10 @@
filename: _kStackTraceFilename,
));
- http.StreamedResponse resp = await _client.send(req);
+ final http.StreamedResponse resp = await _client.send(req);
if (resp.statusCode == 200) {
- String reportId = await new http.ByteStream(resp.stream)
+ final String reportId = await new http.ByteStream(resp.stream)
.bytesToString();
printStatus('Crash report sent (report ID: $reportId)');
} else {
@@ -225,11 +225,11 @@
/// that will emit the request body.
@override
http.ByteStream finalize() {
- String boundary = _boundaryString();
+ final String boundary = _boundaryString();
headers['content-type'] = 'multipart/form-data; boundary=$boundary';
super.finalize();
- StreamController<List<int>> controller = new StreamController<List<int>>(sync: true);
+ final StreamController<List<int>> controller = new StreamController<List<int>>(sync: true);
void writeAscii(String string) {
controller.add(UTF8.encode(string));
@@ -369,8 +369,8 @@
/// Returns a randomly-generated multipart boundary string
String _boundaryString() {
- String prefix = "dart-";
- List<int> list = new List<int>.generate(_BOUNDARY_LENGTH - prefix.length,
+ final String prefix = "dart-";
+ final List<int> list = new List<int>.generate(_BOUNDARY_LENGTH - prefix.length,
(int index) =>
_BOUNDARY_CHARACTERS[_random.nextInt(_BOUNDARY_CHARACTERS.length)],
growable: false);
@@ -382,7 +382,7 @@
/// [stream] is done. Unlike [store], [sink] remains open after [stream] is
/// done.
Future<Null> writeStreamToSink<O, I extends O>(Stream<I> stream, EventSink<O> sink) {
- Completer<Null> completer = new Completer<Null>();
+ final Completer<Null> completer = new Completer<Null>();
stream.listen(sink.add,
onError: sink.addError,
onDone: () => completer.complete());
diff --git a/packages/flutter_tools/lib/src/dart/analysis.dart b/packages/flutter_tools/lib/src/dart/analysis.dart
index a7430a7..744d8b9 100644
--- a/packages/flutter_tools/lib/src/dart/analysis.dart
+++ b/packages/flutter_tools/lib/src/dart/analysis.dart
@@ -50,8 +50,8 @@
}
List<AnalysisErrorDescription> analyze(Iterable<File> files) {
- List<AnalysisErrorInfo> infos = _analyze(files);
- List<AnalysisErrorDescription> errors = <AnalysisErrorDescription>[];
+ final List<AnalysisErrorInfo> infos = _analyze(files);
+ final List<AnalysisErrorDescription> errors = <AnalysisErrorDescription>[];
for (AnalysisErrorInfo info in infos) {
for (AnalysisError error in info.errors) {
if (!_isFiltered(error))
@@ -65,17 +65,17 @@
context = AnalysisEngine.instance.createAnalysisContext();
_processAnalysisOptions();
context.analysisOptions = options;
- PackageInfo packageInfo = new PackageInfo(options.packageMap);
- List<UriResolver> resolvers = _getResolvers(context, packageInfo.asMap());
+ final PackageInfo packageInfo = new PackageInfo(options.packageMap);
+ final List<UriResolver> resolvers = _getResolvers(context, packageInfo.asMap());
context.sourceFactory =
new SourceFactory(resolvers, packageInfo.asPackages());
- List<Source> sources = <Source>[];
- ChangeSet changeSet = new ChangeSet();
+ final List<Source> sources = <Source>[];
+ final ChangeSet changeSet = new ChangeSet();
for (File file in files) {
- JavaFile sourceFile = new JavaFile(fs.path.normalize(file.absolute.path));
+ final JavaFile sourceFile = new JavaFile(fs.path.normalize(file.absolute.path));
Source source = new FileBasedSource(sourceFile, sourceFile.toURI());
- Uri uri = context.sourceFactory.restoreUri(source);
+ final Uri uri = context.sourceFactory.restoreUri(source);
if (uri != null) {
source = new FileBasedSource(sourceFile, uri);
}
@@ -84,7 +84,7 @@
}
context.applyChanges(changeSet);
- List<AnalysisErrorInfo> infos = <AnalysisErrorInfo>[];
+ final List<AnalysisErrorInfo> infos = <AnalysisErrorInfo>[];
for (Source source in sources) {
context.computeErrors(source);
infos.add(context.getErrors(source));
@@ -98,13 +98,13 @@
Map<String, List<file_system.Folder>> packageMap) {
// Create our list of resolvers.
- List<UriResolver> resolvers = <UriResolver>[];
+ final List<UriResolver> resolvers = <UriResolver>[];
// Look for an embedder.
- EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
+ final EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
if (locator.embedderYamls.isNotEmpty) {
// Create and configure an embedded SDK.
- EmbedderSdk sdk = new EmbedderSdk(PhysicalResourceProvider.INSTANCE, locator.embedderYamls);
+ final EmbedderSdk sdk = new EmbedderSdk(PhysicalResourceProvider.INSTANCE, locator.embedderYamls);
// Fail fast if no URI mappings are found.
assert(sdk.libraryMap.size() > 0);
sdk.analysisOptions = context.analysisOptions;
@@ -112,7 +112,7 @@
resolvers.add(new DartUriResolver(sdk));
} else {
// Fall back to a standard SDK if no embedder is found.
- FolderBasedDartSdk sdk = new FolderBasedDartSdk(resourceProvider,
+ final FolderBasedDartSdk sdk = new FolderBasedDartSdk(resourceProvider,
PhysicalResourceProvider.INSTANCE.getFolder(sdkDir));
sdk.analysisOptions = context.analysisOptions;
@@ -120,11 +120,11 @@
}
if (options.packageRootPath != null) {
- ContextBuilderOptions builderOptions = new ContextBuilderOptions();
+ final ContextBuilderOptions builderOptions = new ContextBuilderOptions();
builderOptions.defaultPackagesDirectoryPath = options.packageRootPath;
- ContextBuilder builder = new ContextBuilder(resourceProvider, null, null,
+ final ContextBuilder builder = new ContextBuilder(resourceProvider, null, null,
options: builderOptions);
- PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider,
+ final PackageMapUriResolver packageUriResolver = new PackageMapUriResolver(resourceProvider,
builder.convertPackagesToMap(builder.createPackageMap('')));
resolvers.add(packageUriResolver);
@@ -135,17 +135,17 @@
}
bool _isFiltered(AnalysisError error) {
- ErrorProcessor processor = ErrorProcessor.getProcessor(context.analysisOptions, error);
+ final ErrorProcessor processor = ErrorProcessor.getProcessor(context.analysisOptions, error);
// Filtered errors are processed to a severity of `null`.
return processor != null && processor.severity == null;
}
void _processAnalysisOptions() {
- String optionsPath = options.analysisOptionsFile;
+ final String optionsPath = options.analysisOptionsFile;
if (optionsPath != null) {
- file_system.File file =
+ final file_system.File file =
PhysicalResourceProvider.INSTANCE.getFile(optionsPath);
- Map<Object, Object> optionMap =
+ final Map<Object, Object> optionMap =
analysisOptionsProvider.getOptionsFromFile(file);
if (optionMap != null)
applyToAnalysisOptions(options, optionMap);
@@ -153,9 +153,9 @@
}
void _processPlugins() {
- List<Plugin> plugins = <Plugin>[];
+ final List<Plugin> plugins = <Plugin>[];
plugins.addAll(AnalysisEngine.instance.requiredPlugins);
- ExtensionManager manager = new ExtensionManager();
+ final ExtensionManager manager = new ExtensionManager();
manager.processPlugins(plugins);
linter.registerLintRules();
}
@@ -181,7 +181,7 @@
ErrorCode get errorCode => error.errorCode;
String get errorType {
- ErrorSeverity severity = errorCode.errorSeverity;
+ final ErrorSeverity severity = errorCode.errorSeverity;
if (severity == ErrorSeverity.INFO) {
if (errorCode.type == ErrorType.HINT || errorCode.type == ErrorType.LINT)
return errorCode.type.displayName;
@@ -231,9 +231,9 @@
class PackageInfo {
PackageInfo(Map<String, String> packageMap) {
- Map<String, Uri> packages = new HashMap<String, Uri>();
+ final Map<String, Uri> packages = new HashMap<String, Uri>();
for (String package in packageMap.keys) {
- String path = packageMap[package];
+ final String path = packageMap[package];
packages[package] = new Uri.directory(path);
_map[package] = <file_system.Folder>[
PhysicalResourceProvider.INSTANCE.getFolder(path)
diff --git a/packages/flutter_tools/lib/src/dart/dependencies.dart b/packages/flutter_tools/lib/src/dart/dependencies.dart
index d390577..167378b 100644
--- a/packages/flutter_tools/lib/src/dart/dependencies.dart
+++ b/packages/flutter_tools/lib/src/dart/dependencies.dart
@@ -35,7 +35,7 @@
mainScriptPath
];
- String output = runSyncAndThrowStdErrOnError(args);
+ final String output = runSyncAndThrowStdErrOnError(args);
return new Set<String>.from(LineSplitter.split(output));
}
@@ -65,8 +65,8 @@
assert(fs.path.isAbsolute(this.projectRootPath));
// TODO(goderbauer): Implement --print-deps in gen_snapshot so we don't have to parse the Makefile
- Directory tempDir = fs.systemTempDirectory.createTempSync('dart_dependency_set_builder_');
- String depfilePath = fs.path.join(tempDir.path, 'snapshot_blob.bin.d');
+ final Directory tempDir = fs.systemTempDirectory.createTempSync('dart_dependency_set_builder_');
+ final String depfilePath = fs.path.join(tempDir.path, 'snapshot_blob.bin.d');
final List<String> args = <String>[
snapshotterPath,
@@ -84,14 +84,14 @@
String output = fs.file(depfilePath).readAsStringSync();
tempDir.deleteSync(recursive: true);
- int splitIndex = output.indexOf(':');
+ final int splitIndex = output.indexOf(':');
if (splitIndex == -1)
throw new Exception('Unexpected output $output');
output = output.substring(splitIndex + 1);
// Note: next line means we cannot process anything with spaces in the path
// because Makefiles don't support spaces in paths :(
- List<String> depsList = output.trim().split(' ');
+ final List<String> depsList = output.trim().split(' ');
return new Set<String>.from(depsList);
}
}
diff --git a/packages/flutter_tools/lib/src/dart/package_map.dart b/packages/flutter_tools/lib/src/dart/package_map.dart
index e2b7ab0..0367bf8 100644
--- a/packages/flutter_tools/lib/src/dart/package_map.dart
+++ b/packages/flutter_tools/lib/src/dart/package_map.dart
@@ -9,7 +9,7 @@
const String kPackagesFileName = '.packages';
Map<String, Uri> _parse(String packagesPath) {
- List<int> source = fs.file(packagesPath).readAsBytesSync();
+ final List<int> source = fs.file(packagesPath).readAsBytesSync();
return packages_file.parse(source, new Uri.file(packagesPath));
}
@@ -42,10 +42,10 @@
/// Returns the path to [packageUri].
String pathForPackage(Uri packageUri) {
assert(packageUri.scheme == 'package');
- List<String> pathSegments = packageUri.pathSegments.toList();
- String packageName = pathSegments.removeAt(0);
- Uri packageBase = map[packageName];
- String packageRelativePath = fs.path.joinAll(pathSegments);
+ final List<String> pathSegments = packageUri.pathSegments.toList();
+ final String packageName = pathSegments.removeAt(0);
+ final Uri packageBase = map[packageName];
+ final String packageRelativePath = fs.path.joinAll(pathSegments);
return packageBase.resolve(packageRelativePath).path;
}
@@ -53,7 +53,7 @@
if (fs.isFileSync(packagesPath))
return null;
String message = '$packagesPath does not exist.';
- String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml');
+ final String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml');
if (fs.isFileSync(pubspecPath))
message += '\nDid you run "flutter packages get" in this directory?';
else
diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart
index 4cb0a7a..22e0fb2 100644
--- a/packages/flutter_tools/lib/src/dart/pub.dart
+++ b/packages/flutter_tools/lib/src/dart/pub.dart
@@ -15,10 +15,10 @@
bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) {
if (!dotPackages.existsSync())
return true;
- DateTime dotPackagesLastModified = dotPackages.lastModifiedSync();
+ final DateTime dotPackagesLastModified = dotPackages.lastModifiedSync();
if (pubSpecYaml.lastModifiedSync().isAfter(dotPackagesLastModified))
return true;
- File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools');
+ final File flutterToolsStamp = Cache.instance.getStampFileFor('flutter_tools');
if (flutterToolsStamp.existsSync() &&
flutterToolsStamp.lastModifiedSync().isAfter(dotPackagesLastModified))
return true;
@@ -34,8 +34,8 @@
if (directory == null)
directory = fs.currentDirectory.path;
- File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
- File dotPackages = fs.file(fs.path.join(directory, '.packages'));
+ final File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
+ final File dotPackages = fs.file(fs.path.join(directory, '.packages'));
if (!pubSpecYaml.existsSync()) {
if (!skipIfAbsent)
@@ -44,10 +44,10 @@
}
if (!checkLastModified || _shouldRunPubGet(pubSpecYaml: pubSpecYaml, dotPackages: dotPackages)) {
- String command = upgrade ? 'upgrade' : 'get';
- Status status = logger.startProgress("Running 'flutter packages $command' in ${fs.path.basename(directory)}...",
+ final String command = upgrade ? 'upgrade' : 'get';
+ final Status status = logger.startProgress("Running 'flutter packages $command' in ${fs.path.basename(directory)}...",
expectSlowOperation: true);
- int code = await runCommandAndStreamOutput(
+ final int code = await runCommandAndStreamOutput(
<String>[sdkBinaryName('pub'), '--verbosity=warning', command, '--no-packages-dir', '--no-precompile'],
workingDirectory: directory,
mapFunction: _filterOverrideWarnings,
diff --git a/packages/flutter_tools/lib/src/dependency_checker.dart b/packages/flutter_tools/lib/src/dependency_checker.dart
index d9efa5e..9bd3680 100644
--- a/packages/flutter_tools/lib/src/dependency_checker.dart
+++ b/packages/flutter_tools/lib/src/dependency_checker.dart
@@ -34,8 +34,8 @@
// Check all dependency modification times.
for (String path in _dependencies) {
- File file = fs.file(path);
- FileStat stat = file.statSync();
+ final File file = fs.file(path);
+ final FileStat stat = file.statSync();
if (stat.type == FileSystemEntityType.NOT_FOUND) {
printTrace('DependencyChecker: Error stating $path.');
return true;
diff --git a/packages/flutter_tools/lib/src/devfs.dart b/packages/flutter_tools/lib/src/devfs.dart
index e1f0236..d9277c6 100644
--- a/packages/flutter_tools/lib/src/devfs.dart
+++ b/packages/flutter_tools/lib/src/devfs.dart
@@ -72,8 +72,8 @@
_fileStat = file.statSync();
if (_fileStat.type == FileSystemEntityType.LINK) {
// Resolve, stat, and maybe cache the symlink target.
- String resolved = file.resolveSymbolicLinksSync();
- FileSystemEntity linkTarget = fs.file(resolved);
+ final String resolved = file.resolveSymbolicLinksSync();
+ final FileSystemEntity linkTarget = fs.file(resolved);
// Stat the link target.
_fileStat = linkTarget.statSync();
if (devFSConfig.cacheSymlinks) {
@@ -84,7 +84,7 @@
@override
bool get isModified {
- FileStat _oldFileStat = _fileStat;
+ final FileStat _oldFileStat = _fileStat;
_stat();
return _oldFileStat == null || _fileStat.modified.isAfter(_oldFileStat.modified);
}
@@ -121,7 +121,7 @@
/// Return `true` only once so that the content is written to the device only once.
@override
bool get isModified {
- bool modified = _isModified;
+ final bool modified = _isModified;
_isModified = false;
return modified;
}
@@ -173,7 +173,7 @@
@override
Future<Uri> create(String fsName) async {
- Map<String, dynamic> response = await vmService.vm.createDevFS(fsName);
+ final Map<String, dynamic> response = await vmService.vm.createDevFS(fsName);
return Uri.parse(response['uri']);
}
@@ -193,7 +193,7 @@
} catch (e) {
return e;
}
- String fileContents = BASE64.encode(bytes);
+ final String fileContents = BASE64.encode(bytes);
try {
return await vmService.vm.invokeRpcRaw(
'_writeDevFSFile',
@@ -251,8 +251,8 @@
// Finished.
break;
}
- Uri deviceUri = _outstanding.keys.first;
- DevFSContent content = _outstanding.remove(deviceUri);
+ final Uri deviceUri = _outstanding.keys.first;
+ final DevFSContent content = _outstanding.remove(deviceUri);
_scheduleWrite(deviceUri, content, progressReporter);
_inFlight++;
}
@@ -265,15 +265,15 @@
int retry = 0,
]) async {
try {
- HttpClientRequest request = await _client.putUrl(httpAddress);
+ final HttpClientRequest request = await _client.putUrl(httpAddress);
request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
request.headers.add('dev_fs_name', fsName);
// TODO(goderbauer): transfer real Uri (instead of file path) when remote end supports it
request.headers.add('dev_fs_path_b64',
BASE64.encode(UTF8.encode(deviceUri.toFilePath(windows: false))));
- Stream<List<int>> contents = content.contentsAsCompressedStream();
+ final Stream<List<int>> contents = content.contentsAsCompressedStream();
await request.addStream(contents);
- HttpClientResponse response = await request.close();
+ final HttpClientResponse response = await request.close();
await response.drain<Null>();
} catch (e) {
if (retry < kMaxRetries) {
@@ -375,17 +375,17 @@
// Handle deletions.
printTrace('Scanning for deleted files');
- String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
+ final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
final List<Uri> toRemove = new List<Uri>();
_entries.forEach((Uri deviceUri, DevFSContent content) {
if (!content._exists) {
- Future<Map<String, dynamic>> operation =
+ final Future<Map<String, dynamic>> operation =
_operations.deleteFile(fsName, deviceUri);
if (operation != null)
_pendingOperations.add(operation);
toRemove.add(deviceUri);
if (deviceUri.path.startsWith(assetBuildDirPrefix)) {
- String archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
+ final String archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
assetPathsToEvict.add(archivePath);
}
}
@@ -399,7 +399,7 @@
// Update modified files
int numBytes = 0;
- Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
+ final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
_entries.forEach((Uri deviceUri, DevFSContent content) {
String archivePath;
if (deviceUri.path.startsWith(assetBuildDirPrefix))
@@ -423,7 +423,7 @@
} else {
// Make service protocol requests for each.
dirtyEntries.forEach((Uri deviceUri, DevFSContent content) {
- Future<Map<String, dynamic>> operation =
+ final Future<Map<String, dynamic>> operation =
_operations.writeFile(fsName, deviceUri, content);
if (operation != null)
_pendingOperations.add(operation);
@@ -449,7 +449,7 @@
}
void _scanFile(Uri deviceUri, FileSystemEntity file) {
- DevFSContent content = _entries.putIfAbsent(deviceUri, () => new DevFSFileContent(file));
+ final DevFSContent content = _entries.putIfAbsent(deviceUri, () => new DevFSFileContent(file));
content._exists = true;
}
@@ -463,7 +463,7 @@
}
bool _shouldIgnore(Uri deviceUri) {
- List<String> ignoredUriPrefixes = <String>['android/',
+ final List<String> ignoredUriPrefixes = <String>['android/',
_asUriPath(getBuildDirectory()),
'ios/',
'.pub/'];
@@ -480,7 +480,7 @@
bool ignoreDotFiles: true,
Set<String> fileFilter}) async {
if (directoryUriOnDevice == null) {
- String relativeRootPath = fs.path.relative(directory.path, from: rootDirectory.path);
+ final String relativeRootPath = fs.path.relative(directory.path, from: rootDirectory.path);
if (relativeRootPath == '.') {
directoryUriOnDevice = new Uri();
} else {
@@ -488,7 +488,7 @@
}
}
try {
- Stream<FileSystemEntity> files =
+ final Stream<FileSystemEntity> files =
directory.list(recursive: recursive, followLinks: false);
await for (FileSystemEntity file in files) {
if (!devFSConfig.noDirectorySymlinks && (file is Link)) {
@@ -532,12 +532,12 @@
Future<Null> _scanPackages(Set<String> fileFilter) async {
StringBuffer sb;
- PackageMap packageMap = new PackageMap(_packagesFilePath);
+ final PackageMap packageMap = new PackageMap(_packagesFilePath);
for (String packageName in packageMap.map.keys) {
- Uri packageUri = packageMap.map[packageName];
- String packagePath = packageUri.toFilePath();
- Directory packageDirectory = fs.directory(packageUri);
+ final Uri packageUri = packageMap.map[packageName];
+ final String packagePath = packageUri.toFilePath();
+ final Directory packageDirectory = fs.directory(packageUri);
Uri directoryUriOnDevice = fs.path.toUri(fs.path.join('packages', packageName) + fs.path.separator);
bool packageExists;
@@ -560,7 +560,7 @@
}
}
if (sb != null) {
- DevFSContent content = _entries[fs.path.toUri('.packages')];
+ final DevFSContent content = _entries[fs.path.toUri('.packages')];
if (content is DevFSStringContent && content.string == sb.toString()) {
content._exists = true;
return;
diff --git a/packages/flutter_tools/lib/src/device.dart b/packages/flutter_tools/lib/src/device.dart
index b29be3f..09d3ab2 100644
--- a/packages/flutter_tools/lib/src/device.dart
+++ b/packages/flutter_tools/lib/src/device.dart
@@ -42,8 +42,8 @@
/// This does a case insentitive compare with [deviceId].
Future<List<Device>> getDevicesById(String deviceId) async {
deviceId = deviceId.toLowerCase();
- List<Device> devices = await getAllConnectedDevices();
- Device device = devices.firstWhere(
+ final List<Device> devices = await getAllConnectedDevices();
+ final Device device = devices.firstWhere(
(Device device) =>
device.id.toLowerCase() == deviceId ||
device.name.toLowerCase() == deviceId,
@@ -250,11 +250,11 @@
return <String>[];
// Extract device information
- List<List<String>> table = <List<String>>[];
+ final List<List<String>> table = <List<String>>[];
for (Device device in devices) {
String supportIndicator = device.isSupported() ? '' : ' (unsupported)';
if (device.isLocalEmulator) {
- String type = device.platform == TargetPlatform.ios ? 'simulator' : 'emulator';
+ final String type = device.platform == TargetPlatform.ios ? 'simulator' : 'emulator';
supportIndicator += ' ($type)';
}
table.add(<String>[
@@ -266,7 +266,7 @@
}
// Calculate column widths
- List<int> indices = new List<int>.generate(table[0].length - 1, (int i) => i);
+ final List<int> indices = new List<int>.generate(table[0].length - 1, (int i) => i);
List<int> widths = indices.map((int i) => 0).toList();
for (List<String> row in table) {
widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList();
@@ -336,7 +336,7 @@
@override
String toString() {
- StringBuffer buf = new StringBuffer('started=$started');
+ final StringBuffer buf = new StringBuffer('started=$started');
if (observatoryUri != null)
buf.write(', observatory=$observatoryUri');
if (diagnosticUri != null)
diff --git a/packages/flutter_tools/lib/src/doctor.dart b/packages/flutter_tools/lib/src/doctor.dart
index 1ec463e..f4fd3ea 100644
--- a/packages/flutter_tools/lib/src/doctor.dart
+++ b/packages/flutter_tools/lib/src/doctor.dart
@@ -28,7 +28,7 @@
};
String osName() {
- String os = platform.operatingSystem;
+ final String os = platform.operatingSystem;
return _osNames.containsKey(os) ? _osNames[os] : os;
}
@@ -59,7 +59,7 @@
if (_iosWorkflow.appliesToHostPlatform)
_validators.add(_iosWorkflow);
- List<DoctorValidator> ideValidators = <DoctorValidator>[];
+ final List<DoctorValidator> ideValidators = <DoctorValidator>[];
ideValidators.addAll(AndroidStudioValidator.allValidators);
ideValidators.addAll(IntelliJValidator.installedValidators);
if (ideValidators.isNotEmpty)
@@ -82,12 +82,12 @@
}
Future<String> get summaryText async {
- StringBuffer buffer = new StringBuffer();
+ final StringBuffer buffer = new StringBuffer();
bool allGood = true;
for (DoctorValidator validator in validators) {
- ValidationResult result = await validator.validate();
+ final ValidationResult result = await validator.validate();
buffer.write('${result.leadingBox} ${validator.title} is ');
if (result.type == ValidationType.missing)
buffer.write('not installed.');
@@ -123,7 +123,7 @@
printStatus('');
firstLine = false;
- ValidationResult result = await validator.validate();
+ final ValidationResult result = await validator.validate();
if (result.type == ValidationType.missing)
doctorResult = false;
@@ -134,7 +134,7 @@
printStatus('${result.leadingBox} ${validator.title}');
for (ValidationMessage message in result.messages) {
- String text = message.message.replaceAll('\n', '\n ');
+ final String text = message.message.replaceAll('\n', '\n ');
if (message.isError) {
printStatus(' ✗ $text', emphasis: true);
} else {
@@ -211,10 +211,10 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
- ValidationType valid = ValidationType.installed;
+ final List<ValidationMessage> messages = <ValidationMessage>[];
+ final ValidationType valid = ValidationType.installed;
- FlutterVersion version = FlutterVersion.getVersion();
+ final FlutterVersion version = FlutterVersion.getVersion();
messages.add(new ValidationMessage('Flutter at ${version.flutterRoot}'));
messages.add(new ValidationMessage(
@@ -262,7 +262,7 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
int installCount = 0;
@@ -300,25 +300,25 @@
));
return false;
}
- String version = _readPackageVersion(packageName);
+ final String version = _readPackageVersion(packageName);
messages.add(new ValidationMessage('$title plugin '
'${version != null ? "version $version" : "installed"}'));
return true;
}
String _readPackageVersion(String packageName) {
- String jarPath = packageName.endsWith('.jar')
+ final String jarPath = packageName.endsWith('.jar')
? fs.path.join(pluginsPath, packageName)
: fs.path.join(pluginsPath, packageName, 'lib', '$packageName.jar');
// TODO(danrubel) look for a better way to extract a single 2K file from the zip
// rather than reading the entire file into memory.
try {
- Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
- ArchiveFile file = archive.findFile('META-INF/plugin.xml');
- String content = UTF8.decode(file.content);
- String versionStartTag = '<version>';
- int start = content.indexOf(versionStartTag);
- int end = content.indexOf('</version>', start);
+ final Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
+ final ArchiveFile file = archive.findFile('META-INF/plugin.xml');
+ final String content = UTF8.decode(file.content);
+ final String versionStartTag = '<version>';
+ final int start = content.indexOf(versionStartTag);
+ final int end = content.indexOf('</version>', start);
return content.substring(start + versionStartTag.length, end);
} catch (_) {
return null;
@@ -326,7 +326,7 @@
}
bool hasPackage(String packageName) {
- String packagePath = fs.path.join(pluginsPath, packageName);
+ final String packagePath = fs.path.join(pluginsPath, packageName);
if (packageName.endsWith('.jar'))
return fs.isFileSync(packagePath);
return fs.isDirectorySync(packagePath);
@@ -345,14 +345,14 @@
String pluginsPath;
static Iterable<DoctorValidator> get installed {
- List<DoctorValidator> validators = <DoctorValidator>[];
+ final List<DoctorValidator> validators = <DoctorValidator>[];
if (homeDirPath == null) return validators;
void addValidator(String title, String version, String installPath, String pluginsPath) {
- IntelliJValidatorOnLinuxAndWindows validator =
+ final IntelliJValidatorOnLinuxAndWindows validator =
new IntelliJValidatorOnLinuxAndWindows(title, version, installPath, pluginsPath);
for (int index = 0; index < validators.length; ++index) {
- DoctorValidator other = validators[index];
+ final DoctorValidator other = validators[index];
if (other is IntelliJValidatorOnLinuxAndWindows && validator.installPath == other.installPath) {
if (validator.version.compareTo(other.version) > 0)
validators[index] = validator;
@@ -364,10 +364,10 @@
for (FileSystemEntity dir in fs.directory(homeDirPath).listSync()) {
if (dir is Directory) {
- String name = fs.path.basename(dir.path);
+ final String name = fs.path.basename(dir.path);
IntelliJValidator._idToTitle.forEach((String id, String title) {
if (name.startsWith('.$id')) {
- String version = name.substring(id.length + 1);
+ final String version = name.substring(id.length + 1);
String installPath;
try {
installPath = fs.file(fs.path.join(dir.path, 'system', '.home')).readAsStringSync();
@@ -375,7 +375,7 @@
// ignored
}
if (installPath != null && fs.isDirectorySync(installPath)) {
- String pluginsPath = fs.path.join(dir.path, 'config', 'plugins');
+ final String pluginsPath = fs.path.join(dir.path, 'config', 'plugins');
addValidator(title, version, installPath, pluginsPath);
}
}
@@ -400,21 +400,21 @@
};
static Iterable<DoctorValidator> get installed {
- List<DoctorValidator> validators = <DoctorValidator>[];
- List<String> installPaths = <String>['/Applications', fs.path.join(homeDirPath, 'Applications')];
+ final List<DoctorValidator> validators = <DoctorValidator>[];
+ final List<String> installPaths = <String>['/Applications', fs.path.join(homeDirPath, 'Applications')];
void checkForIntelliJ(Directory dir) {
- String name = fs.path.basename(dir.path);
+ final String name = fs.path.basename(dir.path);
_dirNameToId.forEach((String dirName, String id) {
if (name == dirName) {
- String title = IntelliJValidator._idToTitle[id];
+ final String title = IntelliJValidator._idToTitle[id];
validators.add(new IntelliJValidatorOnMac(title, id, dir.path));
}
});
}
try {
- Iterable<FileSystemEntity> installDirs = installPaths
+ final Iterable<FileSystemEntity> installDirs = installPaths
.map((String installPath) => fs.directory(installPath).listSync())
.expand((List<FileSystemEntity> mappedDirs) => mappedDirs)
.where((FileSystemEntity mappedDir) => mappedDir is Directory);
@@ -444,7 +444,7 @@
@override
String get version {
if (_version == null) {
- String plistFile = fs.path.join(installPath, 'Contents', 'Info.plist');
+ final String plistFile = fs.path.join(installPath, 'Contents', 'Info.plist');
_version = getValueFromFile(plistFile, kCFBundleShortVersionStringKey) ?? 'unknown';
}
return _version;
@@ -453,9 +453,9 @@
@override
String get pluginsPath {
- List<String> split = version.split('.');
- String major = split[0];
- String minor = split[1];
+ final List<String> split = version.split('.');
+ final String major = split[0];
+ final String minor = split[1];
return fs.path.join(homeDirPath, 'Library', 'Application Support', '$id$major.$minor');
}
}
@@ -465,7 +465,7 @@
@override
Future<ValidationResult> validate() async {
- List<Device> devices = await deviceManager.getAllConnectedDevices();
+ final List<Device> devices = await deviceManager.getAllConnectedDevices();
List<ValidationMessage> messages;
if (devices.isEmpty) {
messages = <ValidationMessage>[new ValidationMessage('None')];
diff --git a/packages/flutter_tools/lib/src/flx.dart b/packages/flutter_tools/lib/src/flx.dart
index bd0078f..fa4a75b 100644
--- a/packages/flutter_tools/lib/src/flx.dart
+++ b/packages/flutter_tools/lib/src/flx.dart
@@ -59,7 +59,7 @@
assert(mainPath != null);
assert(snapshotPath != null);
assert(packages != null);
- String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot);
+ final String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot);
final List<String> args = <String>[
snapshotterPath,
@@ -83,9 +83,9 @@
assert(mainPath != null);
assert(snapshotPath != null);
assert(packages != null);
- String snapshotterPath = artifacts.getArtifactPath(Artifact.genSnapshot);
- String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData);
- String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData);
+ final String snapshotterPath = artifacts.getArtifactPath(Artifact.genSnapshot);
+ final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData);
+ final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData);
final List<String> args = <String>[
snapshotterPath,
@@ -149,7 +149,7 @@
if (kernelContent != null) {
// TODO(danrubel) in the future, call the VM to generate this file
kernelFile = fs.file(kernelPath);
- IOSink sink = kernelFile.openWrite();
+ final IOSink sink = kernelFile.openWrite();
await sink.addStream(kernelContent.contentsAsStream());
sink.close();
}
@@ -158,7 +158,7 @@
// In a precompiled snapshot, the instruction buffer contains script
// content equivalents
- int result = await createSnapshot(
+ final int result = await createSnapshot(
mainPath: mainPath,
snapshotPath: snapshotPath,
depfilePath: depfilePath,
@@ -201,8 +201,8 @@
printTrace('Building $outputPath');
// Build the asset bundle.
- AssetBundle assetBundle = new AssetBundle();
- int result = await assetBundle.build(
+ final AssetBundle assetBundle = new AssetBundle();
+ final int result = await assetBundle.build(
manifestPath: manifestPath,
workingDirPath: workingDirPath,
packagesPath: packagesPath,
@@ -213,7 +213,7 @@
if (result != 0)
throwToolExit('Error building $outputPath: $result', exitCode: result);
- ZipBuilder zipBuilder = new ZipBuilder();
+ final ZipBuilder zipBuilder = new ZipBuilder();
// Add all entries from the asset bundle.
zipBuilder.entries.addAll(assetBundle.entries);
diff --git a/packages/flutter_tools/lib/src/ios/devices.dart b/packages/flutter_tools/lib/src/ios/devices.dart
index 343956d..9075daf 100644
--- a/packages/flutter_tools/lib/src/ios/devices.dart
+++ b/packages/flutter_tools/lib/src/ios/devices.dart
@@ -97,18 +97,18 @@
if (!doctor.iosWorkflow.hasIDeviceId)
return <IOSDevice>[];
- List<IOSDevice> devices = <IOSDevice>[];
+ final List<IOSDevice> devices = <IOSDevice>[];
for (String id in _getAttachedDeviceIDs(mockIOS)) {
- String name = IOSDevice._getDeviceInfo(id, 'DeviceName', mockIOS);
+ final String name = IOSDevice._getDeviceInfo(id, 'DeviceName', mockIOS);
devices.add(new IOSDevice(id, name: name));
}
return devices;
}
static Iterable<String> _getAttachedDeviceIDs([IOSDevice mockIOS]) {
- String listerPath = (mockIOS != null) ? mockIOS.listerPath : _checkForCommand('idevice_id');
+ final String listerPath = (mockIOS != null) ? mockIOS.listerPath : _checkForCommand('idevice_id');
try {
- String output = runSync(<String>[listerPath, '-l']);
+ final String output = runSync(<String>[listerPath, '-l']);
return output.trim().split('\n').where((String s) => s != null && s.isNotEmpty);
} catch (e) {
return <String>[];
@@ -116,7 +116,7 @@
}
static String _getDeviceInfo(String deviceID, String infoKey, [IOSDevice mockIOS]) {
- String informerPath = (mockIOS != null)
+ final String informerPath = (mockIOS != null)
? mockIOS.informerPath
: _checkForCommand('ideviceinfo');
return runSync(<String>[informerPath, '-k', infoKey, '-u', deviceID]).trim();
@@ -142,7 +142,7 @@
@override
bool isAppInstalled(ApplicationPackage app) {
try {
- String apps = runCheckedSync(<String>[installerPath, '--list-apps']);
+ final String apps = runCheckedSync(<String>[installerPath, '--list-apps']);
if (new RegExp(app.id, multiLine: true).hasMatch(apps)) {
return true;
}
@@ -157,8 +157,8 @@
@override
bool installApp(ApplicationPackage app) {
- IOSApp iosApp = app;
- Directory bundle = fs.directory(iosApp.deviceBundlePath);
+ final IOSApp iosApp = app;
+ final Directory bundle = fs.directory(iosApp.deviceBundlePath);
if (!bundle.existsSync()) {
printError("Could not find application bundle at ${bundle.path}; have you run 'flutter build ios'?");
return false;
@@ -203,7 +203,7 @@
printTrace('Building ${app.name} for $id');
// Step 1: Build the precompiled/DBC application if necessary.
- XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: mode, target: mainPath, buildForDevice: true);
+ final XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: mode, target: mainPath, buildForDevice: true);
if (!buildResult.success) {
printError('Could not build the precompiled application for the device.');
await diagnoseXcodeBuildFailure(buildResult);
@@ -216,15 +216,15 @@
}
// Step 2: Check that the application exists at the specified path.
- IOSApp iosApp = app;
- Directory bundle = fs.directory(iosApp.deviceBundlePath);
+ final IOSApp iosApp = app;
+ final Directory bundle = fs.directory(iosApp.deviceBundlePath);
if (!bundle.existsSync()) {
printError('Could not find the built application bundle at ${bundle.path}.');
return new LaunchResult.failed();
}
// Step 3: Attempt to install the application on the device.
- List<String> launchArguments = <String>["--enable-dart-profiling"];
+ final List<String> launchArguments = <String>["--enable-dart-profiling"];
if (debuggingOptions.startPaused)
launchArguments.add("--start-paused");
@@ -240,7 +240,7 @@
if (platformArgs['trace-startup'] ?? false)
launchArguments.add('--trace-startup');
- List<String> launchCommand = <String>[
+ final List<String> launchCommand = <String>[
'/usr/bin/env',
'ios-deploy',
'--id',
@@ -271,12 +271,12 @@
// TODO(danrubel): The Android device class does something similar to this code below.
// The various Device subclasses should be refactored and common code moved into the superclass.
- ProtocolDiscovery observatoryDiscovery = new ProtocolDiscovery.observatory(
+ final ProtocolDiscovery observatoryDiscovery = new ProtocolDiscovery.observatory(
getLogReader(app: app), portForwarder: portForwarder, hostPort: debuggingOptions.observatoryPort);
- ProtocolDiscovery diagnosticDiscovery = new ProtocolDiscovery.diagnosticService(
+ final ProtocolDiscovery diagnosticDiscovery = new ProtocolDiscovery.diagnosticService(
getLogReader(app: app), portForwarder: portForwarder, hostPort: debuggingOptions.diagnosticPort);
- Future<Uri> forwardObsUri = observatoryDiscovery.nextUri();
+ final Future<Uri> forwardObsUri = observatoryDiscovery.nextUri();
Future<Uri> forwardDiagUri;
if (debuggingOptions.buildMode == BuildMode.debug) {
forwardDiagUri = diagnosticDiscovery.nextUri();
@@ -284,9 +284,9 @@
forwardDiagUri = new Future<Uri>.value(null);
}
- Future<int> launch = runCommandAndStreamOutput(launchCommand, trace: true);
+ final Future<int> launch = runCommandAndStreamOutput(launchCommand, trace: true);
- List<Uri> uris = await launch.then<List<Uri>>((int result) async {
+ final List<Uri> uris = await launch.then<List<Uri>>((int result) async {
installationResult = result;
if (result != 0) {
@@ -392,7 +392,7 @@
//
// iOS 9 format: Runner[297] <Notice>:
// iOS 10 format: Runner(libsystem_asl.dylib)[297] <Notice>:
- String appName = app == null ? '' : app.name.replaceAll('.app', '');
+ final String appName = app == null ? '' : app.name.replaceAll('.app', '');
_lineRegex = new RegExp(appName + r'(\(.*\))?\[[\d]+\] <[A-Za-z]+>: ');
}
@@ -420,7 +420,7 @@
}
void _onLine(String line) {
- Match match = _lineRegex.firstMatch(line);
+ final Match match = _lineRegex.firstMatch(line);
if (match != null) {
// Only display the log line after the initial device and executable information.
@@ -451,14 +451,14 @@
}
// Usage: iproxy LOCAL_TCP_PORT DEVICE_TCP_PORT UDID
- Process process = await runCommand(<String>[
+ final Process process = await runCommand(<String>[
device.iproxyPath,
hostPort.toString(),
devicePort.toString(),
device.id,
]);
- ForwardedPort forwardedPort = new ForwardedPort.withContext(hostPort,
+ final ForwardedPort forwardedPort = new ForwardedPort.withContext(hostPort,
devicePort, process);
printTrace("Forwarded port $forwardedPort");
@@ -477,7 +477,7 @@
printTrace("Unforwarding port $forwardedPort");
- Process process = forwardedPort.context;
+ final Process process = forwardedPort.context;
if (process != null) {
processManager.killPid(process.pid);
diff --git a/packages/flutter_tools/lib/src/ios/ios_workflow.dart b/packages/flutter_tools/lib/src/ios/ios_workflow.dart
index 6a672f8..3154fab 100644
--- a/packages/flutter_tools/lib/src/ios/ios_workflow.dart
+++ b/packages/flutter_tools/lib/src/ios/ios_workflow.dart
@@ -46,7 +46,7 @@
if (!hasIosDeploy)
return false;
try {
- Version version = new Version.parse(iosDeployVersionText);
+ final Version version = new Version.parse(iosDeployVersionText);
return version >= new Version.parse(iosDeployMinimumVersion);
} on FormatException catch (_) {
return false;
@@ -55,7 +55,7 @@
@override
Future<ValidationResult> validate() async {
- List<ValidationMessage> messages = <ValidationMessage>[];
+ final List<ValidationMessage> messages = <ValidationMessage>[];
ValidationType xcodeStatus = ValidationType.missing;
ValidationType pythonStatus = ValidationType.missing;
ValidationType brewStatus = ValidationType.missing;
@@ -143,7 +143,7 @@
} else {
// Check for compatibility between libimobiledevice and Xcode.
// TODO(cbracken) remove this check once libimobiledevice > 1.2.0 is released.
- ProcessResult result = (await runAsync(<String>['idevice_id', '-l'])).processResult;
+ final ProcessResult result = (await runAsync(<String>['idevice_id', '-l'])).processResult;
if (result.exitCode == 0 && result.stdout.isNotEmpty && !exitsHappy(<String>['ideviceName'])) {
brewStatus = ValidationType.partial;
messages.add(new ValidationMessage.error(
diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart
index 599521f..26b6c93 100644
--- a/packages/flutter_tools/lib/src/ios/mac.dart
+++ b/packages/flutter_tools/lib/src/ios/mac.dart
@@ -42,7 +42,7 @@
} else {
try {
printTrace('xcrun clang');
- ProcessResult result = processManager.runSync(<String>['/usr/bin/xcrun', 'clang']);
+ final ProcessResult result = processManager.runSync(<String>['/usr/bin/xcrun', 'clang']);
if (result.stdout != null && result.stdout.contains('license'))
_eulaSigned = false;
@@ -88,8 +88,8 @@
if (!xcodeVersionRegex.hasMatch(xcodeVersionText))
return false;
- String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1);
- List<String> components = version.split('.');
+ final String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1);
+ final List<String> components = version.split('.');
_xcodeMajorVersion = int.parse(components[0]);
_xcodeMinorVersion = components.length == 1 ? 0 : int.parse(components[1]);
@@ -115,7 +115,7 @@
bool buildForDevice,
bool codesign: true
}) async {
- String flutterProjectPath = fs.currentDirectory.path;
+ final String flutterProjectPath = fs.currentDirectory.path;
updateXcodeGeneratedProperties(flutterProjectPath, mode, target);
if (!_checkXcodeVersion())
@@ -126,7 +126,7 @@
await _addServicesToBundle(fs.directory(app.appDirectory));
- List<String> commands = <String>[
+ final List<String> commands = <String>[
'/usr/bin/env',
'xcrun',
'xcodebuild',
@@ -136,7 +136,7 @@
'ONLY_ACTIVE_ARCH=YES',
];
- List<FileSystemEntity> contents = fs.directory(app.appDirectory).listSync();
+ final List<FileSystemEntity> contents = fs.directory(app.appDirectory).listSync();
for (FileSystemEntity entity in contents) {
if (fs.path.extension(entity.path) == '.xcworkspace') {
commands.addAll(<String>[
@@ -164,7 +164,7 @@
);
}
- RunResult result = await runAsync(
+ final RunResult result = await runAsync(
commands,
workingDirectory: app.appDirectory,
allowReentrantFlutter: true
@@ -192,8 +192,8 @@
);
} else {
// Look for 'clean build/Release-iphoneos/Runner.app'.
- RegExp regexp = new RegExp(r' clean (\S*\.app)$', multiLine: true);
- Match match = regexp.firstMatch(result.stdout);
+ final RegExp regexp = new RegExp(r' clean (\S*\.app)$', multiLine: true);
+ final Match match = regexp.firstMatch(result.stdout);
String outputDir;
if (match != null)
outputDir = fs.path.join(app.appDirectory, match.group(1));
@@ -202,9 +202,9 @@
}
Future<Null> diagnoseXcodeBuildFailure(XcodeBuildResult result) async {
- File plistFile = fs.file('ios/Runner/Info.plist');
+ final File plistFile = fs.file('ios/Runner/Info.plist');
if (plistFile.existsSync()) {
- String plistContent = plistFile.readAsStringSync();
+ final String plistContent = plistFile.readAsStringSync();
if (plistContent.contains('com.yourcompany')) {
printError('');
printError('It appears that your application still contains the default signing identifier.');
@@ -232,7 +232,7 @@
assert(result.xcodeBuildExecution.appDirectory != null);
if (result.xcodeBuildExecution.buildForPhysicalDevice &&
result.xcodeBuildExecution.buildCommands.contains('build')) {
- RunResult checkBuildSettings = await runAsync(
+ final RunResult checkBuildSettings = await runAsync(
result.xcodeBuildExecution.buildCommands..add('-showBuildSettings'),
workingDirectory: result.xcodeBuildExecution.appDirectory,
allowReentrantFlutter: true
@@ -302,8 +302,8 @@
if (!platform.isMacOS)
return false;
try {
- String version = runCheckedSync(<String>['xcodebuild', '-version']);
- Match match = _xcodeVersionRegExp.firstMatch(version);
+ final String version = runCheckedSync(<String>['xcodebuild', '-version']);
+ final Match match = _xcodeVersionRegExp.firstMatch(version);
if (int.parse(match[1]) < 7) {
printError('Found "${match[0]}". $_xcodeRequirement');
return false;
@@ -316,7 +316,7 @@
}
Future<Null> _addServicesToBundle(Directory bundle) async {
- List<Map<String, String>> services = <Map<String, String>>[];
+ final List<Map<String, String>> services = <Map<String, String>>[];
printTrace("Trying to resolve native pub services.");
// Step 1: Parse the service configuration yaml files present in the service
@@ -325,12 +325,12 @@
printTrace("Found ${services.length} service definition(s).");
// Step 2: Copy framework dylibs to the correct spot for xcodebuild to pick up.
- Directory frameworksDirectory = fs.directory(fs.path.join(bundle.path, "Frameworks"));
+ final Directory frameworksDirectory = fs.directory(fs.path.join(bundle.path, "Frameworks"));
await _copyServiceFrameworks(services, frameworksDirectory);
// Step 3: Copy the service definitions manifest at the correct spot for
// xcodebuild to pick up.
- File manifestFile = fs.file(fs.path.join(bundle.path, "ServiceDefinitions.json"));
+ final File manifestFile = fs.file(fs.path.join(bundle.path, "ServiceDefinitions.json"));
_copyServiceDefinitionsManifest(services, manifestFile);
}
@@ -338,8 +338,8 @@
printTrace("Copying service frameworks to '${fs.path.absolute(frameworksDirectory.path)}'.");
frameworksDirectory.createSync(recursive: true);
for (Map<String, String> service in services) {
- String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
- File dylib = fs.file(dylibPath);
+ final String dylibPath = await getServiceFromUrl(service['ios-framework'], service['root'], service['name']);
+ final File dylib = fs.file(dylibPath);
printTrace("Copying ${dylib.path} into bundle.");
if (!dylib.existsSync()) {
printError("The service dylib '${dylib.path}' does not exist.");
@@ -352,12 +352,12 @@
void _copyServiceDefinitionsManifest(List<Map<String, String>> services, File manifest) {
printTrace("Creating service definitions manifest at '${manifest.path}'");
- List<Map<String, String>> jsonServices = services.map((Map<String, String> service) => <String, String>{
+ final List<Map<String, String>> jsonServices = services.map((Map<String, String> service) => <String, String>{
'name': service['name'],
// Since we have already moved it to the Frameworks directory. Strip away
// the directory and basenames.
'framework': fs.path.basenameWithoutExtension(service['ios-framework'])
}).toList();
- Map<String, dynamic> json = <String, dynamic>{ 'services' : jsonServices };
+ final Map<String, dynamic> json = <String, dynamic>{ 'services' : jsonServices };
manifest.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
}
diff --git a/packages/flutter_tools/lib/src/ios/plist_utils.dart b/packages/flutter_tools/lib/src/ios/plist_utils.dart
index 105c18c..6d727d4 100644
--- a/packages/flutter_tools/lib/src/ios/plist_utils.dart
+++ b/packages/flutter_tools/lib/src/ios/plist_utils.dart
@@ -19,10 +19,10 @@
if (!fs.isFileSync(plistFilePath))
return null;
- String normalizedPlistPath = fs.path.withoutExtension(fs.path.absolute(plistFilePath));
+ final String normalizedPlistPath = fs.path.withoutExtension(fs.path.absolute(plistFilePath));
try {
- String value = runCheckedSync(<String>[
+ final String value = runCheckedSync(<String>[
'/usr/bin/defaults', 'read', normalizedPlistPath, key
]);
return value.isEmpty ? null : value;
diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart
index 6a82aa9..71b46c4 100644
--- a/packages/flutter_tools/lib/src/ios/simulators.dart
+++ b/packages/flutter_tools/lib/src/ios/simulators.dart
@@ -61,7 +61,7 @@
return true;
if (deviceName == null) {
- SimDevice testDevice = _createTestDevice();
+ final SimDevice testDevice = _createTestDevice();
if (testDevice == null) {
return false;
}
@@ -72,7 +72,7 @@
// "template" is but the built-in 'Blank' seems to work. -l causes xcrun to
// quit after a time limit without killing the simulator. We quit after
// 1 second.
- List<String> args = <String>[_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1'];
+ final List<String> args = <String>[_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1'];
printTrace(args.join(' '));
runDetached(args);
printStatus('Waiting for iOS Simulator to boot...');
@@ -98,11 +98,11 @@
}
SimDevice _createTestDevice() {
- SimDeviceType deviceType = _findSuitableDeviceType();
+ final SimDeviceType deviceType = _findSuitableDeviceType();
if (deviceType == null)
return null;
- String runtime = _findSuitableRuntime();
+ final String runtime = _findSuitableRuntime();
if (runtime == null)
return null;
@@ -112,8 +112,8 @@
.forEach(_deleteDevice);
// Create new device
- String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix';
- List<String> args = <String>[_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime];
+ final String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix';
+ final List<String> args = <String>[_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime];
printTrace(args.join(' '));
runCheckedSync(args);
@@ -121,8 +121,8 @@
}
SimDeviceType _findSuitableDeviceType() {
- List<Map<String, dynamic>> allTypes = _list(SimControlListSection.devicetypes);
- List<Map<String, dynamic>> usableTypes = allTypes
+ final List<Map<String, dynamic>> allTypes = _list(SimControlListSection.devicetypes);
+ final List<Map<String, dynamic>> usableTypes = allTypes
.where((Map<String, dynamic> info) => info['name'].startsWith('iPhone'))
.toList()
..sort((Map<String, dynamic> r1, Map<String, dynamic> r2) => -compareIphoneVersions(r1['identifier'], r2['identifier']));
@@ -141,8 +141,8 @@
}
String _findSuitableRuntime() {
- List<Map<String, dynamic>> allRuntimes = _list(SimControlListSection.runtimes);
- List<Map<String, dynamic>> usableRuntimes = allRuntimes
+ final List<Map<String, dynamic>> allRuntimes = _list(SimControlListSection.runtimes);
+ final List<Map<String, dynamic>> usableRuntimes = allRuntimes
.where((Map<String, dynamic> info) => info['name'].startsWith('iOS'))
.toList()
..sort((Map<String, dynamic> r1, Map<String, dynamic> r2) => -compareIosVersions(r1['version'], r2['version']));
@@ -159,7 +159,7 @@
void _deleteDevice(SimDevice device) {
try {
- List<String> args = <String>[_xcrunPath, 'simctl', 'delete', device.name];
+ final List<String> args = <String>[_xcrunPath, 'simctl', 'delete', device.name];
printTrace(args.join(' '));
runCheckedSync(args);
} catch(e) {
@@ -190,9 +190,9 @@
// },
// "pairs": { ... },
- List<String> command = <String>[_xcrunPath, 'simctl', 'list', '--json', section.name];
+ final List<String> command = <String>[_xcrunPath, 'simctl', 'list', '--json', section.name];
printTrace(command.join(' '));
- ProcessResult results = processManager.runSync(command);
+ final ProcessResult results = processManager.runSync(command);
if (results.exitCode != 0) {
printError('Error executing simctl: ${results.exitCode}\n${results.stderr}');
return <String, Map<String, dynamic>>{};
@@ -203,12 +203,12 @@
/// Returns a list of all available devices, both potential and connected.
List<SimDevice> getDevices() {
- List<SimDevice> devices = <SimDevice>[];
+ final List<SimDevice> devices = <SimDevice>[];
- Map<String, dynamic> devicesSection = _list(SimControlListSection.devices);
+ final Map<String, dynamic> devicesSection = _list(SimControlListSection.devices);
for (String deviceCategory in devicesSection.keys) {
- List<Map<String, String>> devicesData = devicesSection[deviceCategory];
+ final List<Map<String, String>> devicesData = devicesSection[deviceCategory];
for (Map<String, String> data in devicesData) {
devices.add(new SimDevice(deviceCategory, data));
@@ -244,7 +244,7 @@
}
void launch(String deviceId, String appIdentifier, [List<String> launchArgs]) {
- List<String> args = <String>[_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier];
+ final List<String> args = <String>[_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier];
if (launchArgs != null)
args.addAll(launchArgs);
runCheckedSync(args);
@@ -329,7 +329,7 @@
}
String _getSimulatorAppHomeDirectory(ApplicationPackage app) {
- String simulatorPath = _getSimulatorPath();
+ final String simulatorPath = _getSimulatorPath();
if (simulatorPath == null)
return null;
return fs.path.join(simulatorPath, 'data');
@@ -346,7 +346,7 @@
@override
bool installApp(ApplicationPackage app) {
try {
- IOSApp iosApp = app;
+ final IOSApp iosApp = app;
SimControl.instance.install(id, iosApp.simulatorBundlePath);
return true;
} catch (e) {
@@ -374,7 +374,7 @@
// Step 1: Check if the device is part of a blacklisted category.
// We do not support WatchOS or tvOS devices.
- RegExp blacklist = new RegExp(r'Apple (TV|Watch)', caseSensitive: false);
+ final RegExp blacklist = new RegExp(r'Apple (TV|Watch)', caseSensitive: false);
if (blacklist.hasMatch(name)) {
_supportMessage = 'Flutter does not support Apple TV or Apple Watch. Select an iPhone 5s or above.';
return false;
@@ -386,14 +386,14 @@
// runner on the simulator is completely different).
// Check for unsupported iPads.
- Match iPadMatch = new RegExp(r'iPad (2|Retina)', caseSensitive: false).firstMatch(name);
+ final Match iPadMatch = new RegExp(r'iPad (2|Retina)', caseSensitive: false).firstMatch(name);
if (iPadMatch != null) {
_supportMessage = 'Flutter does not yet support iPad 2 or iPad Retina. Select an iPad Air or above.';
return false;
}
// Check for unsupported iPhones.
- Match iPhoneMatch = new RegExp(r'iPhone [0-5]').firstMatch(name);
+ final Match iPhoneMatch = new RegExp(r'iPhone [0-5]').firstMatch(name);
if (iPhoneMatch != null) {
if (name == 'iPhone 5s')
return true;
@@ -441,7 +441,7 @@
}
// Prepare launch arguments.
- List<String> args = <String>['--enable-dart-profiling'];
+ final List<String> args = <String>['--enable-dart-profiling'];
if (!prebuiltApplication) {
args.addAll(<String>[
@@ -457,9 +457,9 @@
if (debuggingOptions.startPaused)
args.add('--start-paused');
- int observatoryPort = await debuggingOptions.findBestObservatoryPort();
+ final int observatoryPort = await debuggingOptions.findBestObservatoryPort();
args.add('--observatory-port=$observatoryPort');
- int diagnosticPort = await debuggingOptions.findBestDiagnosticPort();
+ final int diagnosticPort = await debuggingOptions.findBestDiagnosticPort();
args.add('--diagnostic-port=$diagnosticPort');
}
@@ -484,7 +484,7 @@
printTrace('Waiting for observatory port to be available...');
try {
- Uri deviceUri = await observatoryDiscovery.nextUri();
+ final Uri deviceUri = await observatoryDiscovery.nextUri();
return new LaunchResult.succeeded(observatoryUri: deviceUri);
} catch (error) {
printError('Error waiting for a debug connection: $error');
@@ -495,9 +495,9 @@
}
bool _applicationIsInstalledAndRunning(ApplicationPackage app) {
- bool isInstalled = isAppInstalled(app);
+ final bool isInstalled = isAppInstalled(app);
- bool isRunning = exitsHappy(<String>[
+ final bool isRunning = exitsHappy(<String>[
'/usr/bin/killall',
'Runner',
]);
@@ -515,14 +515,14 @@
Future<Null> _buildAndInstallApplicationBundle(ApplicationPackage app) async {
// Step 1: Build the Xcode project.
// The build mode for the simulator is always debug.
- XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: BuildMode.debug, buildForDevice: false);
+ final XcodeBuildResult buildResult = await buildXcodeProject(app: app, mode: BuildMode.debug, buildForDevice: false);
if (!buildResult.success)
throwToolExit('Could not build the application for the simulator.');
// Step 2: Assert that the Xcode project was successfully built.
- IOSApp iosApp = app;
- Directory bundle = fs.directory(iosApp.simulatorBundlePath);
- bool bundleExists = bundle.existsSync();
+ final IOSApp iosApp = app;
+ final Directory bundle = fs.directory(iosApp.simulatorBundlePath);
+ final bool bundleExists = bundle.existsSync();
if (!bundleExists)
throwToolExit('Could not find the built application bundle at ${bundle.path}.');
@@ -542,7 +542,7 @@
Future<bool> pushFile(
ApplicationPackage app, String localFile, String targetFile) async {
if (p.platform.isMacOS) {
- String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app);
+ final String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app);
runCheckedSync(<String>['cp', localFile, fs.path.join(simulatorHomeDirectory, targetFile)]);
return true;
}
@@ -575,16 +575,16 @@
@override
void clearLogs() {
- File logFile = fs.file(logFilePath);
+ final File logFile = fs.file(logFilePath);
if (logFile.existsSync()) {
- RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE);
+ final RandomAccessFile randomFile = logFile.openSync(mode: FileMode.WRITE);
randomFile.truncateSync(0);
randomFile.closeSync();
}
}
void ensureLogsExists() {
- File logFile = fs.file(logFilePath);
+ final File logFile = fs.file(logFilePath);
if (!logFile.existsSync())
logFile.writeAsBytesSync(<int>[]);
}
@@ -667,10 +667,10 @@
];
String _filterDeviceLine(String string) {
- Match match = _mapRegex.matchAsPrefix(string);
+ final Match match = _mapRegex.matchAsPrefix(string);
if (match != null) {
- String category = match.group(1);
- String content = match.group(2);
+ final String category = match.group(1);
+ final String content = match.group(2);
// Filter out some messages that clearly aren't related to Flutter.
if (string.contains(': could not find icon for representation -> com.apple.'))
@@ -720,7 +720,7 @@
void _onDeviceLine(String line) {
printTrace('[DEVICE LOG] $line');
- Match multi = _lastMessageMultipleRegex.matchAsPrefix(line);
+ final Match multi = _lastMessageMultipleRegex.matchAsPrefix(line);
if (multi != null) {
if (_lastLine != null) {
@@ -737,7 +737,7 @@
}
String _filterSystemLog(String string) {
- Match match = _mapRegex.matchAsPrefix(string);
+ final Match match = _mapRegex.matchAsPrefix(string);
return match == null ? string : '${match.group(1)}: ${match.group(2)}';
}
@@ -746,7 +746,7 @@
if (!_flutterRunnerRegex.hasMatch(line))
return;
- String filteredLine = _filterSystemLog(line);
+ final String filteredLine = _filterSystemLog(line);
if (filteredLine == null)
return;
@@ -760,13 +760,13 @@
}
int compareIosVersions(String v1, String v2) {
- List<int> v1Fragments = v1.split('.').map(int.parse).toList();
- List<int> v2Fragments = v2.split('.').map(int.parse).toList();
+ final List<int> v1Fragments = v1.split('.').map(int.parse).toList();
+ final List<int> v2Fragments = v2.split('.').map(int.parse).toList();
int i = 0;
while(i < v1Fragments.length && i < v2Fragments.length) {
- int v1Fragment = v1Fragments[i];
- int v2Fragment = v2Fragments[i];
+ final int v1Fragment = v1Fragments[i];
+ final int v2Fragment = v2Fragments[i];
if (v1Fragment != v2Fragment)
return v1Fragment.compareTo(v2Fragment);
i++;
@@ -786,11 +786,11 @@
new RegExp(r'com.apple.CoreSimulator.SimDeviceType.iPhone-(\d+)(.*)');
int compareIphoneVersions(String id1, String id2) {
- Match m1 = _iosDeviceTypePattern.firstMatch(id1);
- Match m2 = _iosDeviceTypePattern.firstMatch(id2);
+ final Match m1 = _iosDeviceTypePattern.firstMatch(id1);
+ final Match m2 = _iosDeviceTypePattern.firstMatch(id2);
- int v1 = int.parse(m1[1]);
- int v2 = int.parse(m2[1]);
+ final int v1 = int.parse(m1[1]);
+ final int v2 = int.parse(m2[1]);
if (v1 != v2)
return v1.compareTo(v2);
@@ -798,8 +798,8 @@
// Sorted in the least preferred first order.
const List<String> qualifiers = const <String>['-Plus', '', 's-Plus', 's'];
- int q1 = qualifiers.indexOf(m1[2]);
- int q2 = qualifiers.indexOf(m2[2]);
+ final int q1 = qualifiers.indexOf(m1[2]);
+ final int q2 = qualifiers.indexOf(m2[2]);
return q1.compareTo(q2);
}
diff --git a/packages/flutter_tools/lib/src/ios/xcodeproj.dart b/packages/flutter_tools/lib/src/ios/xcodeproj.dart
index 9cd5087..c32ab15 100644
--- a/packages/flutter_tools/lib/src/ios/xcodeproj.dart
+++ b/packages/flutter_tools/lib/src/ios/xcodeproj.dart
@@ -13,11 +13,11 @@
final RegExp _varExpr = new RegExp(r'\$\((.*)\)');
void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String target) {
- StringBuffer localsBuffer = new StringBuffer();
+ final StringBuffer localsBuffer = new StringBuffer();
localsBuffer.writeln('// This is a generated file; do not edit or check into version control.');
- String flutterRoot = fs.path.normalize(Cache.flutterRoot);
+ final String flutterRoot = fs.path.normalize(Cache.flutterRoot);
localsBuffer.writeln('FLUTTER_ROOT=$flutterRoot');
// This holds because requiresProjectRoot is true for this command
@@ -34,27 +34,27 @@
localsBuffer.writeln('SYMROOT=\${SOURCE_ROOT}/../${getIosBuildDirectory()}');
- String flutterFrameworkDir = fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, mode)));
+ final String flutterFrameworkDir = fs.path.normalize(fs.path.dirname(artifacts.getArtifactPath(Artifact.flutterFramework, TargetPlatform.ios, mode)));
localsBuffer.writeln('FLUTTER_FRAMEWORK_DIR=$flutterFrameworkDir');
if (artifacts is LocalEngineArtifacts) {
- LocalEngineArtifacts localEngineArtifacts = artifacts;
+ final LocalEngineArtifacts localEngineArtifacts = artifacts;
localsBuffer.writeln('LOCAL_ENGINE=${localEngineArtifacts.engineOutPath}');
}
- File localsFile = fs.file(fs.path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'));
+ final File localsFile = fs.file(fs.path.join(projectPath, 'ios', 'Flutter', 'Generated.xcconfig'));
localsFile.createSync(recursive: true);
localsFile.writeAsStringSync(localsBuffer.toString());
}
Map<String, String> getXcodeBuildSettings(String xcodeProjPath, String target) {
- String absProjPath = fs.path.absolute(xcodeProjPath);
- String out = runCheckedSync(<String>[
+ final String absProjPath = fs.path.absolute(xcodeProjPath);
+ final String out = runCheckedSync(<String>[
'/usr/bin/xcodebuild', '-project', absProjPath, '-target', target, '-showBuildSettings'
]);
- Map<String, String> settings = <String, String>{};
+ final Map<String, String> settings = <String, String>{};
for (String line in out.split('\n').where(_settingExpr.hasMatch)) {
- Match match = _settingExpr.firstMatch(line);
+ final Match match = _settingExpr.firstMatch(line);
settings[match[1]] = match[2];
}
return settings;
@@ -64,10 +64,10 @@
/// Substitutes variables in [str] with their values from the specified Xcode
/// project and target.
String substituteXcodeVariables(String str, String xcodeProjPath, String target) {
- Iterable<Match> matches = _varExpr.allMatches(str);
+ final Iterable<Match> matches = _varExpr.allMatches(str);
if (matches.isEmpty)
return str;
- Map<String, String> settings = getXcodeBuildSettings(xcodeProjPath, target);
+ final Map<String, String> settings = getXcodeBuildSettings(xcodeProjPath, target);
return str.replaceAllMapped(_varExpr, (Match m) => settings[m[1]] ?? m[0]);
}
diff --git a/packages/flutter_tools/lib/src/protocol_discovery.dart b/packages/flutter_tools/lib/src/protocol_discovery.dart
index 99dad09..ad839a1 100644
--- a/packages/flutter_tools/lib/src/protocol_discovery.dart
+++ b/packages/flutter_tools/lib/src/protocol_discovery.dart
@@ -50,7 +50,7 @@
/// The [Future] returned by this function will complete when the next service
/// Uri is found.
Future<Uri> nextUri() async {
- Uri deviceUri = await _completer.future.timeout(
+ final Uri deviceUri = await _completer.future.timeout(
const Duration(seconds: 60), onTimeout: () {
throwToolExit('Timeout while attempting to retrieve Uri for $_serviceName');
}
@@ -58,7 +58,7 @@
printTrace('$_serviceName Uri on device: $deviceUri');
Uri hostUri;
if (portForwarder != null) {
- int devicePort = deviceUri.port;
+ final int devicePort = deviceUri.port;
hostPort ??= await findPreferredPort(defaultHostPort);
hostPort = await portForwarder
.forward(devicePort, hostPort: hostPort)
@@ -79,8 +79,8 @@
void _onLine(String line) {
Uri uri;
- String prefix = '$_serviceName listening on ';
- int index = line.indexOf(prefix + 'http://');
+ final String prefix = '$_serviceName listening on ';
+ final int index = line.indexOf(prefix + 'http://');
if (index >= 0) {
try {
uri = Uri.parse(line.substring(index + prefix.length));
diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart
index 87baf60..c2eed76 100644
--- a/packages/flutter_tools/lib/src/resident_runner.dart
+++ b/packages/flutter_tools/lib/src/resident_runner.dart
@@ -108,8 +108,8 @@
}
Future<Null> _screenshot() async {
- Status status = logger.startProgress('Taking screenshot...');
- File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
+ final Status status = logger.startProgress('Taking screenshot...');
+ final File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
try {
if (supportsServiceProtocol && isRunningDebug) {
if (vmService != null)
@@ -133,7 +133,7 @@
}
}
}
- int sizeKB = (await outputFile.length()) ~/ 1024;
+ final int sizeKB = (await outputFile.length()) ~/ 1024;
status.stop();
printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).');
} catch (error) {
@@ -265,7 +265,7 @@
}
} else if (lower == 'o') {
if (supportsServiceProtocol && isRunningDebug) {
- String platform = await _debugRotatePlatform();
+ final String platform = await _debugRotatePlatform();
print('Switched operating system to: $platform');
return true;
}
@@ -287,7 +287,7 @@
}
_processingTerminalRequest = true;
try {
- bool handled = await _commonTerminalInputHandler(command);
+ final bool handled = await _commonTerminalInputHandler(command);
if (!handled)
await handleTerminalCommand(command);
} finally {
@@ -323,18 +323,18 @@
}
Future<int> waitForAppToFinish() async {
- int exitCode = await _finished.future;
+ final int exitCode = await _finished.future;
await cleanupAtFinish();
return exitCode;
}
bool hasDirtyDependencies() {
- DartDependencySetBuilder dartDependencySetBuilder =
+ final DartDependencySetBuilder dartDependencySetBuilder =
new DartDependencySetBuilder(
mainPath, projectRootPath, packagesFilePath);
- DependencyChecker dependencyChecker =
+ final DependencyChecker dependencyChecker =
new DependencyChecker(dartDependencySetBuilder, assetBundle);
- String path = package.packagePath;
+ final String path = package.packagePath;
if (path == null) {
return true;
}
@@ -402,7 +402,7 @@
String findMainDartFile([String target]) {
if (target == null)
target = '';
- String targetPath = fs.path.absolute(target);
+ final String targetPath = fs.path.absolute(target);
if (fs.isDirectorySync(targetPath))
return fs.path.join(targetPath, 'lib', 'main.dart');
else
diff --git a/packages/flutter_tools/lib/src/run_cold.dart b/packages/flutter_tools/lib/src/run_cold.dart
index 874b9e9..6979555 100644
--- a/packages/flutter_tools/lib/src/run_cold.dart
+++ b/packages/flutter_tools/lib/src/run_cold.dart
@@ -83,14 +83,14 @@
if (package == null) {
String message = 'No application found for ${device.platform}.';
- String hint = getMissingPackageHintForPlatform(device.platform);
+ final String hint = getMissingPackageHintForPlatform(device.platform);
if (hint != null)
message += '\n$hint';
printError(message);
return 1;
}
- Stopwatch startTime = new Stopwatch()..start();
+ final Stopwatch startTime = new Stopwatch()..start();
Map<String, dynamic> platformArgs;
if (traceStartup != null)
@@ -98,7 +98,7 @@
await startEchoingDeviceLog(package);
- String modeName = getModeName(debuggingOptions.buildMode);
+ final String modeName = getModeName(debuggingOptions.buildMode);
if (mainPath == null) {
assert(prebuiltMode);
printStatus('Launching ${package.displayName} on ${device.name} in $modeName mode...');
diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart
index 1e9b369..a83bb6f 100644
--- a/packages/flutter_tools/lib/src/run_hot.dart
+++ b/packages/flutter_tools/lib/src/run_hot.dart
@@ -98,7 +98,7 @@
// Already computed.
return true;
}
- DartDependencySetBuilder dartDependencySetBuilder =
+ final DartDependencySetBuilder dartDependencySetBuilder =
new DartDependencySetBuilder(
mainPath, projectRootPath, packagesFilePath);
try {
@@ -129,7 +129,7 @@
if (package == null) {
String message = 'No application found for ${device.platform}.';
- String hint = getMissingPackageHintForPlatform(device.platform);
+ final String hint = getMissingPackageHintForPlatform(device.platform);
if (hint != null)
message += '\n$hint';
printError(message);
@@ -142,11 +142,11 @@
return 1;
}
- Map<String, dynamic> platformArgs = new Map<String, dynamic>();
+ final Map<String, dynamic> platformArgs = new Map<String, dynamic>();
await startEchoingDeviceLog(package);
- String modeName = getModeName(debuggingOptions.buildMode);
+ final String modeName = getModeName(debuggingOptions.buildMode);
printStatus('Launching ${getDisplayPath(mainPath)} on ${device.name} in $modeName mode...');
// Include kernel code
@@ -155,7 +155,7 @@
kernelContent = new DevFSFileContent(fs.file(kernelFilePath));
// Start the application.
- Future<LaunchResult> futureResult = device.startApp(
+ final Future<LaunchResult> futureResult = device.startApp(
package,
debuggingOptions.buildMode,
mainPath: mainPath,
@@ -167,7 +167,7 @@
applicationNeedsRebuild: shouldBuild || hasDirtyDependencies()
);
- LaunchResult result = await futureResult;
+ final LaunchResult result = await futureResult;
if (!result.started) {
printError('Error launching application on ${device.name}.');
@@ -184,7 +184,7 @@
}
try {
- Uri baseUri = await _initDevFS();
+ final Uri baseUri = await _initDevFS();
if (connectionInfoCompleter != null) {
connectionInfoCompleter.complete(
new DebugConnectionInfo(
@@ -198,7 +198,7 @@
printError('Error initializing DevFS: $error');
return 3;
}
- bool devfsResult = await _updateDevFS();
+ final bool devfsResult = await _updateDevFS();
if (!devfsResult) {
printError('Could not perform initial file synchronization.');
return 3;
@@ -229,7 +229,7 @@
await _cleanupDevFS();
await stopEchoingDeviceLog();
await stopApp();
- File benchmarkOutput = fs.file('hot_benchmark.json');
+ final File benchmarkOutput = fs.file('hot_benchmark.json');
benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData));
}
@@ -243,7 +243,7 @@
Future<Null> handleTerminalCommand(String code) async {
final String lower = code.toLowerCase();
if ((lower == 'r') || (code == AnsiTerminal.KEY_F5)) {
- OperationResult result = await restart(fullRestart: code == 'R');
+ final OperationResult result = await restart(fullRestart: code == 'R');
if (!result.isOk) {
// TODO(johnmccutchan): Attempt to determine the number of errors that
// occurred and tighten this message.
@@ -255,7 +255,7 @@
DevFS _devFS;
Future<Uri> _initDevFS() {
- String fsName = fs.path.basename(projectRootPath);
+ final String fsName = fs.path.basename(projectRootPath);
_devFS = new DevFS(vmService,
fsName,
fs.directory(projectRootPath),
@@ -271,13 +271,13 @@
final bool rebuildBundle = assetBundle.needsBuild();
if (rebuildBundle) {
printTrace('Updating assets');
- int result = await assetBundle.build();
+ final int result = await assetBundle.build();
if (result != 0)
return false;
}
- Status devFSStatus = logger.startProgress('Syncing files to device...',
+ final Status devFSStatus = logger.startProgress('Syncing files to device...',
expectSlowOperation: true);
- int bytes = await _devFS.update(progressReporter: progressReporter,
+ final int bytes = await _devFS.update(progressReporter: progressReporter,
bundle: assetBundle,
bundleDirty: rebuildBundle,
fileFilter: _dartDependencies);
@@ -316,16 +316,16 @@
Future<Null> _launchInView(Uri entryUri,
Uri packagesUri,
Uri assetsDirectoryUri) async {
- FlutterView view = vmService.vm.mainView;
+ final FlutterView view = vmService.vm.mainView;
return view.runFromSource(entryUri, packagesUri, assetsDirectoryUri);
}
Future<Null> _launchFromDevFS(ApplicationPackage package,
String mainScript) async {
- String entryUri = fs.path.relative(mainScript, from: projectRootPath);
- Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryUri));
- Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
- Uri deviceAssetsDirectoryUri =
+ final String entryUri = fs.path.relative(mainScript, from: projectRootPath);
+ final Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryUri));
+ final Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
+ final Uri deviceAssetsDirectoryUri =
_devFS.baseUri.resolveUri(fs.path.toUri(getAssetBuildDirectory()));
await _launchInView(deviceEntryUri,
devicePackagesUri,
@@ -333,9 +333,9 @@
}
Future<OperationResult> _restartFromSources() async {
- Stopwatch restartTimer = new Stopwatch();
+ final Stopwatch restartTimer = new Stopwatch();
restartTimer.start();
- bool updatedDevFS = await _updateDevFS();
+ final bool updatedDevFS = await _updateDevFS();
if (!updatedDevFS)
return new OperationResult(1, 'Dart Source Error');
await _launchFromDevFS(package, mainPath);
@@ -374,7 +374,7 @@
@override
Future<OperationResult> restart({ bool fullRestart: false, bool pauseAfterRestart: false }) async {
if (fullRestart) {
- Status status = logger.startProgress('Performing full restart...', progressId: 'hot.restart');
+ final Status status = logger.startProgress('Performing full restart...', progressId: 'hot.restart');
try {
await _restartFromSources();
status.stop();
@@ -385,9 +385,9 @@
rethrow;
}
} else {
- Status status = logger.startProgress('Performing hot reload...', progressId: 'hot.reload');
+ final Status status = logger.startProgress('Performing hot reload...', progressId: 'hot.reload');
try {
- OperationResult result = await _reloadSources(pause: pauseAfterRestart);
+ final OperationResult result = await _reloadSources(pause: pauseAfterRestart);
status.stop();
if (result.isOk)
printStatus("${result.message}.");
@@ -409,7 +409,7 @@
// not be affected, so we resume reporting reload times on the second
// reload.
final bool shouldReportReloadTime = !_runningFromSnapshot;
- Stopwatch reloadTimer = new Stopwatch();
+ final Stopwatch reloadTimer = new Stopwatch();
reloadTimer.start();
Stopwatch devFSTimer;
Stopwatch vmReloadTimer;
@@ -420,7 +420,7 @@
vmReloadTimer = new Stopwatch();
reassembleTimer = new Stopwatch();
}
- bool updatedDevFS = await _updateDevFS();
+ final bool updatedDevFS = await _updateDevFS();
if (benchmarkMode) {
devFSTimer.stop();
// Record time it took to synchronize to DevFS.
@@ -431,12 +431,12 @@
return new OperationResult(1, 'Dart Source Error');
String reloadMessage;
try {
- String entryPath = fs.path.relative(mainPath, from: projectRootPath);
- Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryPath));
- Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
+ final String entryPath = fs.path.relative(mainPath, from: projectRootPath);
+ final Uri deviceEntryUri = _devFS.baseUri.resolveUri(fs.path.toUri(entryPath));
+ final Uri devicePackagesUri = _devFS.baseUri.resolve('.packages');
if (benchmarkMode)
vmReloadTimer.start();
- Map<String, dynamic> reloadReport =
+ final Map<String, dynamic> reloadReport =
await currentView.uiIsolate.reloadSources(
pause: pause,
rootLibUri: deviceEntryUri,
@@ -447,13 +447,13 @@
return new OperationResult(1, 'reload rejected');
} else {
flutterUsage.sendEvent('hot', 'reload');
- int loadedLibraryCount = reloadReport['details']['loadedLibraryCount'];
- int finalLibraryCount = reloadReport['details']['finalLibraryCount'];
+ final int loadedLibraryCount = reloadReport['details']['loadedLibraryCount'];
+ final int finalLibraryCount = reloadReport['details']['finalLibraryCount'];
reloadMessage = 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries';
}
} catch (error, st) {
- int errorCode = error['code'];
- String errorMessage = error['message'];
+ final int errorCode = error['code'];
+ final String errorMessage = error['message'];
if (errorCode == Isolate.kIsolateReloadBarred) {
printError('Unable to hot reload app due to an unrecoverable error in '
'the source code. Please address the error and then use '
diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart
index 7c39287..f8f3a7f 100644
--- a/packages/flutter_tools/lib/src/runner/flutter_command.dart
+++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart
@@ -82,7 +82,7 @@
}
BuildMode getBuildMode() {
- List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']];
+ final List<bool> modeFlags = <bool>[argResults['debug'], argResults['profile'], argResults['release']];
if (modeFlags.where((bool flag) => flag).length > 1)
throw new UsageException('Only one of --debug, --profile, or --release can be specified.', null);
if (argResults['debug'])
@@ -110,14 +110,14 @@
/// so that this method can record and report the overall time to analytics.
@override
Future<Null> run() {
- Stopwatch stopwatch = new Stopwatch()..start();
- UsageTimer analyticsTimer = usagePath == null ? null : flutterUsage.startTimer(name);
+ final Stopwatch stopwatch = new Stopwatch()..start();
+ final UsageTimer analyticsTimer = usagePath == null ? null : flutterUsage.startTimer(name);
if (flutterUsage.isFirstRun)
flutterUsage.printUsage();
return verifyThenRunCommand().whenComplete(() {
- int ms = stopwatch.elapsedMilliseconds;
+ final int ms = stopwatch.elapsedMilliseconds;
printTrace("'flutter $name' took ${ms}ms.");
analyticsTimer?.finish();
});
@@ -141,7 +141,7 @@
setupApplicationPackages();
- String commandPath = usagePath;
+ final String commandPath = usagePath;
if (commandPath != null)
flutterUsage.sendCommand(usagePath);
@@ -234,14 +234,14 @@
}
if (_usesTargetOption) {
- String targetPath = targetFile;
+ final String targetPath = targetFile;
if (!fs.isFileSync(targetPath))
throw new ToolExit('Target file "$targetPath" not found.');
}
// Validate the current package map only if we will not be running "pub get" later.
if (!(_usesPubOption && argResults['pub'])) {
- String error = new PackageMap(PackageMap.globalPackagesPath).checkValid();
+ final String error = new PackageMap(PackageMap.globalPackagesPath).checkValid();
if (error != null)
throw new ToolExit(error);
}
diff --git a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
index 6bfc8f2..51444d6 100644
--- a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
+++ b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
@@ -130,7 +130,7 @@
try {
if (platform.script.scheme == 'data')
return '../..'; // we're running as a test
- String script = platform.script.toFilePath();
+ final String script = platform.script.toFilePath();
if (fs.path.basename(script) == kSnapshotFileName)
return fs.path.dirname(fs.path.dirname(fs.path.dirname(script)));
if (fs.path.basename(script) == kFlutterToolsScriptFileName)
@@ -171,14 +171,14 @@
if (globalResults['bug-report']) {
// --bug-report implies --record-to=<tmp_path>
- Directory tmp = await const LocalFileSystem()
+ final Directory tmp = await const LocalFileSystem()
.systemTempDirectory
.createTemp('flutter_tools_');
recordTo = tmp.path;
// Record the arguments that were used to invoke this runner.
- File manifest = tmp.childFile('MANIFEST.txt');
- StringBuffer buffer = new StringBuffer()
+ final File manifest = tmp.childFile('MANIFEST.txt');
+ final StringBuffer buffer = new StringBuffer()
..writeln('# arguments')
..writeln(globalResults.arguments)
..writeln()
@@ -188,7 +188,7 @@
// ZIP the recording up once the recording has been serialized.
addShutdownHook(() async {
- File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip');
+ final File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip');
os.zip(tmp, zipFile);
printStatus(
'Bug report written to ${zipFile.basename}.\n'
@@ -244,7 +244,7 @@
deviceManager.specifiedDeviceId = globalResults['device-id'];
// Set up the tooling configuration.
- String enginePath = _findEnginePath(globalResults);
+ final String enginePath = _findEnginePath(globalResults);
if (enginePath != null) {
Artifacts.useLocalEngine(enginePath, _findEngineBuildPath(globalResults, enginePath));
}
@@ -272,10 +272,10 @@
if (engineSourcePath == null && globalResults['local-engine'] != null) {
try {
- Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName];
+ final Uri engineUri = new PackageMap(PackageMap.globalPackagesPath).map[kFlutterEnginePackageName];
if (engineUri != null) {
engineSourcePath = fs.path.dirname(fs.path.dirname(fs.path.dirname(fs.path.dirname(engineUri.path))));
- bool dirExists = fs.isDirectorySync(fs.path.join(engineSourcePath, 'out'));
+ final bool dirExists = fs.isDirectorySync(fs.path.join(engineSourcePath, 'out'));
if (engineSourcePath == '/' || engineSourcePath.isEmpty || !dirExists)
engineSourcePath = null;
}
@@ -312,7 +312,7 @@
throw new ProcessExit(2);
}
- String engineBuildPath = fs.path.normalize(fs.path.join(enginePath, 'out', localEngine));
+ final String engineBuildPath = fs.path.normalize(fs.path.join(enginePath, 'out', localEngine));
if (!fs.isDirectorySync(engineBuildPath)) {
printError('No Flutter engine build found at $engineBuildPath.');
throw new ProcessExit(2);
@@ -385,7 +385,7 @@
break;
}
- String parent = fs.path.dirname(directory);
+ final String parent = fs.path.dirname(directory);
if (parent == directory)
break;
directory = parent;
@@ -393,13 +393,13 @@
// Check that the flutter running is that same as the one referenced in the pubspec.
if (fs.isFileSync(kPackagesFileName)) {
- PackageMap packageMap = new PackageMap(kPackagesFileName);
- Uri flutterUri = packageMap.map['flutter'];
+ final PackageMap packageMap = new PackageMap(kPackagesFileName);
+ final Uri flutterUri = packageMap.map['flutter'];
if (flutterUri != null && (flutterUri.scheme == 'file' || flutterUri.scheme == '')) {
// .../flutter/packages/flutter/lib
- Uri rootUri = flutterUri.resolve('../../..');
- String flutterPath = fs.path.normalize(fs.file(rootUri).absolute.path);
+ final Uri rootUri = flutterUri.resolve('../../..');
+ final String flutterPath = fs.path.normalize(fs.file(rootUri).absolute.path);
if (!fs.isDirectorySync(flutterPath)) {
printError(
diff --git a/packages/flutter_tools/lib/src/services.dart b/packages/flutter_tools/lib/src/services.dart
index bf4da51..00bd107 100644
--- a/packages/flutter_tools/lib/src/services.dart
+++ b/packages/flutter_tools/lib/src/services.dart
@@ -19,7 +19,7 @@
printTrace("Looking for YAML at '$path'");
if (!fs.isFileSync(path))
return null;
- String manifestString = fs.file(path).readAsStringSync();
+ final String manifestString = fs.file(path).readAsStringSync();
return loadYaml(manifestString);
}
@@ -51,8 +51,8 @@
}
for (String service in manifest['services']) {
- String serviceRoot = packageMap[service].path;
- dynamic serviceConfig = _loadYamlFile('$serviceRoot/$_kFlutterServicesManifestPath');
+ final String serviceRoot = packageMap[service].path;
+ final dynamic serviceConfig = _loadYamlFile('$serviceRoot/$_kFlutterServicesManifestPath');
if (serviceConfig == null) {
printStatus('No $_kFlutterServicesManifestPath found for service "$serviceRoot"; skipping.');
continue;
@@ -99,14 +99,14 @@
File generateServiceDefinitions(
String dir, List<Map<String, String>> servicesIn
) {
- List<Map<String, String>> services =
+ final List<Map<String, String>> services =
servicesIn.map((Map<String, String> service) => <String, String>{
'name': service['name'],
'class': service['android-class']
}).toList();
- Map<String, dynamic> json = <String, dynamic>{ 'services': services };
- File servicesFile = fs.file(fs.path.join(dir, 'services.json'));
+ final Map<String, dynamic> json = <String, dynamic>{ 'services': services };
+ final File servicesFile = fs.file(fs.path.join(dir, 'services.json'));
servicesFile.writeAsStringSync(JSON.encode(json), mode: FileMode.WRITE, flush: true);
return servicesFile;
}
diff --git a/packages/flutter_tools/lib/src/template.dart b/packages/flutter_tools/lib/src/template.dart
index 958a688..a1c3197 100644
--- a/packages/flutter_tools/lib/src/template.dart
+++ b/packages/flutter_tools/lib/src/template.dart
@@ -30,7 +30,7 @@
return;
}
- List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
+ final List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
for (FileSystemEntity entity in templateFiles) {
if (entity is! File) {
@@ -38,7 +38,7 @@
continue;
}
- String relativePath = fs.path.relative(entity.path,
+ final String relativePath = fs.path.relative(entity.path,
from: baseDir.absolute.path);
if (relativePath.contains(_kTemplateExtension)) {
@@ -52,7 +52,7 @@
factory Template.fromName(String name) {
// All named templates are placed in the 'templates' directory
- Directory templateDir = _templateDirectoryInPackage(name);
+ final Directory templateDir = _templateDirectoryInPackage(name);
return new Template(templateDir, templateDir);
}
@@ -67,7 +67,7 @@
destination.createSync(recursive: true);
int fileCount = 0;
- String destinationDirPath = destination.absolute.path;
+ final String destinationDirPath = destination.absolute.path;
_templateFilePaths.forEach((String relativeDestPath, String absoluteSrcPath) {
String finalDestinationPath = fs.path
@@ -76,8 +76,8 @@
.replaceAll(_kTemplateExtension, '');
if (projectName != null)
finalDestinationPath = finalDestinationPath.replaceAll('projectName', projectName);
- File finalDestinationFile = fs.file(finalDestinationPath);
- String relativePathForLogging = fs.path.relative(finalDestinationFile.path);
+ final File finalDestinationFile = fs.file(finalDestinationPath);
+ final String relativePathForLogging = fs.path.relative(finalDestinationFile.path);
// Step 1: Check if the file needs to be overwritten.
@@ -97,7 +97,7 @@
fileCount++;
finalDestinationFile.createSync(recursive: true);
- File sourceFile = fs.file(absoluteSrcPath);
+ final File sourceFile = fs.file(absoluteSrcPath);
// Step 2: If the absolute paths ends with a 'copy.tmpl', this file does
// not need mustache rendering but needs to be directly copied.
@@ -112,8 +112,8 @@
// rendering via mustache.
if (sourceFile.path.endsWith(_kTemplateExtension)) {
- String templateContents = sourceFile.readAsStringSync();
- String renderedContents = new mustache.Template(templateContents).renderString(context);
+ final String templateContents = sourceFile.readAsStringSync();
+ final String renderedContents = new mustache.Template(templateContents).renderString(context);
finalDestinationFile.writeAsStringSync(renderedContents);
@@ -131,7 +131,7 @@
}
Directory _templateDirectoryInPackage(String name) {
- String templatesDir = fs.path.join(Cache.flutterRoot,
+ final String templatesDir = fs.path.join(Cache.flutterRoot,
'packages', 'flutter_tools', 'templates');
return fs.directory(fs.path.join(templatesDir, name));
}
diff --git a/packages/flutter_tools/lib/src/test/coverage_collector.dart b/packages/flutter_tools/lib/src/test/coverage_collector.dart
index 44fa133..78ff476 100644
--- a/packages/flutter_tools/lib/src/test/coverage_collector.dart
+++ b/packages/flutter_tools/lib/src/test/coverage_collector.dart
@@ -32,7 +32,7 @@
assert(process != null);
assert(port != null);
- int pid = process.pid;
+ final int pid = process.pid;
int exitCode;
process.exitCode.then<Null>((int code) {
exitCode = code;
@@ -68,12 +68,12 @@
if (_globalHitmap == null)
return null;
if (formatter == null) {
- coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath);
- String packagePath = fs.currentDirectory.path;
- List<String> reportOn = <String>[fs.path.join(packagePath, 'lib')];
+ final coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath);
+ final String packagePath = fs.currentDirectory.path;
+ final List<String> reportOn = <String>[fs.path.join(packagePath, 'lib')];
formatter = new coverage.LcovFormatter(resolver, reportOn: reportOn, basePath: packagePath);
}
- String result = await formatter.format(_globalHitmap);
+ final String result = await formatter.format(_globalHitmap);
_globalHitmap = null;
return result;
}
diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart
index 5fafa71..eff482a 100644
--- a/packages/flutter_tools/lib/src/test/flutter_platform.dart
+++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart
@@ -102,20 +102,20 @@
if (_testCount > 0)
throwToolExit('installHook() was called with an observatory port, a diagnostic port, both, or debugger mode enabled, but then more than one test suite was run.');
}
- int ourTestCount = _testCount;
+ final int ourTestCount = _testCount;
_testCount += 1;
- StreamController<dynamic> localController = new StreamController<dynamic>();
- StreamController<dynamic> remoteController = new StreamController<dynamic>();
- Completer<Null> testCompleteCompleter = new Completer<Null>();
- _FlutterPlatformStreamSinkWrapper<dynamic> remoteSink = new _FlutterPlatformStreamSinkWrapper<dynamic>(
+ final StreamController<dynamic> localController = new StreamController<dynamic>();
+ final StreamController<dynamic> remoteController = new StreamController<dynamic>();
+ final Completer<Null> testCompleteCompleter = new Completer<Null>();
+ final _FlutterPlatformStreamSinkWrapper<dynamic> remoteSink = new _FlutterPlatformStreamSinkWrapper<dynamic>(
remoteController.sink,
testCompleteCompleter.future,
);
- StreamChannel<dynamic> localChannel = new StreamChannel<dynamic>.withGuarantees(
+ final StreamChannel<dynamic> localChannel = new StreamChannel<dynamic>.withGuarantees(
remoteController.stream,
localController.sink,
);
- StreamChannel<dynamic> remoteChannel = new StreamChannel<dynamic>.withGuarantees(
+ final StreamChannel<dynamic> remoteChannel = new StreamChannel<dynamic>.withGuarantees(
localController.stream,
remoteSink,
);
@@ -135,12 +135,12 @@
controller.sink.done.whenComplete(() { controllerSinkClosed = true; });
// Prepare our WebSocket server to talk to the engine subproces.
- HttpServer server = await HttpServer.bind(_kHost, 0);
+ final HttpServer server = await HttpServer.bind(_kHost, 0);
finalizers.add(() async {
printTrace('test $ourTestCount: shutting down test harness socket server');
await server.close(force: true);
});
- Completer<WebSocket> webSocket = new Completer<WebSocket>();
+ final Completer<WebSocket> webSocket = new Completer<WebSocket>();
server.listen(
(HttpRequest request) {
webSocket.complete(WebSocketTransformer.upgrade(request));
@@ -159,14 +159,14 @@
);
// Prepare a temporary directory to store the Dart file that will talk to us.
- Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('dart_test_listener');
+ final Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('dart_test_listener');
finalizers.add(() async {
printTrace('test $ourTestCount: deleting temporary directory');
temporaryDirectory.deleteSync(recursive: true);
});
// Prepare the Dart file that will talk to us and start the test.
- File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart');
+ final File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart');
listenerFile.createSync();
listenerFile.writeAsStringSync(_generateTestMain(
testUrl: fs.path.toUri(fs.path.absolute(testPath)).toString(),
@@ -175,7 +175,7 @@
// Start the engine subprocess.
printTrace('test $ourTestCount: starting shell process');
- Process process = await _startProcess(
+ final Process process = await _startProcess(
shellPath,
listenerFile.path,
packages: PackageMap.globalPackagesPath,
@@ -194,13 +194,13 @@
if (!controllerSinkClosed && exitCode != -15) { // ProcessSignal.SIGTERM
// We expect SIGTERM (15) because we tried to terminate it.
// It's negative because signals are returned as negative exit codes.
- String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'after tests finished'), testPath, shellPath);
+ final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'after tests finished'), testPath, shellPath);
controller.sink.addError(message);
}
}
});
- Completer<Null> timeout = new Completer<Null>();
+ final Completer<Null> timeout = new Completer<Null>();
// Pipe stdout and stderr from the subprocess to our printStatus console.
// We also keep track of what observatory port the engine used, if any.
@@ -232,7 +232,7 @@
// The local test harness could get bored of us.
printTrace('test $ourTestCount: awaiting initial result for pid ${process.pid}');
- _InitialResult initialResult = await Future.any(<Future<_InitialResult>>[
+ final _InitialResult initialResult = await Future.any(<Future<_InitialResult>>[
process.exitCode.then<_InitialResult>((int exitCode) => _InitialResult.crashed),
timeout.future.then<_InitialResult>((Null _) => _InitialResult.timedOut),
new Future<_InitialResult>.delayed(_kTestProcessTimeout, () => _InitialResult.timedOut),
@@ -242,9 +242,9 @@
switch (initialResult) {
case _InitialResult.crashed:
printTrace('test $ourTestCount: process with pid ${process.pid} crashed before connecting to test harness');
- int exitCode = await process.exitCode;
+ final int exitCode = await process.exitCode;
subprocessActive = false;
- String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before connecting to test harness'), testPath, shellPath);
+ final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before connecting to test harness'), testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
@@ -252,7 +252,7 @@
break;
case _InitialResult.timedOut:
printTrace('test $ourTestCount: timed out waiting for process with pid ${process.pid} to connect to test harness');
- String message = _getErrorMessage('Test never connected to test harness.', testPath, shellPath);
+ final String message = _getErrorMessage('Test never connected to test harness.', testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
@@ -260,10 +260,10 @@
break;
case _InitialResult.connected:
printTrace('test $ourTestCount: process with pid ${process.pid} connected to test harness');
- WebSocket testSocket = await webSocket.future;
+ final WebSocket testSocket = await webSocket.future;
- Completer<Null> harnessDone = new Completer<Null>();
- StreamSubscription<dynamic> harnessToTest = controller.stream.listen(
+ final Completer<Null> harnessDone = new Completer<Null>();
+ final StreamSubscription<dynamic> harnessToTest = controller.stream.listen(
(dynamic event) { testSocket.add(JSON.encode(event)); },
onDone: () { harnessDone.complete(); },
onError: (dynamic error, dynamic stack) {
@@ -279,8 +279,8 @@
cancelOnError: true,
);
- Completer<Null> testDone = new Completer<Null>();
- StreamSubscription<dynamic> testToHarness = testSocket.listen(
+ final Completer<Null> testDone = new Completer<Null>();
+ final StreamSubscription<dynamic> testToHarness = testSocket.listen(
(dynamic encodedEvent) {
assert(encodedEvent is String); // we shouldn't ever get binary messages
controller.sink.add(JSON.decode(encodedEvent));
@@ -300,7 +300,7 @@
);
printTrace('test $ourTestCount: awaiting test result for pid ${process.pid}');
- _TestResult testResult = await Future.any(<Future<_TestResult>>[
+ final _TestResult testResult = await Future.any(<Future<_TestResult>>[
process.exitCode.then<_TestResult>((int exitCode) { return _TestResult.crashed; }),
harnessDone.future.then<_TestResult>((Null _) { return _TestResult.harnessBailed; }),
testDone.future.then<_TestResult>((Null _) { return _TestResult.testBailed; }),
@@ -312,9 +312,9 @@
switch (testResult) {
case _TestResult.crashed:
printTrace('test $ourTestCount: process with pid ${process.pid} crashed');
- int exitCode = await process.exitCode;
+ final int exitCode = await process.exitCode;
subprocessActive = false;
- String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before test harness closed its WebSocket'), testPath, shellPath);
+ final String message = _getErrorMessage(_getExitCodeMessage(exitCode, 'before test harness closed its WebSocket'), testPath, shellPath);
controller.sink.addError(message);
controller.sink.close();
printTrace('test $ourTestCount: waiting for controller sink to close');
@@ -414,13 +414,13 @@
if (_cachedFontConfig != null)
return _cachedFontConfig;
- StringBuffer sb = new StringBuffer();
+ final StringBuffer sb = new StringBuffer();
sb.writeln('<fontconfig>');
sb.writeln(' <dir>${cache.getCacheArtifacts().path}</dir>');
sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>');
sb.writeln('</fontconfig>');
- Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts');
+ final Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts');
_cachedFontConfig = fs.file('${fontsDir.path}/fonts.conf');
_cachedFontConfig.createSync();
_cachedFontConfig.writeAsStringSync(sb.toString());
@@ -438,7 +438,7 @@
}) {
assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable.
assert(!startPaused || enableObservatory);
- List<String> command = <String>[executable];
+ final List<String> command = <String>[executable];
if (enableObservatory) {
// Some systems drive the _FlutterPlatform class in an unusual way, where
// only one test file is processed at a time, and the operating
@@ -467,7 +467,7 @@
testPath,
]);
printTrace(command.join(' '));
- Map<String, String> environment = <String, String>{
+ final Map<String, String> environment = <String, String>{
'FLUTTER_TEST': 'true',
'FONTCONFIG_FILE': _fontConfigFile.path,
};
@@ -497,7 +497,7 @@
} else if (line.startsWith(observatoryPortString)) {
printTrace('Shell: $line');
try {
- int port = int.parse(line.substring(observatoryPortString.length, line.length - 1)); // last character is a slash
+ final int port = int.parse(line.substring(observatoryPortString.length, line.length - 1)); // last character is a slash
if (reportObservatoryPort != null)
reportObservatoryPort(port);
} catch (error) {
diff --git a/packages/flutter_tools/lib/src/usage.dart b/packages/flutter_tools/lib/src/usage.dart
index 2f4b5ec..4674964 100644
--- a/packages/flutter_tools/lib/src/usage.dart
+++ b/packages/flutter_tools/lib/src/usage.dart
@@ -20,7 +20,7 @@
class Usage {
/// Create a new Usage instance; [versionOverride] is used for testing.
Usage({ String settingsName: 'flutter', String versionOverride }) {
- String version = versionOverride ?? FlutterVersion.getVersionString(whitelistBranchName: true);
+ final String version = versionOverride ?? FlutterVersion.getVersionString(whitelistBranchName: true);
_analytics = new AnalyticsIO(_kFlutterUA, settingsName, version);
bool runningOnCI = false;
diff --git a/packages/flutter_tools/lib/src/version.dart b/packages/flutter_tools/lib/src/version.dart
index 3bdd2e7..cf8230d 100644
--- a/packages/flutter_tools/lib/src/version.dart
+++ b/packages/flutter_tools/lib/src/version.dart
@@ -19,9 +19,9 @@
FlutterVersion(this.flutterRoot) {
_channel = _runGit('git rev-parse --abbrev-ref --symbolic @{u}');
- int slash = _channel.indexOf('/');
+ final int slash = _channel.indexOf('/');
if (slash != -1) {
- String remote = _channel.substring(0, slash);
+ final String remote = _channel.substring(0, slash);
_repositoryUrl = _runGit('git ls-remote --get-url $remote');
_channel = _channel.substring(slash + 1);
} else if (_channel.isEmpty) {
@@ -59,10 +59,10 @@
@override
String toString() {
- String flutterText = 'Flutter • channel $channel • ${repositoryUrl == null ? 'unknown source' : repositoryUrl}';
- String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
- String engineText = 'Engine • revision $engineRevisionShort';
- String toolsText = 'Tools • Dart $dartSdkVersion';
+ final String flutterText = 'Flutter • channel $channel • ${repositoryUrl == null ? 'unknown source' : repositoryUrl}';
+ final String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
+ final String engineText = 'Engine • revision $engineRevisionShort';
+ final String toolsText = 'Tools • Dart $dartSdkVersion';
// Flutter • channel master • https://github.com/flutter/flutter.git
// Framework • revision 2259c59be8 • 19 minutes ago • 2016-08-15 22:51:40
@@ -102,7 +102,7 @@
}
String _runSync(List<String> command, String cwd) {
- ProcessResult results = processManager.runSync(command, workingDirectory: cwd);
+ final ProcessResult results = processManager.runSync(command, workingDirectory: cwd);
return results.exitCode == 0 ? results.stdout.trim() : '';
}
diff --git a/packages/flutter_tools/lib/src/vmservice.dart b/packages/flutter_tools/lib/src/vmservice.dart
index 4355164..574fe76 100644
--- a/packages/flutter_tools/lib/src/vmservice.dart
+++ b/packages/flutter_tools/lib/src/vmservice.dart
@@ -54,9 +54,9 @@
/// non-empty directory as long as there is no collision with the
/// `"vmservice"` subdirectory.
static void enableRecordingConnection(String location) {
- Directory dir = getRecordingSink(location, _kRecordingType);
+ final Directory dir = getRecordingSink(location, _kRecordingType);
_openChannel = (Uri uri) {
- StreamChannel<String> delegate = _defaultOpenChannel(uri);
+ final StreamChannel<String> delegate = _defaultOpenChannel(uri);
return new RecordingVMServiceChannel(delegate, dir);
};
}
@@ -67,7 +67,7 @@
/// activity has been recorded (i.e. the result of having been previously
/// passed to [enableRecordingConnection]), or a [ToolExit] will be thrown.
static void enableReplayConnection(String location) {
- Directory dir = getReplaySource(location, _kRecordingType);
+ final Directory dir = getReplaySource(location, _kRecordingType);
_openChannel = (Uri uri) => new ReplayVMServiceChannel(dir);
}
@@ -79,9 +79,9 @@
Uri httpUri, {
Duration requestTimeout: kDefaultRequestTimeout,
}) {
- Uri wsUri = httpUri.replace(scheme: 'ws', path: fs.path.join(httpUri.path, 'ws'));
- StreamChannel<String> channel = _openChannel(wsUri);
- rpc.Peer peer = new rpc.Peer.withoutJson(jsonDocument.bind(channel));
+ final Uri wsUri = httpUri.replace(scheme: 'ws', path: fs.path.join(httpUri.path, 'ws'));
+ final StreamChannel<String> channel = _openChannel(wsUri);
+ final rpc.Peer peer = new rpc.Peer.withoutJson(jsonDocument.bind(channel));
return new VMService._(peer, httpUri, wsUri, requestTimeout);
}
@@ -144,7 +144,7 @@
ServiceEvent event;
if (eventIsolate != null) {
// getFromMap creates the Isolate if necessary.
- Isolate isolate = vm.getFromMap(eventIsolate);
+ final Isolate isolate = vm.getFromMap(eventIsolate);
event = new ServiceObject._fromMap(isolate, eventData);
if (event.kind == ServiceEvent.kIsolateExit) {
vm._isolateCache.remove(isolate.id);
@@ -217,7 +217,7 @@
void _upgradeList(List<dynamic> list, ServiceObjectOwner owner) {
for (int i = 0; i < list.length; i++) {
- dynamic v = list[i];
+ final dynamic v = list[i];
if ((v is Map<String, dynamic>) && _isServiceMap(v)) {
list[i] = owner.getFromMap(v);
} else if (v is List) {
@@ -243,7 +243,7 @@
if (!_isServiceMap(map))
throw new VMServiceObjectLoadError("Expected a service map", map);
- String type = _stripRef(map['type']);
+ final String type = _stripRef(map['type']);
ServiceObject serviceObject;
switch (type) {
@@ -310,7 +310,7 @@
/// Fetch this object from vmService and return the response directly.
Future<Map<String, dynamic>> _fetchDirect() {
- Map<String, dynamic> params = <String, dynamic>{
+ final Map<String, dynamic> params = <String, dynamic>{
'objectId': id,
};
return _owner.isolate.invokeRpcRaw('getObject', params: params);
@@ -319,22 +319,22 @@
Future<ServiceObject> _inProgressReload;
/// Reload the service object (if possible).
Future<ServiceObject> reload() async {
- bool hasId = (id != null) && (id != '');
- bool isVM = this is VM;
+ final bool hasId = (id != null) && (id != '');
+ final bool isVM = this is VM;
// We should always reload the VM.
// We can't reload objects without an id.
// We shouldn't reload an immutable and already loaded object.
- bool skipLoad = !isVM && (!hasId || (immutable && loaded));
+ final bool skipLoad = !isVM && (!hasId || (immutable && loaded));
if (skipLoad) {
return this;
}
if (_inProgressReload == null) {
- Completer<ServiceObject> completer = new Completer<ServiceObject>();
+ final Completer<ServiceObject> completer = new Completer<ServiceObject>();
_inProgressReload = completer.future;
try {
- Map<String, dynamic> response = await _fetchDirect();
+ final Map<String, dynamic> response = await _fetchDirect();
if (_stripRef(response['type']) == 'Sentinel') {
// An object may have been collected.
completer.complete(new ServiceObject._fromMap(owner, response));
@@ -515,8 +515,8 @@
final Map<String, FlutterView> _viewCache = new Map<String, FlutterView>();
int _compareIsolates(Isolate a, Isolate b) {
- DateTime aStart = a.startTime;
- DateTime bStart = b.startTime;
+ final DateTime aStart = a.startTime;
+ final DateTime bStart = b.startTime;
if (aStart == null) {
if (bStart == null) {
return 0;
@@ -531,7 +531,7 @@
}
void _buildIsolateList() {
- List<Isolate> isolateList = _isolateCache.values.toList();
+ final List<Isolate> isolateList = _isolateCache.values.toList();
isolateList.sort(_compareIsolates);
isolates.clear();
isolates.addAll(isolateList);
@@ -539,11 +539,11 @@
void _removeDeadIsolates(List<Isolate> newIsolates) {
// Build a set of new isolates.
- Set<String> newIsolateSet = new Set<String>();
+ final Set<String> newIsolateSet = new Set<String>();
newIsolates.forEach((Isolate iso) => newIsolateSet.add(iso.id));
// Remove any old isolates which no longer exist.
- List<String> toRemove = <String>[];
+ final List<String> toRemove = <String>[];
_isolateCache.forEach((String id, _) {
if (!newIsolateSet.contains(id)) {
toRemove.add(id);
@@ -558,14 +558,14 @@
if (map == null) {
return null;
}
- String type = _stripRef(map['type']);
+ final String type = _stripRef(map['type']);
if (type == 'VM') {
// Update this VM object.
update(map);
return this;
}
- String mapId = map['id'];
+ final String mapId = map['id'];
switch (type) {
case 'Isolate': {
@@ -627,7 +627,7 @@
assert(params != null);
timeout ??= _vmService._requestTimeout;
try {
- Map<String, dynamic> result = await _vmService
+ final Map<String, dynamic> result = await _vmService
._sendRequest(method, params)
.timeout(timeout);
return result;
@@ -647,14 +647,14 @@
Map<String, dynamic> params: const <String, dynamic>{},
Duration timeout,
}) async {
- Map<String, dynamic> response = await invokeRpcRaw(
+ final Map<String, dynamic> response = await invokeRpcRaw(
method,
params: params,
timeout: timeout,
);
- ServiceObject serviceObject = new ServiceObject._fromMap(this, response);
+ final ServiceObject serviceObject = new ServiceObject._fromMap(this, response);
if ((serviceObject != null) && (serviceObject._canCache)) {
- String serviceObjectId = serviceObject.id;
+ final String serviceObjectId = serviceObject.id;
_cache.putIfAbsent(serviceObjectId, () => serviceObject);
}
return serviceObject;
@@ -689,7 +689,7 @@
// Read one file from a file system.
Future<List<int>> readDevFSFile(String fsName, String path) async {
- Map<String, dynamic> response = await invokeRpcRaw(
+ final Map<String, dynamic> response = await invokeRpcRaw(
'_readDevFSFile',
params: <String, dynamic>{
'fsName': fsName,
@@ -774,13 +774,13 @@
if (map == null) {
return null;
}
- String mapType = _stripRef(map['type']);
+ final String mapType = _stripRef(map['type']);
if (mapType == 'Isolate') {
// There are sometimes isolate refs in ServiceEvents.
return vm.getFromMap(map);
}
- String mapId = map['id'];
+ final String mapId = map['id'];
ServiceObject serviceObject = (mapId != null) ? _cache[mapId] : null;
if (serviceObject != null) {
serviceObject.update(map);
@@ -827,7 +827,7 @@
return;
_loaded = true;
- int startTimeMillis = map['startTime'];
+ final int startTimeMillis = map['startTime'];
startTime = new DateTime.fromMillisecondsSinceEpoch(startTimeMillis);
_upgradeCollection(map, this);
@@ -842,7 +842,7 @@
Uri rootLibUri,
Uri packagesUri}) async {
try {
- Map<String, dynamic> arguments = <String, dynamic>{
+ final Map<String, dynamic> arguments = <String, dynamic>{
'pause': pause
};
// TODO(goderbauer): Transfer Uri (instead of file path) when remote end supports it.
@@ -853,7 +853,7 @@
if (packagesUri != null) {
arguments['packagesUri'] = packagesUri.toFilePath(windows: false);
}
- Map<String, dynamic> response = await invokeRpcRaw('_reloadSources', params: arguments);
+ final Map<String, dynamic> response = await invokeRpcRaw('_reloadSources', params: arguments);
return response;
} on rpc.RpcException catch(e) {
return new Future<Map<String, dynamic>>.error(<String, dynamic>{
@@ -952,7 +952,7 @@
}
Future<Null> flutterPlatformOverride([String platform]) async {
- Map<String, String> result = await invokeFlutterExtensionRpcRaw(
+ final Map<String, String> result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.platformOverride',
params: platform != null ? <String, dynamic>{ 'value': platform } : <String, String>{},
timeout: const Duration(seconds: 5),
diff --git a/packages/flutter_tools/lib/src/vmservice_record_replay.dart b/packages/flutter_tools/lib/src/vmservice_record_replay.dart
index 5e458b4..af948e0 100644
--- a/packages/flutter_tools/lib/src/vmservice_record_replay.dart
+++ b/packages/flutter_tools/lib/src/vmservice_record_replay.dart
@@ -35,8 +35,8 @@
// purpose other than to make the serialized format more human-readable.
_messages.sort();
- File file = _getManifest(location);
- String json = new JsonEncoder.withIndent(' ').convert(_messages);
+ final File file = _getManifest(location);
+ final String json = new JsonEncoder.withIndent(' ').convert(_messages);
await file.writeAsString(json, flush: true);
}, ShutdownStage.SERIALIZE_RECORDING);
}
@@ -83,7 +83,7 @@
@override
int compareTo(_Message other) {
- int result = id.compareTo(other.id);
+ final int result = id.compareTo(other.id);
if (result != 0) {
return result;
} else if (type == _kRequest) {
@@ -210,12 +210,12 @@
: _transactions = _loadTransactions(location);
static Map<int, _Transaction> _loadTransactions(Directory location) {
- File file = _getManifest(location);
- String json = file.readAsStringSync();
- Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage);
- Map<int, _Transaction> transactions = <int, _Transaction>{};
+ final File file = _getManifest(location);
+ final String json = file.readAsStringSync();
+ final Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage);
+ final Map<int, _Transaction> transactions = <int, _Transaction>{};
for (_Message message in messages) {
- _Transaction transaction =
+ final _Transaction transaction =
transactions.putIfAbsent(message.id, () => new _Transaction());
if (message.type == _kRequest) {
assert(transaction.request == null);
@@ -235,7 +235,7 @@
void send(_Request request) {
if (!_transactions.containsKey(request.id))
throw new ArgumentError('No matching invocation found');
- _Transaction transaction = _transactions.remove(request.id);
+ final _Transaction transaction = _transactions.remove(request.id);
// TODO(tvolkert): validate that `transaction.request` matches `request`
if (transaction.response == null) {
// This signals that when we were recording, the VM shut down before
@@ -295,6 +295,6 @@
}
File _getManifest(Directory location) {
- String path = location.fileSystem.path.join(location.path, _kManifest);
+ final String path = location.fileSystem.path.join(location.path, _kManifest);
return location.fileSystem.file(path);
}
diff --git a/packages/flutter_tools/lib/src/zip.dart b/packages/flutter_tools/lib/src/zip.dart
index 463f296..a7b1161 100644
--- a/packages/flutter_tools/lib/src/zip.dart
+++ b/packages/flutter_tools/lib/src/zip.dart
@@ -31,7 +31,7 @@
@override
Future<Null> createZip(File outFile, Directory zipBuildDir) async {
- Archive archive = new Archive();
+ final Archive archive = new Archive();
final Completer<Null> finished = new Completer<Null>();
int count = entries.length;
@@ -45,7 +45,7 @@
});
await finished.future;
- List<int> zipData = new ZipEncoder().encode(archive);
+ final List<int> zipData = new ZipEncoder().encode(archive);
await outFile.writeAsBytes(zipData);
}
}
@@ -57,7 +57,7 @@
Future<Null> createZip(File outFile, Directory zipBuildDir) async {
// If there are no assets, then create an empty zip file.
if (entries.isEmpty) {
- List<int> zipData = new ZipEncoder().encode(new Archive());
+ final List<int> zipData = new ZipEncoder().encode(new Archive());
await outFile.writeAsBytes(zipData);
return;
}
@@ -73,7 +73,7 @@
int count = entries.length;
entries.forEach((String archivePath, DevFSContent content) {
content.contentsAsBytes().then<Null>((List<int> data) {
- File file = fs.file(fs.path.join(zipBuildDir.path, archivePath));
+ final File file = fs.file(fs.path.join(zipBuildDir.path, archivePath));
file.parent.createSync(recursive: true);
file.writeAsBytes(data).then<Null>((File value) {
count -= 1;