diff --git a/packages/flutter_tools/bin/fuchsia_builder.dart b/packages/flutter_tools/bin/fuchsia_builder.dart index 39ad9ee6a1..ffeae8556f 100644 --- a/packages/flutter_tools/bin/fuchsia_builder.dart +++ b/packages/flutter_tools/bin/fuchsia_builder.dart @@ -35,7 +35,7 @@ const List _kRequiredOptions = const [ ]; Future main(List args) async { - AppContext executableContext = new AppContext(); + final AppContext executableContext = new AppContext(); executableContext.setVariable(Logger, new StdoutLogger()); executableContext.runInZone(() { // Initialize the context with some defaults. @@ -66,7 +66,7 @@ Future run(List args) async { exit(1); } Cache.flutterRoot = platform.environment['FLUTTER_ROOT']; - String outputPath = argResults[_kOptionOutput]; + final String outputPath = argResults[_kOptionOutput]; try { await assemble( outputPath: outputPath, diff --git a/packages/flutter_tools/lib/executable.dart b/packages/flutter_tools/lib/executable.dart index 6e67c60f79..bfdcdedc49 100644 --- a/packages/flutter_tools/lib/executable.dart +++ b/packages/flutter_tools/lib/executable.dart @@ -60,10 +60,10 @@ import 'src/usage.dart'; /// /// This function is intended to be used from the `flutter` command line tool. Future main(List 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, [ new AnalyzeCommand(verboseHelp: verboseHelp), @@ -104,11 +104,11 @@ Future run(List args, List subCommands, { 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 @@ Future run(List args, List subCommands, { // Initialize the system locale. await intl.findSystemLocale(); - Completer runCompleter = new Completer(); + final Completer runCompleter = new Completer(); Chain.capture>(() async { await runner.run(args); await _exit(0); @@ -206,7 +206,7 @@ Future _handleToolError( 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 @@ FileSystem crashFileSystem = new LocalFileSystem(); Future _createLocalCrashReport(List 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 _createLocalCrashReport(List args, dynamic error, Chain cha Future _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 @@ Future _exit(int code) async { // 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 @@ Future _exit(int code) async { // Run shutdown hooks before flushing logs await runShutdownHooks(); - Completer completer = new Completer(); + final Completer completer = new Completer(); // 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 1c539a2123..922c1a9238 100644 --- a/packages/flutter_tools/lib/src/android/adb.dart +++ b/packages/flutter_tools/lib/src/android/adb.dart @@ -51,7 +51,7 @@ class Adb { /// Ask the ADB server for its internal version number. Future 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 @@ class Adb { /// Queries the adb server for the list of connected adb devices. Future> 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 []; return message.split('\n').map( @@ -73,16 +73,16 @@ class Adb { } Future _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> result = await socket.toList(); - List data = result.fold([], (List previous, List element) { + final List> result = await socket.toList(); + final List data = result.fold([], (List previous, List 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 @@ class AdbDevice { // '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 @@ class AdbDevice { rest = rest.trim(); for (String data in rest.split(' ')) { if (data.contains(':')) { - List fields = data.split(':'); + final List fields = data.split(':'); _info[fields[0]] = fields[1]; } } @@ -183,11 +183,11 @@ String cleanAdbDeviceName(String name) { } List _createAdbRequest(String payload) { - List data = payload.codeUnits; + final List data = payload.codeUnits; // A 4-byte hexadecimal string giving the length of the payload. - String prefix = data.length.toRadixString(16).padLeft(4, '0'); - List result = []; + final String prefix = data.length.toRadixString(16).padLeft(4, '0'); + final List result = []; 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 2c1fc8f4ae..5982a4bf8d 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 @@ class AndroidDevice extends Device { if (_properties == null) { _properties = {}; - List propCommand = adbCommandForDevice(['shell', 'getprop']); + final List propCommand = adbCommandForDevice(['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 @@ class AndroidDevice extends Device { @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 @@ class AndroidDevice extends Device { 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 @@ class AndroidDevice extends Device { return false; try { - String adbVersion = runCheckedSync([getAdbPath(androidSdk), 'version']); + final String adbVersion = runCheckedSync([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 @@ class AndroidDevice extends Device { runCheckedSync([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 @@ class AndroidDevice extends Device { } 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 @@ class AndroidDevice extends Device { @override bool isAppInstalled(ApplicationPackage app) { // This call takes 400ms - 600ms. - String listOut = runCheckedSync(adbCommandForDevice(['shell', 'pm', 'list', 'packages', app.id])); + final String listOut = runCheckedSync(adbCommandForDevice(['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 @@ class AndroidDevice extends Device { if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion()) return false; - Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true); - String installOut = runCheckedSync(adbCommandForDevice(['install', '-r', apk.apkPath])); + final Status status = logger.startProgress('Installing ${apk.apkPath}...', expectSlowOperation: true); + final String installOut = runCheckedSync(adbCommandForDevice(['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 @@ class AndroidDevice extends Device { if (!_checkForSupportedAdbVersion() || !_checkForSupportedAndroidVersion()) return false; - String uninstallOut = runCheckedSync(adbCommandForDevice(['uninstall', app.id])); - RegExp failureExp = new RegExp(r'^Failure.*$', multiLine: true); - String failure = failureExp.stringMatch(uninstallOut); + final String uninstallOut = runCheckedSync(adbCommandForDevice(['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 @@ class AndroidDevice extends Device { cmd.addAll(['--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 @@ class AndroidDevice extends Device { Uri observatoryUri, diagnosticUri; if (debuggingOptions.buildMode == BuildMode.debug) { - List deviceUris = await Future.wait( + final List deviceUris = await Future.wait( >[observatoryDiscovery.nextUri(), diagnosticDiscovery.nextUri()] ); observatoryUri = deviceUris[0]; @@ -400,7 +400,7 @@ class AndroidDevice extends Device { @override Future stopApp(ApplicationPackage app) { - List command = adbCommandForDevice(['shell', 'am', 'force-stop', app.id]); + final List command = adbCommandForDevice(['shell', 'am', 'force-stop', app.id]); return runCommandAndStreamOutput(command).then((int exitCode) => exitCode == 0); } @@ -429,11 +429,11 @@ class AndroidDevice extends Device { /// 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([ + final String output = runCheckedSync(adbCommandForDevice([ 'logcat', '-v', 'time', '-t', '1' ])); - Match timeMatch = _timeRegExp.firstMatch(output); + final Match timeMatch = _timeRegExp.firstMatch(output); return timeMatch?.group(0); } @@ -454,12 +454,12 @@ class AndroidDevice extends Device { @override Future> discoverApps() { - RegExp discoverExp = new RegExp(r'DISCOVER: (.*)'); - List result = []; - StreamSubscription logs = getLogReader().logLines.listen((String line) { - Match match = discoverExp.firstMatch(line); + final RegExp discoverExp = new RegExp(r'DISCOVER: (.*)'); + final List result = []; + final StreamSubscription logs = getLogReader().logLines.listen((String line) { + final Match match = discoverExp.firstMatch(line); if (match != null) { - Map app = JSON.decode(match.group(1)); + final Map app = JSON.decode(match.group(1)); result.add(new DiscoveredApp(app['id'], app['observatoryPort'], app['diagnosticPort'])); } }); @@ -476,7 +476,7 @@ class AndroidDevice extends Device { } Map parseAdbDeviceProperties(String str) { - Map properties = {}; + final Map properties = {}; final RegExp propertyExp = new RegExp(r'\[(.*?)\]: \[(.*?)\]'); for (Match match in propertyExp.allMatches(str)) properties[match.group(1)] = match.group(2); @@ -490,11 +490,11 @@ final RegExp _kDeviceRegex = new RegExp(r'^(\S+)\s+(\S+)(.*)'); /// /// [mockAdbOutput] is public for testing. List getAdbDevices({ String mockAdbOutput }) { - List devices = []; + final List devices = []; String text; if (mockAdbOutput == null) { - String adbPath = getAdbPath(androidSdk); + final String adbPath = getAdbPath(androidSdk); if (adbPath == null) return []; text = runSync([adbPath, 'devices', '-l']); @@ -517,18 +517,18 @@ List getAdbDevices({ String mockAdbOutput }) { 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 info = {}; + final Map info = {}; if (rest != null && rest.isNotEmpty) { rest = rest.trim(); for (String data in rest.split(' ')) { if (data.contains(':')) { - List fields = data.split(':'); + final List fields = data.split(':'); info[fields[0]] = fields[1]; } } @@ -595,8 +595,8 @@ class _AdbLogReader extends DeviceLogReader { void _start() { // Start the adb logcat process. - List args = ['logcat', '-v', 'time']; - String lastTimestamp = device.lastLogcatTimestamp; + final List args = ['logcat', '-v', 'time']; + final String lastTimestamp = device.lastLogcatTimestamp; if (lastTimestamp != null) _timeOrigin = _adbTimestampToDateTime(lastTimestamp); else @@ -637,7 +637,7 @@ class _AdbLogReader extends DeviceLogReader { } 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 @@ class _AndroidDevicePortForwarder extends DevicePortForwarder { List get forwardedPorts { final List ports = []; - String stdout = runCheckedSync(device.adbCommandForDevice( + final String stdout = runCheckedSync(device.adbCommandForDevice( ['forward', '--list'] )); - List lines = LineSplitter.split(stdout).toList(); + final List lines = LineSplitter.split(stdout).toList(); for (String line in lines) { if (line.startsWith(device.id)) { - List splitLine = line.split("tcp:"); + final List 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 e80eb26920..0a7389f321 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 @@ String getAdbPath([AndroidSdk existingSdk]) { 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 @@ class AndroidSdk { 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 @@ class AndroidSdk { 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 @@ class AndroidSdk { void _init() { List platforms = []; // 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 @@ class AndroidSdk { List buildTools = []; // 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 f9eeb426f6..186db70c36 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 @@ final RegExp _dotHomeStudioVersionMatcher = /// 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 @@ class AndroidStudio implements Comparable { List _validationMessages = []; 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 @@ class AndroidStudio implements Comparable { } 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 @@ class AndroidStudio implements Comparable { @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 @@ class AndroidStudio implements Comparable { /// 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 @@ class AndroidStudio implements Comparable { } // Find all available Studio installations. - List studios = allInstalled(); + final List studios = allInstalled(); if (studios.isEmpty) { return null; } @@ -134,13 +134,13 @@ class AndroidStudio implements Comparable { platform.isMacOS ? _allMacOS() : _allLinuxOrWindows(); static List _allMacOS() { - List candidatePaths = []; + final List candidatePaths = []; void _checkForStudio(String path) { if (!fs.isDirectorySync(path)) return; try { - Iterable directories = fs + final Iterable directories = fs .directory(path) .listSync() .where((FileSystemEntity e) => e is Directory); @@ -159,7 +159,7 @@ class AndroidStudio implements Comparable { _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 @@ class AndroidStudio implements Comparable { } static List _allLinuxOrWindows() { - List studios = []; + final List studios = []; bool _hasStudioAt(String path, {Version newerThan}) { return studios.any((AndroidStudio studio) { @@ -194,7 +194,7 @@ class AndroidStudio implements Comparable { // 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 @@ class AndroidStudio implements Comparable { } } - 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 @@ class AndroidStudio implements Comparable { 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 a30b732e85..d141b29e83 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 @@ class AndroidStudioValidator extends DoctorValidator { AndroidStudioValidator(this._studio) : super('Android Studio'); static List get allValidators { - List validators = []; - List studios = AndroidStudio.allInstalled(); + final List validators = []; + final List 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 @@ class AndroidStudioValidator extends DoctorValidator { @override Future validate() async { - List messages = []; + final List messages = []; 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 @@ class NoAndroidStudioValidator extends DoctorValidator { @override Future validate() async { - List messages = []; + final List messages = []; - 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 @@ class ConfiguredGradleValidator extends DoctorValidator { @override Future validate() async { ValidationType type = ValidationType.missing; - List messages = []; + final List messages = []; messages.add(new ValidationMessage('gradle-dir = $cfgGradleDir')); @@ -103,7 +103,7 @@ class ConfiguredGradleValidator extends DoctorValidator { String versionString; if (processManager.canRun(gradleExecutable)) { type = ValidationType.partial; - ProcessResult result = + final ProcessResult result = processManager.runSync([gradleExecutable, '--version']); if (result.exitCode == 0) { versionString = result.stdout @@ -111,7 +111,7 @@ class ConfiguredGradleValidator extends DoctorValidator { .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 35ebf87845..e9977a3c96 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 @@ class AndroidWorkflow extends DoctorValidator implements Workflow { @override Future validate() async { - List messages = []; + final List messages = []; 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 @@ class AndroidWorkflow extends DoctorValidator implements Workflow { } if (platform.environment.containsKey(kAndroidHome)) { - String androidHomeDir = platform.environment[kAndroidHome]; + final String androidHomeDir = platform.environment[kAndroidHome]; messages.add(new ValidationMessage('$kAndroidHome = $androidHomeDir')); } - List validationResult = androidSdk.validateSdkWellFormed(); + final List validationResult = androidSdk.validateSdkWellFormed(); if (validationResult.isEmpty) { // Empty result means SDK is well formed. @@ -72,10 +72,10 @@ class AndroidWorkflow extends DoctorValidator implements Workflow { try { printTrace('java -version'); - ProcessResult result = processManager.runSync(['java', '-version']); + final ProcessResult result = processManager.runSync(['java', '-version']); if (result.exitCode == 0) { javaVersion = result.stderr; - List versionLines = javaVersion.split('\n'); + final List 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 948befa3ea..02b93827da 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -35,15 +35,15 @@ bool isProjectUsingGradle() { } 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 get gradleAppOut { } 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 ensureGradle() async { Future 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 @@ Future buildGradleProject(BuildMode buildMode, String target) async { // 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 @@ String _escapePath(String path) => platform.isWindows ? path.replaceAll('\\', '\ Future 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( [fs.file(gradle).absolute.path, 'build'], workingDirectory: 'android', allowReentrantFlutter: true @@ -149,22 +149,22 @@ Future buildGradleProjectV1(String gradle) async { 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 buildGradleProjectV2(String gradle, String buildModeName, String target) async { - String assembleTask = "assemble${toTitleCase(buildModeName)}"; + final String assembleTask = "assemble${toTitleCase(buildModeName)}"; // Run 'gradle assemble'. - Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true); - String gradlePath = fs.file(gradle).absolute.path; - List command = [gradlePath]; + final Status status = logger.startProgress('Running \'gradle $assembleTask\'...', expectSlowOperation: true); + final String gradlePath = fs.file(gradle).absolute.path; + final List command = [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 @@ Future buildGradleProjectV2(String gradle, String buildModeName, String ta 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 @@ Future buildGradleProjectV2(String gradle, String buildModeName, String ta 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 8f837a0b29..6d998c5d11 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart @@ -50,14 +50,14 @@ class AndroidApk extends ApplicationPackage { /// 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 aaptArgs = [aaptPath, 'dump', 'badging', applicationBinary]; - ApkManifestData data = ApkManifestData.parseFromAaptBadging(runCheckedSync(aaptArgs)); + final List aaptArgs = [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 @@ class AndroidApk extends ApplicationPackage { 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 manifests = document.findElements('manifest'); + final Iterable 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 @@ abstract class IOSApp extends ApplicationPackage { 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 @@ abstract class IOSApp extends ApplicationPackage { 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 @@ class ApkManifestData { // package: name='io.flutter.gallery' versionCode='1' versionName='0.0.1' platformBuildVersionName='NMR1' // launchable-activity: name='io.flutter.app.FlutterActivity' label='' icon='' - Map> map = >{}; + final Map> map = >{}; 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 entries = {}; + final Map entries = {}; 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 26550198c8..a311e0fe50 100644 --- a/packages/flutter_tools/lib/src/artifacts.dart +++ b/packages/flutter_tools/lib/src/artifacts.dart @@ -105,7 +105,7 @@ class CachedArtifacts extends Artifacts { } 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 @@ class CachedArtifacts extends Artifacts { 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 @@ class CachedArtifacts extends Artifacts { } 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 @@ class CachedArtifacts extends Artifacts { 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 @@ class CachedArtifacts extends Artifacts { } 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 @@ class CachedArtifacts extends Artifacts { 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 @@ class LocalEngineArtifacts extends Artifacts { 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 @@ class LocalEngineArtifacts extends Artifacts { } 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 c69bc4d976..f99d31e5f4 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart @@ -41,7 +41,7 @@ class AssetBundle { if ((projectRoot == null) || (projectAssets == null)) return; - List assets = projectAssets.split(','); + final List assets = projectAssets.split(','); for (String asset in assets) { if (asset == '') continue; @@ -57,7 +57,7 @@ class AssetBundle { 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 @@ class AssetBundle { return 0; } if (manifest != null) { - int result = await _validateFlutterManifest(manifest); + final int result = await _validateFlutterManifest(manifest); if (result != 0) return result; } Map manifestDescriptor = manifest; manifestDescriptor = manifestDescriptor['flutter'] ?? {}; - 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 @@ class AssetBundle { } } - List<_Asset> materialAssets = <_Asset>[]; + final List<_Asset> materialAssets = <_Asset>[]; if (usesMaterialDesign && includeDefaultFonts) { materialAssets.addAll(_getMaterialAssets(_kFontSetMaterial)); if (includeRobotoFonts) @@ -136,7 +136,7 @@ class AssetBundle { entries[_kAssetManifestJson] = _createAssetManifest(assetVariants); - DevFSContent fontManifest = + final DevFSContent fontManifest = _createFontManifest(manifestDescriptor, usesMaterialDesign, includeDefaultFonts, includeRobotoFonts); if (fontManifest != null) entries[_kFontManifestJson] = fontManifest; @@ -183,7 +183,7 @@ class _Asset { 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 @@ class _Asset { } Map _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> _getMaterialFonts(String fontSet) { } List<_Asset> _getMaterialAssets(String fontSet) { - List<_Asset> result = <_Asset>[]; + final List<_Asset> result = <_Asset>[]; for (Map family in _getMaterialFonts(fontSet)) { for (Map 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 @@ Future _obtainLicenses( final List combinedLicensesList = packageLicenses.keys.map( (String license) { - List packageNames = packageLicenses[license].toList() + final List packageNames = packageLicenses[license].toList() ..sort(); return packageNames.join('\n') + '\n\n' + license; } @@ -294,9 +294,9 @@ Future _obtainLicenses( } DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) { - Map> json = >{}; + final Map> json = >{}; for (_Asset main in assetVariants.keys) { - List variants = []; + final List variants = []; for (_Asset variant in assetVariants[main]) variants.add(variant.relativePath); json[main.relativePath] = variants; @@ -308,7 +308,7 @@ DevFSContent _createFontManifest(Map manifestDescriptor, bool usesMaterialDesign, bool includeDefaultFonts, bool includeRobotoFonts) { - List> fonts = >[]; + final List> fonts = >[]; if (usesMaterialDesign && includeDefaultFonts) { fonts.addAll(_getMaterialFonts(AssetBundle._kFontSetMaterial)); if (includeRobotoFonts) @@ -331,7 +331,7 @@ Map<_Asset, List<_Asset>> _parseAssets( String assetBase, { List excludeDirs: const [] }) { - 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 @@ Map<_Asset, List<_Asset>> _parseAssets( 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 files = assetDir.listSync(recursive: true); + final List files = assetDir.listSync(recursive: true); for (FileSystemEntity entity in files) { if (!fs.isFileSync(entity.path)) @@ -368,7 +368,7 @@ Map<_Asset, List<_Asset>> _parseAssets( 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 @@ Map<_Asset, List<_Asset>> _parseAssets( // Add assets referenced in the fonts section of the manifest. if (manifestDescriptor.containsKey('fonts')) { for (Map family in manifestDescriptor['fonts']) { - List> fonts = family['fonts']; + final List> fonts = family['fonts']; if (fonts == null) continue; for (Map 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 @@ _Asset _resolveAsset( 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 @@ _Asset _resolveAsset( 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 _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 729bdd566a..832280f8a5 100644 --- a/packages/flutter_tools/lib/src/base/config.dart +++ b/packages/flutter_tools/lib/src/base/config.dart @@ -44,7 +44,7 @@ class Config { } 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 bb28b6e84a..c96c5bc9be 100644 --- a/packages/flutter_tools/lib/src/base/context.dart +++ b/packages/flutter_tools/lib/src/base/context.dart @@ -20,7 +20,7 @@ class AppContext { 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 @@ class AppContext { if (_instances.containsKey(type)) return _instances[type]; - AppContext parent = _calcParent(_zone); + final AppContext parent = _calcParent(_zone); return parent?.getVariable(type); } @@ -49,11 +49,11 @@ class AppContext { } 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 @@ class AppContext { } Future _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 0cf12d542a..6a4e7ef8b7 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 @@ FileSystem get fs => context == null ? _kLocalFs : context[FileSystem]; /// 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 @@ void enableRecordingFileSystem(String location) { /// 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 @@ void copyDirectorySync(Directory srcDir, Directory destDir) { 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 @@ void copyDirectorySync(Directory srcDir, Directory destDir) { /// 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 @@ Directory getRecordingSink(String dirname, String basename) { /// /// 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 a9d3eef593..b5821b3e02 100644 --- a/packages/flutter_tools/lib/src/base/logger.dart +++ b/packages/flutter_tools/lib/src/base/logger.dart @@ -206,7 +206,7 @@ class VerboseLogger extends Logger { if (message.trim().isEmpty) return; - int millis = stopwatch.elapsedMilliseconds; + final int millis = stopwatch.elapsedMilliseconds; stopwatch.reset(); String prefix; @@ -220,8 +220,8 @@ class VerboseLogger extends Logger { } 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 @@ enum _LogType { 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 @@ class _AnsiStatus extends Status { 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 0fd3b70508..abce28132c 100644 --- a/packages/flutter_tools/lib/src/base/net.dart +++ b/packages/flutter_tools/lib/src/base/net.dart @@ -14,9 +14,9 @@ const int kNetworkProblemExitCode = 50; Future> 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 @@ Future> fetchUrl(Uri url) async { } try { - BytesBuilder responseBody = new BytesBuilder(copy: false); + final BytesBuilder responseBody = new BytesBuilder(copy: false); await for (List 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 3441bc3ab8..0d94547116 100644 --- a/packages/flutter_tools/lib/src/base/os.dart +++ b/packages/flutter_tools/lib/src/base/os.dart @@ -54,10 +54,10 @@ class _PosixUtils extends OperatingSystemUtils { /// to locate the binary. @override File which(String execName) { - ProcessResult result = processManager.runSync(['which', execName]); + final ProcessResult result = processManager.runSync(['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 @@ class _WindowsUtils extends OperatingSystemUtils { @override File which(String execName) { - ProcessResult result = processManager.runSync(['where', execName]); + final ProcessResult result = processManager.runSync(['where', execName]); if (result.exitCode != 0) return null; return fs.file(result.stdout.trim().split('\n').first.trim()); @@ -98,14 +98,14 @@ class _WindowsUtils extends OperatingSystemUtils { @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 bytes = file.readAsBytesSync(); + final File file = entity; + final String path = file.fileSystem.path.relative(file.path, from: data.path); + final List bytes = file.readAsBytesSync(); archive.addFile(new ArchiveFile(path, bytes.length, bytes)); } zipFile.writeAsBytesSync(new ZipEncoder().encode(archive), flush: true); @@ -113,14 +113,14 @@ class _WindowsUtils extends OperatingSystemUtils { @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 @@ class _WindowsUtils extends OperatingSystemUtils { } Future 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 @@ Future findPreferredPort(int defaultPort, { int searchStep: 2 }) async { 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 findPreferredPort(int defaultPort, { int searchStep: 2 }) async { Future _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 @@ String findProjectRoot([String directory]) { 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 2645a94ced..dd9624012b 100644 --- a/packages/flutter_tools/lib/src/base/platform.dart +++ b/packages/flutter_tools/lib/src/base/platform.dart @@ -24,19 +24,19 @@ Platform get platform => context == null ? _kLocalPlatform : context[Platform]; /// non-empty directory as long as there is no collision with the `"platform"` /// subdirectory. Future 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 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 829ac3fc32..062076993d 100644 --- a/packages/flutter_tools/lib/src/base/process.dart +++ b/packages/flutter_tools/lib/src/base/process.dart @@ -69,8 +69,8 @@ Future runShutdownHooks() async { _shutdownHooksRunning = true; try { for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { - List hooks = _shutdownHooks.remove(stage); - List> futures = >[]; + final List hooks = _shutdownHooks.remove(stage); + final List> futures = >[]; for (ShutdownHook shutdownHook in hooks) futures.add(shutdownHook()); await Future.wait(futures); @@ -100,7 +100,7 @@ Future runCommand(List cmd, { Map 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 @@ Future runCommandAndStreamOutput(List cmd, { StringConverter mapFunction, Map environment }) async { - Process process = await runCommand( + final Process process = await runCommand( cmd, workingDirectory: workingDirectory, allowReentrantFlutter: allowReentrantFlutter, environment: environment ); - StreamSubscription subscription = process.stdout + final StreamSubscription subscription = process.stdout .transform(UTF8.decoder) .transform(const LineSplitter()) .where((String line) => filter == null ? true : filter.hasMatch(line)) @@ -133,7 +133,7 @@ Future runCommandAndStreamOutput(List cmd, { 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 runCommandAndStreamOutput(List cmd, { } Future runAndKill(List cmd, Duration timeout) { - Future proc = runDetached(cmd); + final Future proc = runDetached(cmd); return new Future.delayed(timeout, () async { printTrace('Intentionally killing ${cmd[0]}'); processManager.killPid((await proc).pid); @@ -169,7 +169,7 @@ Future runAndKill(List cmd, Duration timeout) { Future runDetached(List cmd) { _traceCommand(cmd); - Future proc = processManager.start( + final Future proc = processManager.start( cmd, mode: ProcessStartMode.DETACHED, ); @@ -181,12 +181,12 @@ Future runAsync(List cmd, { 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 @@ String runSync(List cmd, { } void _traceCommand(List args, { String workingDirectory }) { - String argsText = args.join(' '); + final String argsText = args.join(' '); if (workingDirectory == null) printTrace(argsText); else @@ -257,7 +257,7 @@ String _runWithLoggingSync(List cmd, { 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 @@ class RunResult { @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 de9a8ba06b..41e85f6f68 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 @@ ProcessManager get processManager => context[ProcessManager]; /// 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 @@ void enableRecordingProcessManager(String location) { /// recorded (i.e. the result of having been previously passed to /// [enableRecordingProcessManager]), or a [ToolExit] will be thrown. Future 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 cfc216cf14..209b70c564 100644 --- a/packages/flutter_tools/lib/src/base/utils.dart +++ b/packages/flutter_tools/lib/src/base/utils.dart @@ -22,7 +22,7 @@ bool get isRunningOnBot { } String hex(List 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 @@ String pluralize(String word, int count) => count == 1 ? word : word + 's'; /// 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 @@ String getElapsedAsMilliseconds(Duration duration) => '${duration.inMilliseconds /// 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 @@ class ItemListNotifier { List get items => _items.toList(); void updateWithNewList(List updatedList) { - Set updatedSet = new Set.from(updatedList); + final Set updatedSet = new Set.from(updatedList); - Set addedItems = updatedSet.difference(_items); - Set removedItems = _items.difference(updatedSet); + final Set addedItems = updatedSet.difference(_items); + final Set removedItems = _items.difference(updatedSet); _items = updatedSet; @@ -140,7 +140,7 @@ class SettingsFile { 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 @@ class Uuid { /// 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 60887b31b8..5ef31f6d59 100644 --- a/packages/flutter_tools/lib/src/base/version.dart +++ b/packages/flutter_tools/lib/src/base/version.dart @@ -43,15 +43,15 @@ class Version implements Comparable { /// 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 5facec6ff2..8c0bcc57e5 100644 --- a/packages/flutter_tools/lib/src/build_info.dart +++ b/packages/flutter_tools/lib/src/build_info.dart @@ -130,7 +130,7 @@ String getBuildDirectory() { 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 bbcafa770e..17cfca192f 100644 --- a/packages/flutter_tools/lib/src/cache.dart +++ b/packages/flutter_tools/lib/src/cache.dart @@ -89,7 +89,7 @@ class Cache { 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 @@ class Cache { /// 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 @@ class Cache { } 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 @@ class Cache { } 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 @@ class Cache { Future 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 @@ class Cache { Future 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 @@ class Cache { if (!location.parent.existsSync()) location.parent.createSync(recursive: true); - List fileBytes = await fetchUrl(url); + final List 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 @@ class MaterialFonts { } Future 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 @@ class FlutterEngine { // Return a list of (cache directory path, download URL path) tuples. List> _getBinaryDirs() { - List> binaryDirs = >[]; + final List> binaryDirs = >[]; if (cache.includeAllPlatforms) binaryDirs @@ -309,16 +309,16 @@ class FlutterEngine { ]; 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 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 @@ class FlutterEngine { } Future 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 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 @@ class FlutterEngine { 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 @@ class FlutterEngine { } Future _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 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 c31d0cb190..ec5191ccde 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 @@ abstract class AnalyzeBase { void writeBenchmark(Stopwatch stopwatch, int errorCount, int membersMissingDocumentation) { final String benchmarkOut = 'analysis_benchmark.json'; - Map data = { + final Map data = { 'time': (stopwatch.elapsedMilliseconds / 1000.0), 'issues': errorCount, 'missingDartDocs': membersMissingDocumentation @@ -56,8 +56,8 @@ abstract class AnalyzeBase { bool inRepo(List fileList) { if (fileList == null || fileList.isEmpty) fileList = [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 daccb390b5..2d92ad961f 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 @@ class AnalyzeContinuously extends AnalyzeBase { 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 @@ class AnalyzeContinuously extends AnalyzeBase { 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 @@ class AnalyzeContinuously extends AnalyzeBase { // 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 @@ class AnalyzeContinuously extends AnalyzeBase { 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 @@ class AnalysisServer { int _id = 0; Future start() async { - String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot'); - List command = [ + final String snapshot = fs.path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot'); + final List command = [ fs.path.join(dartSdkPath, 'bin', 'dart'), snapshot, '--sdk', @@ -168,10 +168,10 @@ class AnalysisServer { _process = await processManager.start(command); _process.exitCode.whenComplete(() => _process = null); - Stream errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()); + final Stream errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()); errorStream.listen((String error) => printError(error)); - Stream inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter()); + final Stream inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter()); inStream.listen(_handleServerResponse); // Available options (many of these are obsolete): @@ -199,7 +199,7 @@ class AnalysisServer { Future get onExit => _process.exitCode; void _sendCommand(String method, Map params) { - String message = JSON.encode( { + final String message = JSON.encode( { 'id': (++_id).toString(), 'method': method, 'params': params @@ -211,12 +211,12 @@ class AnalysisServer { void _handleServerResponse(String line) { printTrace('<== $line'); - dynamic response = JSON.decode(line); + final dynamic response = JSON.decode(line); if (response is Map) { 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) { if (event == 'server.status') @@ -228,7 +228,7 @@ class AnalysisServer { } } else if (response['error'] != null) { // Fields are 'code', 'message', and 'stackTrace'. - Map error = response['error']; + final Map error = response['error']; printError('Error response from the server: ${error['code']} ${error['message']}'); if (error['stackTrace'] != null) printError(error['stackTrace']); @@ -239,7 +239,7 @@ class AnalysisServer { void _handleStatus(Map 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 @@ class AnalysisServer { void _handleAnalysisIssues(Map issueInfo) { // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} - String file = issueInfo['file']; - List errors = issueInfo['errors'].map((Map json) => new AnalysisError(json)).toList(); + final String file = issueInfo['file']; + final List errors = issueInfo['errors'].map((Map json) => new AnalysisError(json)).toList(); _errorsController.add(new FileAnalysisErrors(file, errors)); } @@ -299,7 +299,7 @@ class AnalysisError implements Comparable { 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 @@ class AnalysisError implements Comparable { @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 f0a8c50599..2212c15176 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 @@ class AnalyzeOnce extends AnalyzeBase { @override Future analyze() async { - Stopwatch stopwatch = new Stopwatch()..start(); - Set pubSpecDirectories = new HashSet(); - List dartFiles = []; + final Stopwatch stopwatch = new Stopwatch()..start(); + final Set pubSpecDirectories = new HashSet(); + final List dartFiles = []; 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 @@ class AnalyzeOnce extends AnalyzeBase { } } - 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 @@ class AnalyzeOnce extends AnalyzeBase { if (currentPackage && !flutterRepo) { // **/.*dart - Directory currentDirectory = fs.directory('.'); + final Directory currentDirectory = fs.directory('.'); _collectDartFiles(currentDirectory, dartFiles); pubSpecDirectories.add(currentDirectory); } @@ -80,21 +80,21 @@ class AnalyzeOnce extends AnalyzeBase { } // 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 @@ class AnalyzeOnce extends AnalyzeBase { .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 @@ class AnalyzeOnce extends AnalyzeBase { // 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 @@ class AnalyzeOnce extends AnalyzeBase { '"pub deps --style=list" and "pub upgrade --verbosity=solver" in the affected directories.'); throwToolExit(message.toString()); } - Map packages = dependencies.asPackageMap(); + final Map packages = dependencies.asPackageMap(); Cache.releaseLockEarly(); @@ -142,16 +142,16 @@ class AnalyzeOnce extends AnalyzeBase { 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 errors = analyzer.analyze(dartFiles); + final List errors = analyzer.analyze(dartFiles); int errorCount = 0; int membersMissingDocumentation = 0; @@ -176,7 +176,7 @@ class AnalyzeOnce extends AnalyzeBase { dumpErrors(errors.map((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 @@ class AnalyzeOnce extends AnalyzeBase { List flutterRootComponents; bool isFlutterLibrary(String filename) { flutterRootComponents ??= fs.path.normalize(fs.path.absolute(Cache.flutterRoot)).split(fs.path.separator); - List filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.path.separator); + final List 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 @@ class AnalyzeOnce extends AnalyzeBase { 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 @@ class PackageDependency { } void describeConflict(StringBuffer result) { assert(hasConflict); - List targets = values.keys.toList(); + final List 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 @@ class PackageDependencyTracker { 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 @@ class PackageDependencyTracker { } Map asPackageMap() { - Map result = {}; + final Map result = {}; 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 cd7ac3f743..aef95a3ab7 100644 --- a/packages/flutter_tools/lib/src/commands/build.dart +++ b/packages/flutter_tools/lib/src/commands/build.dart @@ -54,14 +54,14 @@ abstract class BuildSubCommand extends FlutterCommand { @mustCallSuper Future 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 @@ class BuildCleanCommand extends FlutterCommand { @override Future 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 4a7337bc14..6441115efd 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 @@ class BuildAotCommand extends BuildSubCommand { @override Future 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 @@ Future _buildAotSnapshot( 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 filePaths = [ + final List filePaths = [ vmEntryPoints, ioEntryPoints, uiPath, @@ -177,7 +177,7 @@ Future _buildAotSnapshot( assert(false); } - List missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList(); + final List missingFiles = filePaths.where((String p) => !fs.isFileSync(p)).toList(); if (missingFiles.isNotEmpty) { printError('Missing files: $missingFiles'); return null; @@ -187,7 +187,7 @@ Future _buildAotSnapshot( return null; } - List genSnapshotCmd = [ + final List genSnapshotCmd = [ genSnapshot, '--assert_initializer', '--await_is_keyword', @@ -242,7 +242,7 @@ Future _buildAotSnapshot( 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 @@ Future _buildAotSnapshot( 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 commonBuildOptions = ['-arch', 'arm64', '-miphoneos-version-min=8.0']; + final List commonBuildOptions = ['-arch', 'arm64', '-miphoneos-version-min=8.0']; if (interpreter) { runCheckedSync(['mv', vmSnapshotData, fs.path.join(outputDir.path, kVmSnapshotData)]); @@ -289,9 +289,9 @@ Future _buildAotSnapshot( ..addAll(['-c', assembly, '-o', assemblyO])); } - String appSo = fs.path.join(outputDir.path, 'app.dylib'); + final String appSo = fs.path.join(outputDir.path, 'app.dylib'); - List linkCommand = ['xcrun', 'clang'] + final List linkCommand = ['xcrun', 'clang'] ..addAll(commonBuildOptions) ..addAll([ '-dynamiclib', diff --git a/packages/flutter_tools/lib/src/commands/build_apk.dart b/packages/flutter_tools/lib/src/commands/build_apk.dart index 50031aad9f..44ac978a33 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 @@ class _AssetBuilder { } 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 @@ class _ApkBuilder { } void compileClassesDex(File classesDex, List jars) { - List packageArgs = [_dx.path, + final List packageArgs = [_dx.path, '--dex', '--force-jumbo', '--output', classesDex.path @@ -106,7 +106,7 @@ class _ApkBuilder { } void package(File outputApk, File androidManifest, Directory assets, Directory artifacts, Directory resources, BuildMode buildMode) { - List packageArgs = [_aapt.path, + final List packageArgs = [_aapt.path, 'package', '-M', androidManifest.path, '-A', assets.path, @@ -222,8 +222,8 @@ class BuildApkCommand extends BuildSubCommand { Future 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 @@ Future<_ApkComponents> _findApkComponents( String resources, Map 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 : {}; @@ -290,7 +290,7 @@ Future<_ApkComponents> _findApkComponents( await parseServiceConfigs(components.services, jars: components.jars); - List allFiles = [ + final List allFiles = [ components.manifest, components.icuData, components.libSkyShell, components.debugKeystore ]..addAll(components.jars) ..addAll(components.extraFiles.values); @@ -316,52 +316,52 @@ int _buildApk( 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 @@ bool _needsRebuild( BuildMode buildMode, Map 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 dependencies = [ + final List dependencies = [ manifest, _kFlutterManifestPath, _kPackagesStatusPath ]; dependencies.addAll(extraFiles.values.map((File file) => file.path)); - Iterable dependenciesStat = + final Iterable dependenciesStat = dependencies.map((String path) => fs.statSync(path)); if (apkStat.type == FileSystemEntityType.NOT_FOUND) @@ -443,8 +443,8 @@ bool _needsRebuild( 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 @@ Future buildAndroid( if (androidSdk == null) throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.'); - List validationResult = androidSdk.validateSdkWellFormed(); + final List validationResult = androidSdk.validateSdkWellFormed(); if (validationResult.isNotEmpty) { validationResult.forEach(printError); throwToolExit('Try re-installing or updating your Android SDK.'); } - Map extraFiles = {}; + final Map extraFiles = {}; 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 @@ Future buildAndroid( 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 @@ Future buildAndroid( 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 @@ Future buildAndroidWithGradle( if (androidSdk == null) throwToolExit('No Android SDK found. Try setting the ANDROID_HOME environment variable.'); - List validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false); + final List validationResult = androidSdk.validateSdkWellFormed(requireApkSigner: false); if (validationResult.isNotEmpty) { validationResult.forEach(printError); throwToolExit('Try re-installing or updating your Android SDK.'); @@ -622,23 +622,23 @@ Future buildApk( } Map _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 {}; } void _writeBuildMetaEntry(String buildDirectoryPath, String key, dynamic value) { - Map meta = _readBuildMeta(buildDirectoryPath); + final Map 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 53927fc43a..ee652a0775 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 @@ class BuildFlxCommand extends BuildSubCommand { @override Future 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 8796c51448..1bf1a6cab4 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 @@ class BuildIOSCommand extends BuildSubCommand { @override Future 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 @@ class BuildIOSCommand extends BuildSubCommand { 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 30ec6a4a95..0c836e909e 100644 --- a/packages/flutter_tools/lib/src/commands/channel.dart +++ b/packages/flutter_tools/lib/src/commands/channel.dart @@ -33,18 +33,18 @@ class ChannelCommand extends FlutterCommand { } Future _listChannels() async { - String currentBranch = runSync( + final String currentBranch = runSync( ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], workingDirectory: Cache.flutterRoot); printStatus('Flutter channels:'); - int result = await runCommandAndStreamOutput( + final int result = await runCommandAndStreamOutput( ['git', 'branch', '-r'], workingDirectory: Cache.flutterRoot, mapFunction: (String line) { - List split = line.split('/'); + final List 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 @@ class ChannelCommand extends FlutterCommand { Future _switchChannel(String branchName) async { printStatus('Switching to flutter channel named $branchName'); - int result = await runCommandAndStreamOutput( + final int result = await runCommandAndStreamOutput( ['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 c00a24d828..59484e581c 100644 --- a/packages/flutter_tools/lib/src/commands/config.dart +++ b/packages/flutter_tools/lib/src/commands/config.dart @@ -49,7 +49,7 @@ class ConfigCommand extends FlutterCommand { @override Future 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 fd4c56c54f..902670cfb6 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -69,21 +69,21 @@ class CreateCommand extends FlutterCommand { 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 @@ class CreateCommand extends FlutterCommand { if (error != null) throwToolExit(error); - int generatedCount = _renderTemplates( + final int generatedCount = _renderTemplates( projectName, argResults['description'], dirPath, @@ -148,7 +148,7 @@ Your main program file is lib/main.dart in the $relativePath directory. printStatus('Creating project ${fs.path.relative(dirPath)}...'); - Map templateContext = { + final Map templateContext = { 'projectName': projectName, 'androidIdentifier': _createAndroidIdentifier(projectName), 'iosIdentifier': _createUTIIdentifier(projectName), @@ -161,7 +161,7 @@ Your main program file is lib/main.dart in the $relativePath directory. 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 @@ Your main program file is lib/main.dart in the $relativePath directory. ); 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 _createAndroidIdentifier(String name) { 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 @@ String _validateProjectDir(String dirPath, { String flutterRoot }) { "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 _validateProjectDir(String dirPath, { String flutterRoot }) { } 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 5309be15d9..ff72a23c8f 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart @@ -48,18 +48,18 @@ class DaemonCommand extends FlutterCommand { Future 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 @@ class Daemon { // {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 @@ class Daemon { } 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 @@ abstract class Domain { } void sendEvent(String name, [dynamic args]) { - Map map = { 'event': name }; + final Map map = { 'event': name }; if (args != null) map['params'] = _toJsonable(args); _send(map); @@ -194,7 +194,7 @@ abstract class Domain { String _getStringArg(Map 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 @@ abstract class Domain { bool _getBoolArg(Map 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 @@ abstract class Domain { int _getIntArg(Map 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 @@ class AppDomain extends Domain { List _apps = []; Future> start(Map 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 @@ class AppDomain extends Domain { 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 @@ class AppDomain extends Domain { ); } - 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', { 'deviceId': device.id, @@ -387,7 +387,7 @@ class AppDomain extends Domain { if (options.debuggingEnabled) { connectionInfoCompleter = new Completer(); connectionInfoCompleter.future.then((DebugConnectionInfo info) { - Map params = { + final Map params = { 'port': info.httpUri.port, 'wsUri': info.wsUri.toString(), }; @@ -396,7 +396,7 @@ class AppDomain extends Domain { _sendAppEvent(app, 'debugPort', params); }); } - Completer appStartedCompleter = new Completer(); + final Completer appStartedCompleter = new Completer(); appStartedCompleter.future.then((Null value) { _sendAppEvent(app, 'started'); }); @@ -424,11 +424,11 @@ class AppDomain extends Domain { enableHotReload && device.supportsHotMode; Future restart(Map 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 @@ class AppDomain extends Domain { } Future callServiceExtension(Map args) async { - String appId = _getStringArg(args, 'appId', required: true); - String methodName = _getStringArg(args, 'methodName'); - Map params = args['params'] ?? {}; + final String appId = _getStringArg(args, 'appId', required: true); + final String methodName = _getStringArg(args, 'methodName'); + final Map params = args['params'] ?? {}; - AppInstance app = _getApp(appId); + final AppInstance app = _getApp(appId); if (app == null) throw "app '$appId' not found"; - Isolate isolate = app.runner.currentView.uiIsolate; - Map result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params); + final Isolate isolate = app.runner.currentView.uiIsolate; + final Map result = await isolate.invokeFlutterExtensionRpcRaw(methodName, params: params); if (result == null) return new OperationResult(1, 'method not available: $methodName'); @@ -458,9 +458,9 @@ class AppDomain extends Domain { } Future stop(Map 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 @@ class AppDomain extends Domain { } Future>> discover(Map 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 apps = await device.discoverApps(); + final List apps = await device.discoverApps(); return apps.map((DiscoveredApp app) { return { 'id': app.id, @@ -496,7 +496,7 @@ class AppDomain extends Domain { } void _sendAppEvent(AppInstance app, String name, [Map args]) { - Map eventArgs = { 'appId': app.id }; + final Map eventArgs = { 'appId': app.id }; if (args != null) eventArgs.addAll(args); sendEvent('app.$name', eventArgs); @@ -540,7 +540,7 @@ class DeviceDomain extends Domain { List _discoverers = []; Future> getDevices([Map args]) { - List devices = _discoverers.expand((PollingDeviceDiscovery discoverer) { + final List devices = _discoverers.expand((PollingDeviceDiscovery discoverer) { return discoverer.devices; }).toList(); return new Future>.value(devices); @@ -562,11 +562,11 @@ class DeviceDomain extends Domain { /// Forward a host port to a device port. Future> forward(Map 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 @@ class DeviceDomain extends Domain { /// Removes a forwarded port. Future unforward(Map 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 @@ class DeviceDomain extends Domain { /// Return the device matching the deviceId field in the args. Device _getDevice(String deviceId) { - List devices = _discoverers.expand((PollingDeviceDiscovery discoverer) { + final List devices = _discoverers.expand((PollingDeviceDiscovery discoverer) { return discoverer.devices; }).toList(); return devices.firstWhere((Device device) => device.id == deviceId, orElse: () => null); @@ -605,13 +605,13 @@ class DeviceDomain extends Domain { /// 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 devices = discoverer.pollingGetDevices(); + final List devices = discoverer.pollingGetDevices(); for (Device device in devices) if (device.id == deviceId) return device; @@ -727,7 +727,7 @@ class AppInstance { 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 @@ class _AppRunLogger extends Logger { if (_status != null) return new Status(); - int id = _nextProgressId++; + final int id = _nextProgressId++; _sendProgressEvent({ 'id': id.toString(), diff --git a/packages/flutter_tools/lib/src/commands/devices.dart b/packages/flutter_tools/lib/src/commands/devices.dart index 4547ade1c6..2982216f3c 100644 --- a/packages/flutter_tools/lib/src/commands/devices.dart +++ b/packages/flutter_tools/lib/src/commands/devices.dart @@ -27,7 +27,7 @@ class DevicesCommand extends FlutterCommand { exitCode: 1); } - List devices = await deviceManager.getAllConnectedDevices(); + final List 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 cfc1cb386e..0039474ae6 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart @@ -85,7 +85,7 @@ class DriveCommand extends RunCommandBase { @override Future runCommand() async { - String testFile = _getTestFile(); + final String testFile = _getTestFile(); if (testFile == null) throwToolExit(null); @@ -110,7 +110,7 @@ class DriveCommand extends RunCommandBase { ); } - 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 @@ class DriveCommand extends RunCommandBase { 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 @@ class DriveCommand extends RunCommandBase { appFile = fs.path.relative(appFile, from: packageDir); } - List parts = fs.path.split(appFile); + final List parts = fs.path.split(appFile); if (parts.length < 2) { printError( @@ -169,7 +169,7 @@ class DriveCommand extends RunCommandBase { // 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( [packageDir, 'test_driver']..addAll(parts.skip(1)))); return '${pathWithNoExtension}_test${fs.path.extension(appFile)}'; } @@ -183,7 +183,7 @@ void restoreTargetDeviceFinder() { } Future findTargetDevice() async { - List devices = await deviceManager.getDevices(); + final List devices = await deviceManager.getDevices(); if (deviceManager.hasSpecifiedDeviceId) { if (devices.isEmpty) { @@ -203,7 +203,7 @@ Future findTargetDevice() async { // 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 @@ Future findTargetDevice() async { // 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 @@ void restoreAppStarter() { } Future _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 @@ Future _startApp(DriveCommand command) async { 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 platformArgs = {}; + final Map platformArgs = {}; if (command.traceStartup) platformArgs['trace-startup'] = command.traceStartup; @@ -280,7 +280,7 @@ Future _startApp(DriveCommand command) async { .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 @@ Future _runTests(List testArgs, String observatoryUri) async { printTrace('Running driver tests.'); PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(PackageMap.globalPackagesPath)); - List args = testArgs.toList() + final List 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( [dartVmPath]..addAll(args), environment: { 'VM_SERVICE_URL': observatoryUri } ); @@ -335,8 +335,8 @@ void restoreAppStopper() { Future _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 45d8c047c6..65bd40826b 100644 --- a/packages/flutter_tools/lib/src/commands/format.dart +++ b/packages/flutter_tools/lib/src/commands/format.dart @@ -36,9 +36,9 @@ class FormatCommand extends FlutterCommand { ); } - String dartfmt = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartfmt'); - List cmd = [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 cmd = [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 fc1de89ef3..acfac126c1 100644 --- a/packages/flutter_tools/lib/src/commands/install.dart +++ b/packages/flutter_tools/lib/src/commands/install.dart @@ -31,7 +31,7 @@ class InstallCommand extends FlutterCommand { @override Future 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 e7d0df53b7..891b70446e 100644 --- a/packages/flutter_tools/lib/src/commands/logs.dart +++ b/packages/flutter_tools/lib/src/commands/logs.dart @@ -42,16 +42,16 @@ class LogsCommand extends FlutterCommand { if (argResults['clear']) device.clearLogs(); - DeviceLogReader logReader = device.getLogReader(); + final DeviceLogReader logReader = device.getLogReader(); Cache.releaseLockEarly(); printStatus('Showing $logReader logs:'); - Completer exitCompleter = new Completer(); + final Completer exitCompleter = new Completer(); // Start reading. - StreamSubscription subscription = logReader.logLines.listen( + final StreamSubscription subscription = logReader.logLines.listen( printStatus, onDone: () { exitCompleter.complete(0); @@ -75,7 +75,7 @@ class LogsCommand extends FlutterCommand { } // 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 eace49a0a9..5e2aabc241 100644 --- a/packages/flutter_tools/lib/src/commands/packages.dart +++ b/packages/flutter_tools/lib/src/commands/packages.dart @@ -56,7 +56,7 @@ class PackagesGetCommand extends FlutterCommand { 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 d34b32807f..60b0677c3f 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart @@ -148,7 +148,7 @@ class RunCommand extends RunCommandBase { @override String get usagePath { - String command = shouldUseHotMode() ? 'hotrun' : name; + final String command = shouldUseHotMode() ? 'hotrun' : name; if (device == null) return command; @@ -180,7 +180,7 @@ class RunCommand extends RunCommandBase { } 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 @@ class RunCommand extends RunCommandBase { 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 @@ class RunCommand extends RunCommandBase { } 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 @@ class RunCommand extends RunCommandBase { 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 @@ class RunCommand extends RunCommandBase { ); } - 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 9dd14b8512..b24d5eb9d0 100644 --- a/packages/flutter_tools/lib/src/commands/screenshot.dart +++ b/packages/flutter_tools/lib/src/commands/screenshot.dart @@ -92,7 +92,7 @@ class ScreenshotCommand extends FlutterCommand { } Future 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 @@ class ScreenshotCommand extends FlutterCommand { 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 @@ class ScreenshotCommand extends FlutterCommand { } Future 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 4a01ad271f..6d31775d12 100644 --- a/packages/flutter_tools/lib/src/commands/stop.dart +++ b/packages/flutter_tools/lib/src/commands/stop.dart @@ -31,9 +31,9 @@ class StopCommand extends FlutterCommand { @override Future 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 6d3f2d8193..1266a3ad02 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -78,7 +78,7 @@ class TestCommand extends FlutterCommand { } Future _runTests(List 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 @@ class TestCommand extends FlutterCommand { } Future _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 @@ class TestCommand extends FlutterCommand { 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 @@ class TestCommand extends FlutterCommand { 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([ + final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info')); + final ProcessResult result = processManager.runSync([ 'lcov', '--add-tracefile', baseCoverageData, '--add-tracefile', sourceFile.path, @@ -163,7 +163,7 @@ class TestCommand extends FlutterCommand { ); } - List testArgs = []; + final List testArgs = []; commandValidator(); @@ -208,7 +208,7 @@ class TestCommand extends FlutterCommand { 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 474d3734cb..e9f1a20c24 100644 --- a/packages/flutter_tools/lib/src/commands/trace.dart +++ b/packages/flutter_tools/lib/src/commands/trace.dart @@ -51,11 +51,11 @@ class TraceCommand extends FlutterCommand { @override Future 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 @@ class TraceCommand extends FlutterCommand { } Future _stopTracing(Tracing tracing) async { - Map timeline = await tracing.stopTracingAndDownloadTimeline(); + final Map timeline = await tracing.stopTracingAndDownloadTimeline(); File localFile; if (argResults['out'] != null) { @@ -103,7 +103,7 @@ class Tracing { 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 @@ class Tracing { await vmService.vm.setVMTimelineFlags([]); timeline = await vmService.vm.getVMTimeline(); } else { - Completer whenFirstFrameRendered = new Completer(); + final Completer whenFirstFrameRendered = new Completer(); vmService.onTimelineEvent.listen((ServiceEvent timelineEvent) { - List> events = timelineEvent.timelineEvents; + final List> events = timelineEvent.timelineEvents; for (Map event in events) { if (event['name'] == kFirstUsefulFrameEventName) whenFirstFrameRendered.complete(); @@ -159,8 +159,8 @@ class Tracing { /// Download the startup trace information from the given observatory client and /// store it to build/start_up_info.json. Future 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 @@ Future downloadStartupTrace(VMService observatory) async { if (!(await traceInfoFile.parent.exists())) await traceInfoFile.parent.create(); - Tracing tracing = new Tracing(observatory); + final Tracing tracing = new Tracing(observatory); - Map timeline = await tracing.stopTracingAndDownloadTimeline( + final Map timeline = await tracing.stopTracingAndDownloadTimeline( waitForFirstFrame: true ); int extractInstantEventTimestamp(String eventName) { - List> events = timeline['traceEvents']; - Map event = events.firstWhere( + final List> events = timeline['traceEvents']; + final Map event = events.firstWhere( (Map 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 @@ Future downloadStartupTrace(VMService observatory) async { throw 'First frame event is missing in the timeline. Cannot compute startup time.'; } - int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros; - Map traceInfo = { + final int timeToFirstFrameMicros = firstFrameTimestampMicros - engineEnterTimestampMicros; + final Map traceInfo = { '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 2a3783b3d0..b92c4e0c62 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 @@ class UpdatePackagesCommand extends FlutterCommand { final bool hidden; Future _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 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 73f7236ea7..cbdf88c709 100644 --- a/packages/flutter_tools/lib/src/commands/upgrade.dart +++ b/packages/flutter_tools/lib/src/commands/upgrade.dart @@ -32,7 +32,7 @@ class UpgradeCommand extends FlutterCommand { 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 @@ class UpgradeCommand extends FlutterCommand { 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 ee214e5e11..ae61ae5ae3 100644 --- a/packages/flutter_tools/lib/src/crash_reporting.dart +++ b/packages/flutter_tools/lib/src/crash_reporting.dart @@ -85,20 +85,20 @@ class CrashReportSender { printStatus('Sending crash report to Google.'); - Uri uri = _baseUri.replace( + final Uri uri = _baseUri.replace( queryParameters: { '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 @@ class CrashReportSender { 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 @@ class _MultipartRequest extends http.BaseRequest { /// 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> controller = new StreamController>(sync: true); + final StreamController> controller = new StreamController>(sync: true); void writeAscii(String string) { controller.add(UTF8.encode(string)); @@ -369,8 +369,8 @@ class _MultipartRequest extends http.BaseRequest { /// Returns a randomly-generated multipart boundary string String _boundaryString() { - String prefix = "dart-"; - List list = new List.generate(_BOUNDARY_LENGTH - prefix.length, + final String prefix = "dart-"; + final List list = new List.generate(_BOUNDARY_LENGTH - prefix.length, (int index) => _BOUNDARY_CHARACTERS[_random.nextInt(_BOUNDARY_CHARACTERS.length)], growable: false); @@ -382,7 +382,7 @@ class _MultipartRequest extends http.BaseRequest { /// [stream] is done. Unlike [store], [sink] remains open after [stream] is /// done. Future writeStreamToSink(Stream stream, EventSink sink) { - Completer completer = new Completer(); + final Completer completer = new Completer(); 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 a7430a7247..744d8b937a 100644 --- a/packages/flutter_tools/lib/src/dart/analysis.dart +++ b/packages/flutter_tools/lib/src/dart/analysis.dart @@ -50,8 +50,8 @@ class AnalysisDriver { } List analyze(Iterable files) { - List infos = _analyze(files); - List errors = []; + final List infos = _analyze(files); + final List errors = []; for (AnalysisErrorInfo info in infos) { for (AnalysisError error in info.errors) { if (!_isFiltered(error)) @@ -65,17 +65,17 @@ class AnalysisDriver { context = AnalysisEngine.instance.createAnalysisContext(); _processAnalysisOptions(); context.analysisOptions = options; - PackageInfo packageInfo = new PackageInfo(options.packageMap); - List resolvers = _getResolvers(context, packageInfo.asMap()); + final PackageInfo packageInfo = new PackageInfo(options.packageMap); + final List resolvers = _getResolvers(context, packageInfo.asMap()); context.sourceFactory = new SourceFactory(resolvers, packageInfo.asPackages()); - List sources = []; - ChangeSet changeSet = new ChangeSet(); + final List sources = []; + 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 @@ class AnalysisDriver { } context.applyChanges(changeSet); - List infos = []; + final List infos = []; for (Source source in sources) { context.computeErrors(source); infos.add(context.getErrors(source)); @@ -98,13 +98,13 @@ class AnalysisDriver { Map> packageMap) { // Create our list of resolvers. - List resolvers = []; + final List resolvers = []; // 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 @@ class AnalysisDriver { 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 @@ class AnalysisDriver { } 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 @@ class AnalysisDriver { } 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 optionMap = + final Map optionMap = analysisOptionsProvider.getOptionsFromFile(file); if (optionMap != null) applyToAnalysisOptions(options, optionMap); @@ -153,9 +153,9 @@ class AnalysisDriver { } void _processPlugins() { - List plugins = []; + final List plugins = []; plugins.addAll(AnalysisEngine.instance.requiredPlugins); - ExtensionManager manager = new ExtensionManager(); + final ExtensionManager manager = new ExtensionManager(); manager.processPlugins(plugins); linter.registerLintRules(); } @@ -181,7 +181,7 @@ class AnalysisErrorDescription { 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 DriverOptions extends AnalysisOptionsImpl { class PackageInfo { PackageInfo(Map packageMap) { - Map packages = new HashMap(); + final Map packages = new HashMap(); for (String package in packageMap.keys) { - String path = packageMap[package]; + final String path = packageMap[package]; packages[package] = new Uri.directory(path); _map[package] = [ 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 d390577dbd..167378b445 100644 --- a/packages/flutter_tools/lib/src/dart/dependencies.dart +++ b/packages/flutter_tools/lib/src/dart/dependencies.dart @@ -35,7 +35,7 @@ class DartDependencySetBuilder { mainScriptPath ]; - String output = runSyncAndThrowStdErrOnError(args); + final String output = runSyncAndThrowStdErrOnError(args); return new Set.from(LineSplitter.split(output)); } @@ -65,8 +65,8 @@ class _GenSnapshotDartDependencySetBuilder implements DartDependencySetBuilder { 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 args = [ snapshotterPath, @@ -84,14 +84,14 @@ class _GenSnapshotDartDependencySetBuilder implements DartDependencySetBuilder { 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 depsList = output.trim().split(' '); + final List depsList = output.trim().split(' '); return new Set.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 e2b7ab0e16..0367bf8abf 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 @@ import '../base/file_system.dart'; const String kPackagesFileName = '.packages'; Map _parse(String packagesPath) { - List source = fs.file(packagesPath).readAsBytesSync(); + final List source = fs.file(packagesPath).readAsBytesSync(); return packages_file.parse(source, new Uri.file(packagesPath)); } @@ -42,10 +42,10 @@ class PackageMap { /// Returns the path to [packageUri]. String pathForPackage(Uri packageUri) { assert(packageUri.scheme == 'package'); - List pathSegments = packageUri.pathSegments.toList(); - String packageName = pathSegments.removeAt(0); - Uri packageBase = map[packageName]; - String packageRelativePath = fs.path.joinAll(pathSegments); + final List 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 @@ class PackageMap { 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 4cb0a7adfa..22e0fb2850 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -15,10 +15,10 @@ import 'sdk.dart'; 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 @@ Future pubGet({ 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 @@ Future pubGet({ } 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( [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 d9efa5e390..9bd3680544 100644 --- a/packages/flutter_tools/lib/src/dependency_checker.dart +++ b/packages/flutter_tools/lib/src/dependency_checker.dart @@ -34,8 +34,8 @@ class DependencyChecker { // 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 e1f0236707..d9277c6d12 100644 --- a/packages/flutter_tools/lib/src/devfs.dart +++ b/packages/flutter_tools/lib/src/devfs.dart @@ -72,8 +72,8 @@ class DevFSFileContent extends DevFSContent { _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 @@ class DevFSFileContent extends DevFSContent { @override bool get isModified { - FileStat _oldFileStat = _fileStat; + final FileStat _oldFileStat = _fileStat; _stat(); return _oldFileStat == null || _fileStat.modified.isAfter(_oldFileStat.modified); } @@ -121,7 +121,7 @@ class DevFSByteContent extends DevFSContent { /// 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 @@ class ServiceProtocolDevFSOperations implements DevFSOperations { @override Future create(String fsName) async { - Map response = await vmService.vm.createDevFS(fsName); + final Map response = await vmService.vm.createDevFS(fsName); return Uri.parse(response['uri']); } @@ -193,7 +193,7 @@ class ServiceProtocolDevFSOperations implements DevFSOperations { } 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 @@ class _DevFSHttpWriter { // 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 @@ class _DevFSHttpWriter { 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> contents = content.contentsAsCompressedStream(); + final Stream> contents = content.contentsAsCompressedStream(); await request.addStream(contents); - HttpClientResponse response = await request.close(); + final HttpClientResponse response = await request.close(); await response.drain(); } catch (e) { if (retry < kMaxRetries) { @@ -375,17 +375,17 @@ class DevFS { // Handle deletions. printTrace('Scanning for deleted files'); - String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory()); + final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory()); final List toRemove = new List(); _entries.forEach((Uri deviceUri, DevFSContent content) { if (!content._exists) { - Future> operation = + final Future> 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 @@ class DevFS { // Update modified files int numBytes = 0; - Map dirtyEntries = {}; + final Map dirtyEntries = {}; _entries.forEach((Uri deviceUri, DevFSContent content) { String archivePath; if (deviceUri.path.startsWith(assetBuildDirPrefix)) @@ -423,7 +423,7 @@ class DevFS { } else { // Make service protocol requests for each. dirtyEntries.forEach((Uri deviceUri, DevFSContent content) { - Future> operation = + final Future> operation = _operations.writeFile(fsName, deviceUri, content); if (operation != null) _pendingOperations.add(operation); @@ -449,7 +449,7 @@ class DevFS { } 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 @@ class DevFS { } bool _shouldIgnore(Uri deviceUri) { - List ignoredUriPrefixes = ['android/', + final List ignoredUriPrefixes = ['android/', _asUriPath(getBuildDirectory()), 'ios/', '.pub/']; @@ -480,7 +480,7 @@ class DevFS { bool ignoreDotFiles: true, Set 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 @@ class DevFS { } } try { - Stream files = + final Stream files = directory.list(recursive: recursive, followLinks: false); await for (FileSystemEntity file in files) { if (!devFSConfig.noDirectorySymlinks && (file is Link)) { @@ -532,12 +532,12 @@ class DevFS { Future _scanPackages(Set 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 @@ class DevFS { } } 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 b29be3f9f9..09d3ab2393 100644 --- a/packages/flutter_tools/lib/src/device.dart +++ b/packages/flutter_tools/lib/src/device.dart @@ -42,8 +42,8 @@ class DeviceManager { /// This does a case insentitive compare with [deviceId]. Future> getDevicesById(String deviceId) async { deviceId = deviceId.toLowerCase(); - List devices = await getAllConnectedDevices(); - Device device = devices.firstWhere( + final List devices = await getAllConnectedDevices(); + final Device device = devices.firstWhere( (Device device) => device.id.toLowerCase() == deviceId || device.name.toLowerCase() == deviceId, @@ -250,11 +250,11 @@ abstract class Device { return []; // Extract device information - List> table = >[]; + final List> table = >[]; 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([ @@ -266,7 +266,7 @@ abstract class Device { } // Calculate column widths - List indices = new List.generate(table[0].length - 1, (int i) => i); + final List indices = new List.generate(table[0].length - 1, (int i) => i); List widths = indices.map((int i) => 0).toList(); for (List row in table) { widths = indices.map((int i) => math.max(widths[i], row[i].length)).toList(); @@ -336,7 +336,7 @@ class LaunchResult { @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 1ec463e5a0..f4fd3ea162 100644 --- a/packages/flutter_tools/lib/src/doctor.dart +++ b/packages/flutter_tools/lib/src/doctor.dart @@ -28,7 +28,7 @@ const Map _osNames = const { }; String osName() { - String os = platform.operatingSystem; + final String os = platform.operatingSystem; return _osNames.containsKey(os) ? _osNames[os] : os; } @@ -59,7 +59,7 @@ class Doctor { if (_iosWorkflow.appliesToHostPlatform) _validators.add(_iosWorkflow); - List ideValidators = []; + final List ideValidators = []; ideValidators.addAll(AndroidStudioValidator.allValidators); ideValidators.addAll(IntelliJValidator.installedValidators); if (ideValidators.isNotEmpty) @@ -82,12 +82,12 @@ class Doctor { } Future 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 @@ class Doctor { 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 @@ class Doctor { 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 @@ class _FlutterValidator extends DoctorValidator { @override Future validate() async { - List messages = []; - ValidationType valid = ValidationType.installed; + final List messages = []; + 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 @@ abstract class IntelliJValidator extends DoctorValidator { @override Future validate() async { - List messages = []; + final List messages = []; int installCount = 0; @@ -300,25 +300,25 @@ abstract class IntelliJValidator extends DoctorValidator { )); 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 = ''; - int start = content.indexOf(versionStartTag); - int end = content.indexOf('', 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 = ''; + final int start = content.indexOf(versionStartTag); + final int end = content.indexOf('', start); return content.substring(start + versionStartTag.length, end); } catch (_) { return null; @@ -326,7 +326,7 @@ abstract class IntelliJValidator extends DoctorValidator { } 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 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator { String pluginsPath; static Iterable get installed { - List validators = []; + final List validators = []; 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 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator { 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 @@ class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator { // 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 @@ class IntelliJValidatorOnMac extends IntelliJValidator { }; static Iterable get installed { - List validators = []; - List installPaths = ['/Applications', fs.path.join(homeDirPath, 'Applications')]; + final List validators = []; + final List installPaths = ['/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 installDirs = installPaths + final Iterable installDirs = installPaths .map((String installPath) => fs.directory(installPath).listSync()) .expand((List mappedDirs) => mappedDirs) .where((FileSystemEntity mappedDir) => mappedDir is Directory); @@ -444,7 +444,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator { @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 @@ class IntelliJValidatorOnMac extends IntelliJValidator { @override String get pluginsPath { - List split = version.split('.'); - String major = split[0]; - String minor = split[1]; + final List 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 @@ class DeviceValidator extends DoctorValidator { @override Future validate() async { - List devices = await deviceManager.getAllConnectedDevices(); + final List devices = await deviceManager.getAllConnectedDevices(); List messages; if (devices.isEmpty) { messages = [new ValidationMessage('None')]; diff --git a/packages/flutter_tools/lib/src/flx.dart b/packages/flutter_tools/lib/src/flx.dart index bd0078f07f..fa4a75b45c 100644 --- a/packages/flutter_tools/lib/src/flx.dart +++ b/packages/flutter_tools/lib/src/flx.dart @@ -59,7 +59,7 @@ Future _createScriptSnapshotWithSkySnapshot({ assert(mainPath != null); assert(snapshotPath != null); assert(packages != null); - String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot); + final String snapshotterPath = artifacts.getArtifactPath(Artifact.skySnapshot); final List args = [ snapshotterPath, @@ -83,9 +83,9 @@ Future _creteScriptSnapshotWithGenSnapshot({ 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 args = [ snapshotterPath, @@ -149,7 +149,7 @@ Future build({ 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 @@ Future build({ // 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 @@ Future assemble({ 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 @@ Future assemble({ 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 343956da93..9075daf25b 100644 --- a/packages/flutter_tools/lib/src/ios/devices.dart +++ b/packages/flutter_tools/lib/src/ios/devices.dart @@ -97,18 +97,18 @@ class IOSDevice extends Device { if (!doctor.iosWorkflow.hasIDeviceId) return []; - List devices = []; + final List devices = []; 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 _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([listerPath, '-l']); + final String output = runSync([listerPath, '-l']); return output.trim().split('\n').where((String s) => s != null && s.isNotEmpty); } catch (e) { return []; @@ -116,7 +116,7 @@ class IOSDevice extends Device { } static String _getDeviceInfo(String deviceID, String infoKey, [IOSDevice mockIOS]) { - String informerPath = (mockIOS != null) + final String informerPath = (mockIOS != null) ? mockIOS.informerPath : _checkForCommand('ideviceinfo'); return runSync([informerPath, '-k', infoKey, '-u', deviceID]).trim(); @@ -142,7 +142,7 @@ class IOSDevice extends Device { @override bool isAppInstalled(ApplicationPackage app) { try { - String apps = runCheckedSync([installerPath, '--list-apps']); + final String apps = runCheckedSync([installerPath, '--list-apps']); if (new RegExp(app.id, multiLine: true).hasMatch(apps)) { return true; } @@ -157,8 +157,8 @@ class IOSDevice extends Device { @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 @@ class IOSDevice extends Device { 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 @@ class IOSDevice extends Device { } // 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 launchArguments = ["--enable-dart-profiling"]; + final List launchArguments = ["--enable-dart-profiling"]; if (debuggingOptions.startPaused) launchArguments.add("--start-paused"); @@ -240,7 +240,7 @@ class IOSDevice extends Device { if (platformArgs['trace-startup'] ?? false) launchArguments.add('--trace-startup'); - List launchCommand = [ + final List launchCommand = [ '/usr/bin/env', 'ios-deploy', '--id', @@ -271,12 +271,12 @@ class IOSDevice extends Device { // 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 forwardObsUri = observatoryDiscovery.nextUri(); + final Future forwardObsUri = observatoryDiscovery.nextUri(); Future forwardDiagUri; if (debuggingOptions.buildMode == BuildMode.debug) { forwardDiagUri = diagnosticDiscovery.nextUri(); @@ -284,9 +284,9 @@ class IOSDevice extends Device { forwardDiagUri = new Future.value(null); } - Future launch = runCommandAndStreamOutput(launchCommand, trace: true); + final Future launch = runCommandAndStreamOutput(launchCommand, trace: true); - List uris = await launch.then>((int result) async { + final List uris = await launch.then>((int result) async { installationResult = result; if (result != 0) { @@ -392,7 +392,7 @@ class _IOSDeviceLogReader extends DeviceLogReader { // // iOS 9 format: Runner[297] : // iOS 10 format: Runner(libsystem_asl.dylib)[297] : - 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 @@ class _IOSDeviceLogReader extends DeviceLogReader { } 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 @@ class _IOSDevicePortForwarder extends DevicePortForwarder { } // Usage: iproxy LOCAL_TCP_PORT DEVICE_TCP_PORT UDID - Process process = await runCommand([ + final Process process = await runCommand([ 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 @@ class _IOSDevicePortForwarder extends DevicePortForwarder { 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 6a672f8d6f..3154fabce6 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 @@ class IOSWorkflow extends DoctorValidator implements Workflow { 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 @@ class IOSWorkflow extends DoctorValidator implements Workflow { @override Future validate() async { - List messages = []; + final List messages = []; ValidationType xcodeStatus = ValidationType.missing; ValidationType pythonStatus = ValidationType.missing; ValidationType brewStatus = ValidationType.missing; @@ -143,7 +143,7 @@ class IOSWorkflow extends DoctorValidator implements Workflow { } else { // Check for compatibility between libimobiledevice and Xcode. // TODO(cbracken) remove this check once libimobiledevice > 1.2.0 is released. - ProcessResult result = (await runAsync(['idevice_id', '-l'])).processResult; + final ProcessResult result = (await runAsync(['idevice_id', '-l'])).processResult; if (result.exitCode == 0 && result.stdout.isNotEmpty && !exitsHappy(['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 599521fd2c..26b6c93e47 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -42,7 +42,7 @@ class Xcode { } else { try { printTrace('xcrun clang'); - ProcessResult result = processManager.runSync(['/usr/bin/xcrun', 'clang']); + final ProcessResult result = processManager.runSync(['/usr/bin/xcrun', 'clang']); if (result.stdout != null && result.stdout.contains('license')) _eulaSigned = false; @@ -88,8 +88,8 @@ class Xcode { if (!xcodeVersionRegex.hasMatch(xcodeVersionText)) return false; - String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1); - List components = version.split('.'); + final String version = xcodeVersionRegex.firstMatch(xcodeVersionText).group(1); + final List components = version.split('.'); _xcodeMajorVersion = int.parse(components[0]); _xcodeMinorVersion = components.length == 1 ? 0 : int.parse(components[1]); @@ -115,7 +115,7 @@ Future buildXcodeProject({ 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 @@ Future buildXcodeProject({ await _addServicesToBundle(fs.directory(app.appDirectory)); - List commands = [ + final List commands = [ '/usr/bin/env', 'xcrun', 'xcodebuild', @@ -136,7 +136,7 @@ Future buildXcodeProject({ 'ONLY_ACTIVE_ARCH=YES', ]; - List contents = fs.directory(app.appDirectory).listSync(); + final List contents = fs.directory(app.appDirectory).listSync(); for (FileSystemEntity entity in contents) { if (fs.path.extension(entity.path) == '.xcworkspace') { commands.addAll([ @@ -164,7 +164,7 @@ Future buildXcodeProject({ ); } - RunResult result = await runAsync( + final RunResult result = await runAsync( commands, workingDirectory: app.appDirectory, allowReentrantFlutter: true @@ -192,8 +192,8 @@ Future buildXcodeProject({ ); } 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 buildXcodeProject({ } Future 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 @@ Future diagnoseXcodeBuildFailure(XcodeBuildResult result) async { 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 @@ bool _checkXcodeVersion() { if (!platform.isMacOS) return false; try { - String version = runCheckedSync(['xcodebuild', '-version']); - Match match = _xcodeVersionRegExp.firstMatch(version); + final String version = runCheckedSync(['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 @@ bool _checkXcodeVersion() { } Future _addServicesToBundle(Directory bundle) async { - List> services = >[]; + final List> services = >[]; printTrace("Trying to resolve native pub services."); // Step 1: Parse the service configuration yaml files present in the service @@ -325,12 +325,12 @@ Future _addServicesToBundle(Directory bundle) async { 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 @@ Future _copyServiceFrameworks(List> services, Director printTrace("Copying service frameworks to '${fs.path.absolute(frameworksDirectory.path)}'."); frameworksDirectory.createSync(recursive: true); for (Map 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 @@ Future _copyServiceFrameworks(List> services, Director void _copyServiceDefinitionsManifest(List> services, File manifest) { printTrace("Creating service definitions manifest at '${manifest.path}'"); - List> jsonServices = services.map((Map service) => { + final List> jsonServices = services.map((Map service) => { '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 json = { 'services' : jsonServices }; + final Map json = { '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 105c18c257..6d727d459c 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 @@ String getValueFromFile(String plistFilePath, String key) { 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([ + final String value = runCheckedSync([ '/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 6a82aa9aca..71b46c4df5 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -61,7 +61,7 @@ class SimControl { return true; if (deviceName == null) { - SimDevice testDevice = _createTestDevice(); + final SimDevice testDevice = _createTestDevice(); if (testDevice == null) { return false; } @@ -72,7 +72,7 @@ class SimControl { // "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 args = [_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1']; + final List args = [_xcrunPath, 'instruments', '-w', deviceName, '-t', 'Blank', '-l', '1']; printTrace(args.join(' ')); runDetached(args); printStatus('Waiting for iOS Simulator to boot...'); @@ -98,11 +98,11 @@ class SimControl { } 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 @@ class SimControl { .forEach(_deleteDevice); // Create new device - String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix'; - List args = [_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime]; + final String deviceName = '${deviceType.name} $_kFlutterTestDeviceSuffix'; + final List args = [_xcrunPath, 'simctl', 'create', deviceName, deviceType.identifier, runtime]; printTrace(args.join(' ')); runCheckedSync(args); @@ -121,8 +121,8 @@ class SimControl { } SimDeviceType _findSuitableDeviceType() { - List> allTypes = _list(SimControlListSection.devicetypes); - List> usableTypes = allTypes + final List> allTypes = _list(SimControlListSection.devicetypes); + final List> usableTypes = allTypes .where((Map info) => info['name'].startsWith('iPhone')) .toList() ..sort((Map r1, Map r2) => -compareIphoneVersions(r1['identifier'], r2['identifier'])); @@ -141,8 +141,8 @@ class SimControl { } String _findSuitableRuntime() { - List> allRuntimes = _list(SimControlListSection.runtimes); - List> usableRuntimes = allRuntimes + final List> allRuntimes = _list(SimControlListSection.runtimes); + final List> usableRuntimes = allRuntimes .where((Map info) => info['name'].startsWith('iOS')) .toList() ..sort((Map r1, Map r2) => -compareIosVersions(r1['version'], r2['version'])); @@ -159,7 +159,7 @@ class SimControl { void _deleteDevice(SimDevice device) { try { - List args = [_xcrunPath, 'simctl', 'delete', device.name]; + final List args = [_xcrunPath, 'simctl', 'delete', device.name]; printTrace(args.join(' ')); runCheckedSync(args); } catch(e) { @@ -190,9 +190,9 @@ class SimControl { // }, // "pairs": { ... }, - List command = [_xcrunPath, 'simctl', 'list', '--json', section.name]; + final List command = [_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 >{}; @@ -203,12 +203,12 @@ class SimControl { /// Returns a list of all available devices, both potential and connected. List getDevices() { - List devices = []; + final List devices = []; - Map devicesSection = _list(SimControlListSection.devices); + final Map devicesSection = _list(SimControlListSection.devices); for (String deviceCategory in devicesSection.keys) { - List> devicesData = devicesSection[deviceCategory]; + final List> devicesData = devicesSection[deviceCategory]; for (Map data in devicesData) { devices.add(new SimDevice(deviceCategory, data)); @@ -244,7 +244,7 @@ class SimControl { } void launch(String deviceId, String appIdentifier, [List launchArgs]) { - List args = [_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier]; + final List args = [_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier]; if (launchArgs != null) args.addAll(launchArgs); runCheckedSync(args); @@ -329,7 +329,7 @@ class IOSSimulator extends Device { } 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 @@ class IOSSimulator extends Device { @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 @@ class IOSSimulator extends Device { // 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 @@ class IOSSimulator extends Device { // 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 @@ class IOSSimulator extends Device { } // Prepare launch arguments. - List args = ['--enable-dart-profiling']; + final List args = ['--enable-dart-profiling']; if (!prebuiltApplication) { args.addAll([ @@ -457,9 +457,9 @@ class IOSSimulator extends Device { 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 @@ class IOSSimulator extends Device { 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 @@ class IOSSimulator extends Device { } bool _applicationIsInstalledAndRunning(ApplicationPackage app) { - bool isInstalled = isAppInstalled(app); + final bool isInstalled = isAppInstalled(app); - bool isRunning = exitsHappy([ + final bool isRunning = exitsHappy([ '/usr/bin/killall', 'Runner', ]); @@ -515,14 +515,14 @@ class IOSSimulator extends Device { Future _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 @@ class IOSSimulator extends Device { Future pushFile( ApplicationPackage app, String localFile, String targetFile) async { if (p.platform.isMacOS) { - String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app); + final String simulatorHomeDirectory = _getSimulatorAppHomeDirectory(app); runCheckedSync(['cp', localFile, fs.path.join(simulatorHomeDirectory, targetFile)]); return true; } @@ -575,16 +575,16 @@ class IOSSimulator extends Device { @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([]); } @@ -667,10 +667,10 @@ class _IOSSimulatorLogReader extends DeviceLogReader { ]; 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 @@ class _IOSSimulatorLogReader extends DeviceLogReader { 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 @@ class _IOSSimulatorLogReader extends DeviceLogReader { } 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 @@ class _IOSSimulatorLogReader extends DeviceLogReader { if (!_flutterRunnerRegex.hasMatch(line)) return; - String filteredLine = _filterSystemLog(line); + final String filteredLine = _filterSystemLog(line); if (filteredLine == null) return; @@ -760,13 +760,13 @@ class _IOSSimulatorLogReader extends DeviceLogReader { } int compareIosVersions(String v1, String v2) { - List v1Fragments = v1.split('.').map(int.parse).toList(); - List v2Fragments = v2.split('.').map(int.parse).toList(); + final List v1Fragments = v1.split('.').map(int.parse).toList(); + final List 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 @@ final RegExp _iosDeviceTypePattern = 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 @@ int compareIphoneVersions(String id1, String id2) { // Sorted in the least preferred first order. const List qualifiers = const ['-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 9cd50876b8..c32ab15d91 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 _settingExpr = new RegExp(r'(\w+)\s*=\s*(\S+)'); 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 @@ void updateXcodeGeneratedProperties(String projectPath, BuildMode mode, String t 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 getXcodeBuildSettings(String xcodeProjPath, String target) { - String absProjPath = fs.path.absolute(xcodeProjPath); - String out = runCheckedSync([ + final String absProjPath = fs.path.absolute(xcodeProjPath); + final String out = runCheckedSync([ '/usr/bin/xcodebuild', '-project', absProjPath, '-target', target, '-showBuildSettings' ]); - Map settings = {}; + final Map settings = {}; 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 @@ Map getXcodeBuildSettings(String xcodeProjPath, String target) { /// Substitutes variables in [str] with their values from the specified Xcode /// project and target. String substituteXcodeVariables(String str, String xcodeProjPath, String target) { - Iterable matches = _varExpr.allMatches(str); + final Iterable matches = _varExpr.allMatches(str); if (matches.isEmpty) return str; - Map settings = getXcodeBuildSettings(xcodeProjPath, target); + final Map 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 99dad09430..ad839a1417 100644 --- a/packages/flutter_tools/lib/src/protocol_discovery.dart +++ b/packages/flutter_tools/lib/src/protocol_discovery.dart @@ -50,7 +50,7 @@ class ProtocolDiscovery { /// The [Future] returned by this function will complete when the next service /// Uri is found. Future 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 @@ class ProtocolDiscovery { 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 @@ class ProtocolDiscovery { 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 87baf6085c..c2eed76ed0 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -108,8 +108,8 @@ abstract class ResidentRunner { } Future _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 @@ abstract class ResidentRunner { } } } - 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 @@ abstract class ResidentRunner { } } 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 @@ abstract class ResidentRunner { } _processingTerminalRequest = true; try { - bool handled = await _commonTerminalInputHandler(command); + final bool handled = await _commonTerminalInputHandler(command); if (!handled) await handleTerminalCommand(command); } finally { @@ -323,18 +323,18 @@ abstract class ResidentRunner { } Future 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 @@ class OperationResult { 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 874b9e9066..69795554f5 100644 --- a/packages/flutter_tools/lib/src/run_cold.dart +++ b/packages/flutter_tools/lib/src/run_cold.dart @@ -83,14 +83,14 @@ class ColdRunner extends ResidentRunner { 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 platformArgs; if (traceStartup != null) @@ -98,7 +98,7 @@ class ColdRunner extends ResidentRunner { 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 1e9b369ca8..a83bb6f65c 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -98,7 +98,7 @@ class HotRunner extends ResidentRunner { // Already computed. return true; } - DartDependencySetBuilder dartDependencySetBuilder = + final DartDependencySetBuilder dartDependencySetBuilder = new DartDependencySetBuilder( mainPath, projectRootPath, packagesFilePath); try { @@ -129,7 +129,7 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { return 1; } - Map platformArgs = new Map(); + final Map platformArgs = new Map(); 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 @@ class HotRunner extends ResidentRunner { kernelContent = new DevFSFileContent(fs.file(kernelFilePath)); // Start the application. - Future futureResult = device.startApp( + final Future futureResult = device.startApp( package, debuggingOptions.buildMode, mainPath: mainPath, @@ -167,7 +167,7 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { } try { - Uri baseUri = await _initDevFS(); + final Uri baseUri = await _initDevFS(); if (connectionInfoCompleter != null) { connectionInfoCompleter.complete( new DebugConnectionInfo( @@ -198,7 +198,7 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { Future 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 @@ class HotRunner extends ResidentRunner { DevFS _devFS; Future _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 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { Future _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 _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 @@ class HotRunner extends ResidentRunner { } Future _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 @@ class HotRunner extends ResidentRunner { @override Future 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 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { // 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 @@ class HotRunner extends ResidentRunner { 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 @@ class HotRunner extends ResidentRunner { 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 reloadReport = + final Map reloadReport = await currentView.uiIsolate.reloadSources( pause: pause, rootLibUri: deviceEntryUri, @@ -447,13 +447,13 @@ class HotRunner extends ResidentRunner { 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 7c39287881..f8f3a7ffa9 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 @@ abstract class FlutterCommand extends Command { } BuildMode getBuildMode() { - List modeFlags = [argResults['debug'], argResults['profile'], argResults['release']]; + final List modeFlags = [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 @@ abstract class FlutterCommand extends Command { /// so that this method can record and report the overall time to analytics. @override Future 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 @@ abstract class FlutterCommand extends Command { setupApplicationPackages(); - String commandPath = usagePath; + final String commandPath = usagePath; if (commandPath != null) flutterUsage.sendCommand(usagePath); @@ -234,14 +234,14 @@ abstract class FlutterCommand extends Command { } 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 6bfc8f24d7..51444d60b5 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 @@ class FlutterCommandRunner extends CommandRunner { 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 @@ class FlutterCommandRunner extends CommandRunner { if (globalResults['bug-report']) { // --bug-report implies --record-to= - 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 @@ class FlutterCommandRunner extends CommandRunner { // 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 @@ class FlutterCommandRunner extends CommandRunner { 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 @@ class FlutterCommandRunner extends CommandRunner { 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 @@ class FlutterCommandRunner extends CommandRunner { 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 @@ class FlutterCommandRunner extends CommandRunner { break; } - String parent = fs.path.dirname(directory); + final String parent = fs.path.dirname(directory); if (parent == directory) break; directory = parent; @@ -393,13 +393,13 @@ class FlutterCommandRunner extends CommandRunner { // 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 bf4da516dd..00bd1073b9 100644 --- a/packages/flutter_tools/lib/src/services.dart +++ b/packages/flutter_tools/lib/src/services.dart @@ -19,7 +19,7 @@ dynamic _loadYamlFile(String path) { 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 @@ Future parseServiceConfigs( } 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 @@ Future getServiceFromUrl( File generateServiceDefinitions( String dir, List> servicesIn ) { - List> services = + final List> services = servicesIn.map((Map service) => { 'name': service['name'], 'class': service['android-class'] }).toList(); - Map json = { 'services': services }; - File servicesFile = fs.file(fs.path.join(dir, 'services.json')); + final Map json = { '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 958a688e18..a1c31978d1 100644 --- a/packages/flutter_tools/lib/src/template.dart +++ b/packages/flutter_tools/lib/src/template.dart @@ -30,7 +30,7 @@ class Template { return; } - List templateFiles = templateSource.listSync(recursive: true); + final List templateFiles = templateSource.listSync(recursive: true); for (FileSystemEntity entity in templateFiles) { if (entity is! File) { @@ -38,7 +38,7 @@ class Template { 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 @@ class Template { 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 @@ class Template { 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 @@ class Template { .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 @@ class Template { 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 @@ class Template { // 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 @@ class Template { } 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 44fa13361b..78ff476af8 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 @@ class CoverageCollector { assert(process != null); assert(port != null); - int pid = process.pid; + final int pid = process.pid; int exitCode; process.exitCode.then((int code) { exitCode = code; @@ -68,12 +68,12 @@ class CoverageCollector { if (_globalHitmap == null) return null; if (formatter == null) { - coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath); - String packagePath = fs.currentDirectory.path; - List reportOn = [fs.path.join(packagePath, 'lib')]; + final coverage.Resolver resolver = new coverage.Resolver(packagesPath: PackageMap.globalPackagesPath); + final String packagePath = fs.currentDirectory.path; + final List reportOn = [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 5fafa71236..eff482a908 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 localController = new StreamController(); - StreamController remoteController = new StreamController(); - Completer testCompleteCompleter = new Completer(); - _FlutterPlatformStreamSinkWrapper remoteSink = new _FlutterPlatformStreamSinkWrapper( + final StreamController localController = new StreamController(); + final StreamController remoteController = new StreamController(); + final Completer testCompleteCompleter = new Completer(); + final _FlutterPlatformStreamSinkWrapper remoteSink = new _FlutterPlatformStreamSinkWrapper( remoteController.sink, testCompleteCompleter.future, ); - StreamChannel localChannel = new StreamChannel.withGuarantees( + final StreamChannel localChannel = new StreamChannel.withGuarantees( remoteController.stream, localController.sink, ); - StreamChannel remoteChannel = new StreamChannel.withGuarantees( + final StreamChannel remoteChannel = new StreamChannel.withGuarantees( localController.stream, remoteSink, ); @@ -135,12 +135,12 @@ class _FlutterPlatform extends PlatformPlugin { 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 = new Completer(); + final Completer webSocket = new Completer(); server.listen( (HttpRequest request) { webSocket.complete(WebSocketTransformer.upgrade(request)); @@ -159,14 +159,14 @@ class _FlutterPlatform extends PlatformPlugin { ); // 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 @@ class _FlutterPlatform extends PlatformPlugin { // 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 timeout = new Completer(); + final Completer timeout = new Completer(); // 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 @@ class _FlutterPlatform extends PlatformPlugin { // The local test harness could get bored of us. printTrace('test $ourTestCount: awaiting initial result for pid ${process.pid}'); - _InitialResult initialResult = await Future.any(>[ + final _InitialResult initialResult = await Future.any(>[ 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 harnessDone = new Completer(); - StreamSubscription harnessToTest = controller.stream.listen( + final Completer harnessDone = new Completer(); + final StreamSubscription harnessToTest = controller.stream.listen( (dynamic event) { testSocket.add(JSON.encode(event)); }, onDone: () { harnessDone.complete(); }, onError: (dynamic error, dynamic stack) { @@ -279,8 +279,8 @@ class _FlutterPlatform extends PlatformPlugin { cancelOnError: true, ); - Completer testDone = new Completer(); - StreamSubscription testToHarness = testSocket.listen( + final Completer testDone = new Completer(); + final StreamSubscription 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 @@ class _FlutterPlatform extends PlatformPlugin { ); printTrace('test $ourTestCount: awaiting test result for pid ${process.pid}'); - _TestResult testResult = await Future.any(>[ + final _TestResult testResult = await Future.any(>[ 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 @@ class _FlutterPlatform extends PlatformPlugin { 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 @@ void main() { if (_cachedFontConfig != null) return _cachedFontConfig; - StringBuffer sb = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); sb.writeln(''); sb.writeln(' ${cache.getCacheArtifacts().path}'); sb.writeln(' /var/cache/fontconfig'); sb.writeln(''); - 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 @@ void main() { }) { assert(executable != null); // Please provide the path to the shell in the SKY_SHELL environment variable. assert(!startPaused || enableObservatory); - List command = [executable]; + final List command = [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 @@ void main() { testPath, ]); printTrace(command.join(' ')); - Map environment = { + final Map environment = { 'FLUTTER_TEST': 'true', 'FONTCONFIG_FILE': _fontConfigFile.path, }; @@ -497,7 +497,7 @@ void main() { } 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 2f4b5ec569..46749646be 100644 --- a/packages/flutter_tools/lib/src/usage.dart +++ b/packages/flutter_tools/lib/src/usage.dart @@ -20,7 +20,7 @@ Usage get flutterUsage => Usage.instance; 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 3bdd2e774e..cf8230de27 100644 --- a/packages/flutter_tools/lib/src/version.dart +++ b/packages/flutter_tools/lib/src/version.dart @@ -19,9 +19,9 @@ class FlutterVersion { 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 @@ class FlutterVersion { @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 @@ class FlutterVersion { } String _runSync(List 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 4355164d71..574fe7608d 100644 --- a/packages/flutter_tools/lib/src/vmservice.dart +++ b/packages/flutter_tools/lib/src/vmservice.dart @@ -54,9 +54,9 @@ class VMService { /// 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 delegate = _defaultOpenChannel(uri); + final StreamChannel delegate = _defaultOpenChannel(uri); return new RecordingVMServiceChannel(delegate, dir); }; } @@ -67,7 +67,7 @@ class VMService { /// 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 @@ class VMService { Uri httpUri, { Duration requestTimeout: kDefaultRequestTimeout, }) { - Uri wsUri = httpUri.replace(scheme: 'ws', path: fs.path.join(httpUri.path, 'ws')); - StreamChannel 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 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 @@ class VMService { 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 _upgradeMap(Map map, ServiceObjectOwner owner) { void _upgradeList(List list, ServiceObjectOwner owner) { for (int i = 0; i < list.length; i++) { - dynamic v = list[i]; + final dynamic v = list[i]; if ((v is Map) && _isServiceMap(v)) { list[i] = owner.getFromMap(v); } else if (v is List) { @@ -243,7 +243,7 @@ abstract class ServiceObject { 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 @@ abstract class ServiceObject { /// Fetch this object from vmService and return the response directly. Future> _fetchDirect() { - Map params = { + final Map params = { 'objectId': id, }; return _owner.isolate.invokeRpcRaw('getObject', params: params); @@ -319,22 +319,22 @@ abstract class ServiceObject { Future _inProgressReload; /// Reload the service object (if possible). Future 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 completer = new Completer(); + final Completer completer = new Completer(); _inProgressReload = completer.future; try { - Map response = await _fetchDirect(); + final Map 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 @@ class VM extends ServiceObjectOwner { final Map _viewCache = new Map(); 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 @@ class VM extends ServiceObjectOwner { } void _buildIsolateList() { - List isolateList = _isolateCache.values.toList(); + final List isolateList = _isolateCache.values.toList(); isolateList.sort(_compareIsolates); isolates.clear(); isolates.addAll(isolateList); @@ -539,11 +539,11 @@ class VM extends ServiceObjectOwner { void _removeDeadIsolates(List newIsolates) { // Build a set of new isolates. - Set newIsolateSet = new Set(); + final Set newIsolateSet = new Set(); newIsolates.forEach((Isolate iso) => newIsolateSet.add(iso.id)); // Remove any old isolates which no longer exist. - List toRemove = []; + final List toRemove = []; _isolateCache.forEach((String id, _) { if (!newIsolateSet.contains(id)) { toRemove.add(id); @@ -558,14 +558,14 @@ class VM extends ServiceObjectOwner { 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 @@ class VM extends ServiceObjectOwner { assert(params != null); timeout ??= _vmService._requestTimeout; try { - Map result = await _vmService + final Map result = await _vmService ._sendRequest(method, params) .timeout(timeout); return result; @@ -647,14 +647,14 @@ class VM extends ServiceObjectOwner { Map params: const {}, Duration timeout, }) async { - Map response = await invokeRpcRaw( + final Map 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 @@ class VM extends ServiceObjectOwner { // Read one file from a file system. Future> readDevFSFile(String fsName, String path) async { - Map response = await invokeRpcRaw( + final Map response = await invokeRpcRaw( '_readDevFSFile', params: { 'fsName': fsName, @@ -774,13 +774,13 @@ class Isolate extends ServiceObjectOwner { 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 @@ class Isolate extends ServiceObjectOwner { return; _loaded = true; - int startTimeMillis = map['startTime']; + final int startTimeMillis = map['startTime']; startTime = new DateTime.fromMillisecondsSinceEpoch(startTimeMillis); _upgradeCollection(map, this); @@ -842,7 +842,7 @@ class Isolate extends ServiceObjectOwner { Uri rootLibUri, Uri packagesUri}) async { try { - Map arguments = { + final Map arguments = { 'pause': pause }; // TODO(goderbauer): Transfer Uri (instead of file path) when remote end supports it. @@ -853,7 +853,7 @@ class Isolate extends ServiceObjectOwner { if (packagesUri != null) { arguments['packagesUri'] = packagesUri.toFilePath(windows: false); } - Map response = await invokeRpcRaw('_reloadSources', params: arguments); + final Map response = await invokeRpcRaw('_reloadSources', params: arguments); return response; } on rpc.RpcException catch(e) { return new Future>.error({ @@ -952,7 +952,7 @@ class Isolate extends ServiceObjectOwner { } Future flutterPlatformOverride([String platform]) async { - Map result = await invokeFlutterExtensionRpcRaw( + final Map result = await invokeFlutterExtensionRpcRaw( 'ext.flutter.platformOverride', params: platform != null ? { 'value': platform } : {}, 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 5e458b4840..af948e0051 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 @@ class RecordingVMServiceChannel extends DelegatingStreamChannel { // 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 @@ abstract class _Message implements Comparable<_Message> { @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 @@ class ReplayVMServiceChannel extends StreamChannelMixin { : _transactions = _loadTransactions(location); static Map _loadTransactions(Directory location) { - File file = _getManifest(location); - String json = file.readAsStringSync(); - Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage); - Map transactions = {}; + final File file = _getManifest(location); + final String json = file.readAsStringSync(); + final Iterable<_Message> messages = JSON.decoder.convert(json).map<_Message>(_toMessage); + final Map transactions = {}; 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 @@ class ReplayVMServiceChannel extends StreamChannelMixin { 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 @@ class _ReplaySink implements StreamSink { } 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 463f296a94..a7b11611cf 100644 --- a/packages/flutter_tools/lib/src/zip.dart +++ b/packages/flutter_tools/lib/src/zip.dart @@ -31,7 +31,7 @@ class _ArchiveZipBuilder extends ZipBuilder { @override Future createZip(File outFile, Directory zipBuildDir) async { - Archive archive = new Archive(); + final Archive archive = new Archive(); final Completer finished = new Completer(); int count = entries.length; @@ -45,7 +45,7 @@ class _ArchiveZipBuilder extends ZipBuilder { }); await finished.future; - List zipData = new ZipEncoder().encode(archive); + final List zipData = new ZipEncoder().encode(archive); await outFile.writeAsBytes(zipData); } } @@ -57,7 +57,7 @@ class _ZipToolBuilder extends ZipBuilder { Future createZip(File outFile, Directory zipBuildDir) async { // If there are no assets, then create an empty zip file. if (entries.isEmpty) { - List zipData = new ZipEncoder().encode(new Archive()); + final List zipData = new ZipEncoder().encode(new Archive()); await outFile.writeAsBytes(zipData); return; } @@ -73,7 +73,7 @@ class _ZipToolBuilder extends ZipBuilder { int count = entries.length; entries.forEach((String archivePath, DevFSContent content) { content.contentsAsBytes().then((List 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((File value) { count -= 1; diff --git a/packages/flutter_tools/test/adb_test.dart b/packages/flutter_tools/test/adb_test.dart index 168085bfa6..c623727e19 100644 --- a/packages/flutter_tools/test/adb_test.dart +++ b/packages/flutter_tools/test/adb_test.dart @@ -6,7 +6,7 @@ import 'package:flutter_tools/src/android/adb.dart'; import 'package:test/test.dart'; void main() { - Adb adb = new Adb('adb'); + final Adb adb = new Adb('adb'); // We only test the [Adb] class is we're able to locate the adb binary. if (!adb.exists()) @@ -20,14 +20,14 @@ void main() { test('getServerVersion', () async { adb.startServer(); - String version = await adb.getServerVersion(); + final String version = await adb.getServerVersion(); expect(version, isNotEmpty); }); test('listDevices', () async { adb.startServer(); - List devices = await adb.listDevices(); + final List devices = await adb.listDevices(); // Any result is ok. expect(devices, isList); diff --git a/packages/flutter_tools/test/analytics_test.dart b/packages/flutter_tools/test/analytics_test.dart index 6f38481aaa..2ca80ce11b 100644 --- a/packages/flutter_tools/test/analytics_test.dart +++ b/packages/flutter_tools/test/analytics_test.dart @@ -33,7 +33,7 @@ void main() { flutterUsage.onSend.listen((Map data) => count++); flutterUsage.enabled = false; - CreateCommand command = new CreateCommand(); + final CreateCommand command = new CreateCommand(); CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); expect(count, 0); @@ -44,7 +44,7 @@ void main() { count = 0; flutterUsage.enabled = false; - DoctorCommand doctorCommand = new DoctorCommand(); + final DoctorCommand doctorCommand = new DoctorCommand(); runner = createTestCommandRunner(doctorCommand); await runner.run(['doctor']); expect(count, 0); @@ -58,8 +58,8 @@ void main() { flutterUsage.onSend.listen((Map data) => count++); flutterUsage.enabled = false; - ConfigCommand command = new ConfigCommand(); - CommandRunner runner = createTestCommandRunner(command); + final ConfigCommand command = new ConfigCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['config']); expect(count, 0); diff --git a/packages/flutter_tools/test/analyze_continuously_test.dart b/packages/flutter_tools/test/analyze_continuously_test.dart index 672df6073b..87789d4f27 100644 --- a/packages/flutter_tools/test/analyze_continuously_test.dart +++ b/packages/flutter_tools/test/analyze_continuously_test.dart @@ -37,7 +37,7 @@ void main() { server = new AnalysisServer(dartSdkPath, [tempDir.path]); int errorCount = 0; - Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; + final Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); await server.start(); @@ -57,7 +57,7 @@ void main() { server = new AnalysisServer(dartSdkPath, [tempDir.path]); int errorCount = 0; - Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; + final Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); await server.start(); @@ -70,12 +70,12 @@ void main() { } void _createSampleProject(Directory directory, { bool brokenCode: false }) { - File pubspecFile = fs.file(fs.path.join(directory.path, 'pubspec.yaml')); + final File pubspecFile = fs.file(fs.path.join(directory.path, 'pubspec.yaml')); pubspecFile.writeAsStringSync(''' name: foo_project '''); - File dartFile = fs.file(fs.path.join(directory.path, 'lib', 'main.dart')); + final File dartFile = fs.file(fs.path.join(directory.path, 'lib', 'main.dart')); dartFile.parent.createSync(); dartFile.writeAsStringSync(''' void main() { diff --git a/packages/flutter_tools/test/analyze_duplicate_names_test.dart b/packages/flutter_tools/test/analyze_duplicate_names_test.dart index 81d434bfd0..a4d9eeb271 100644 --- a/packages/flutter_tools/test/analyze_duplicate_names_test.dart +++ b/packages/flutter_tools/test/analyze_duplicate_names_test.dart @@ -23,13 +23,13 @@ void main() { group('analyze', () { testUsingContext('flutter analyze with two files with the same name', () async { - File dartFileA = fs.file(fs.path.join(tempDir.path, 'a.dart')); + final File dartFileA = fs.file(fs.path.join(tempDir.path, 'a.dart')); dartFileA.parent.createSync(); dartFileA.writeAsStringSync('library test;'); - File dartFileB = fs.file(fs.path.join(tempDir.path, 'b.dart')); + final File dartFileB = fs.file(fs.path.join(tempDir.path, 'b.dart')); dartFileB.writeAsStringSync('library test;'); - AnalyzeCommand command = new AnalyzeCommand(); + final AnalyzeCommand command = new AnalyzeCommand(); applyMocksToCommand(command); return createTestCommandRunner(command).run( ['analyze', '--no-current-package', '--no-current-directory', dartFileA.path, dartFileB.path] diff --git a/packages/flutter_tools/test/analyze_test.dart b/packages/flutter_tools/test/analyze_test.dart index e8ddc66e9a..9c17c8e31e 100644 --- a/packages/flutter_tools/test/analyze_test.dart +++ b/packages/flutter_tools/test/analyze_test.dart @@ -31,7 +31,7 @@ void main() { expect(inRepo([Cache.flutterRoot]), isTrue); expect(inRepo([fs.path.join(Cache.flutterRoot, 'foo')]), isTrue); // Relative paths - String oldWorkingDirectory = fs.currentDirectory.path; + final String oldWorkingDirectory = fs.currentDirectory.path; try { fs.currentDirectory = Cache.flutterRoot; expect(inRepo(['.']), isTrue); diff --git a/packages/flutter_tools/test/android_device_test.dart b/packages/flutter_tools/test/android_device_test.dart index e5840e93bc..c9b85f25fd 100644 --- a/packages/flutter_tools/test/android_device_test.dart +++ b/packages/flutter_tools/test/android_device_test.dart @@ -10,15 +10,15 @@ import 'src/context.dart'; void main() { group('android_device', () { testUsingContext('stores the requested id', () { - String deviceId = '1234'; - AndroidDevice device = new AndroidDevice(deviceId); + final String deviceId = '1234'; + final AndroidDevice device = new AndroidDevice(deviceId); expect(device.id, deviceId); }); }); group('getAdbDevices', () { testUsingContext('physical devices', () { - List devices = getAdbDevices(mockAdbOutput: ''' + final List devices = getAdbDevices(mockAdbOutput: ''' List of devices attached 05a02bac device usb:336592896X product:razor model:Nexus_7 device:flo @@ -28,7 +28,7 @@ List of devices attached }); testUsingContext('emulators and short listings', () { - List devices = getAdbDevices(mockAdbOutput: ''' + final List devices = getAdbDevices(mockAdbOutput: ''' List of devices attached localhost:36790 device 0149947A0D01500C device usb:340787200X @@ -40,7 +40,7 @@ emulator-5612 host features:shell_2 }); testUsingContext('android n', () { - List devices = getAdbDevices(mockAdbOutput: ''' + final List devices = getAdbDevices(mockAdbOutput: ''' List of devices attached ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu features:cmd,shell_v2 '''); @@ -49,7 +49,7 @@ ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu f }); testUsingContext('adb error message', () { - List devices = getAdbDevices(mockAdbOutput: ''' + final List devices = getAdbDevices(mockAdbOutput: ''' It appears you do not have 'Android SDK Platform-tools' installed. Use the 'android' tool to install them: android update sdk --no-ui --filter 'platform-tools' @@ -61,7 +61,7 @@ Use the 'android' tool to install them: group('parseAdbDeviceProperties', () { test('parse adb shell output', () { - Map properties = parseAdbDeviceProperties(kAdbShellGetprop); + final Map properties = parseAdbDeviceProperties(kAdbShellGetprop); expect(properties, isNotNull); expect(properties['ro.build.characteristics'], 'emulator'); expect(properties['ro.product.cpu.abi'], 'x86_64'); diff --git a/packages/flutter_tools/test/android_sdk_test.dart b/packages/flutter_tools/test/android_sdk_test.dart index ebfbbf629b..e9227b117f 100644 --- a/packages/flutter_tools/test/android_sdk_test.dart +++ b/packages/flutter_tools/test/android_sdk_test.dart @@ -18,7 +18,7 @@ void main() { testUsingContext('parse sdk', () { sdkDir = _createSdkDirectory(); - AndroidSdk sdk = new AndroidSdk(sdkDir.path); + final AndroidSdk sdk = new AndroidSdk(sdkDir.path); expect(sdk.latestVersion, isNotNull); expect(sdk.latestVersion.sdkLevel, 23); @@ -26,7 +26,7 @@ void main() { testUsingContext('parse sdk N', () { sdkDir = _createSdkDirectory(withAndroidN: true); - AndroidSdk sdk = new AndroidSdk(sdkDir.path); + final AndroidSdk sdk = new AndroidSdk(sdkDir.path); expect(sdk.latestVersion, isNotNull); expect(sdk.latestVersion.sdkLevel, 24); @@ -35,15 +35,15 @@ void main() { group('android_sdk AndroidSdkVersion', () { testUsingContext('parse normal', () { - AndroidSdk sdk = new AndroidSdk('.'); - AndroidSdkVersion ver = new AndroidSdkVersion(sdk, + final AndroidSdk sdk = new AndroidSdk('.'); + final AndroidSdkVersion ver = new AndroidSdkVersion(sdk, platformVersionName: 'android-23', buildToolsVersionName: '23.0.0'); expect(ver.sdkLevel, 23); }); testUsingContext('parse android n', () { - AndroidSdk sdk = new AndroidSdk('.'); - AndroidSdkVersion ver = new AndroidSdkVersion(sdk, + final AndroidSdk sdk = new AndroidSdk('.'); + final AndroidSdkVersion ver = new AndroidSdkVersion(sdk, platformVersionName: 'android-N', buildToolsVersionName: '24.0.0'); expect(ver.sdkLevel, 24); }); @@ -51,7 +51,7 @@ void main() { } Directory _createSdkDirectory({ bool withAndroidN: false }) { - Directory dir = fs.systemTempDirectory.createTempSync('android-sdk'); + final Directory dir = fs.systemTempDirectory.createTempSync('android-sdk'); _createSdkFile(dir, 'platform-tools/adb'); @@ -70,6 +70,6 @@ Directory _createSdkDirectory({ bool withAndroidN: false }) { } void _createSdkFile(Directory dir, String filePath) { - File file = fs.file(fs.path.join(dir.path, filePath)); + final File file = fs.file(fs.path.join(dir.path, filePath)); file.createSync(recursive: true); } diff --git a/packages/flutter_tools/test/application_package_test.dart b/packages/flutter_tools/test/application_package_test.dart index 3ad42a558e..12aa8ba4e2 100644 --- a/packages/flutter_tools/test/application_package_test.dart +++ b/packages/flutter_tools/test/application_package_test.dart @@ -10,7 +10,7 @@ import 'src/context.dart'; void main() { group('ApkManifestData', () { testUsingContext('parse sdk', () { - ApkManifestData data = ApkManifestData.parseFromAaptBadging(_aaptData); + final ApkManifestData data = ApkManifestData.parseFromAaptBadging(_aaptData); expect(data, isNotNull); expect(data.packageName, 'io.flutter.gallery'); expect(data.launchableActivityName, 'io.flutter.app.FlutterActivity'); diff --git a/packages/flutter_tools/test/asset_bundle_test.dart b/packages/flutter_tools/test/asset_bundle_test.dart index bc720969ad..e2e6db843a 100644 --- a/packages/flutter_tools/test/asset_bundle_test.dart +++ b/packages/flutter_tools/test/asset_bundle_test.dart @@ -10,12 +10,12 @@ import 'package:test/test.dart'; void main() { // Create a temporary directory and write a single file into it. - FileSystem fs = const LocalFileSystem(); - Directory tempDir = fs.systemTempDirectory.createTempSync(); - String projectRoot = tempDir.path; - String assetPath = 'banana.txt'; - String assetContents = 'banana'; - File tempFile = fs.file(fs.path.join(projectRoot, assetPath)); + final FileSystem fs = const LocalFileSystem(); + final Directory tempDir = fs.systemTempDirectory.createTempSync(); + final String projectRoot = tempDir.path; + final String assetPath = 'banana.txt'; + final String assetContents = 'banana'; + final File tempFile = fs.file(fs.path.join(projectRoot, assetPath)); tempFile.parent.createSync(recursive: true); tempFile.writeAsBytesSync(UTF8.encode(assetContents)); @@ -30,31 +30,31 @@ void main() { expect(new AssetBundle.fixed(null, null).needsBuild(), isFalse); }); test('empty string', () async { - AssetBundle ab = new AssetBundle.fixed('', ''); + final AssetBundle ab = new AssetBundle.fixed('', ''); expect(ab.entries, isEmpty); }); test('single entry', () async { - AssetBundle ab = new AssetBundle.fixed('', 'apple.txt'); + final AssetBundle ab = new AssetBundle.fixed('', 'apple.txt'); expect(ab.entries, isNotEmpty); expect(ab.entries.length, 1); - String archivePath = ab.entries.keys.first; + final String archivePath = ab.entries.keys.first; expect(archivePath, isNotNull); expect(archivePath, 'apple.txt'); }); test('two entries', () async { - AssetBundle ab = new AssetBundle.fixed('', 'apple.txt,packages/flutter_gallery_assets/shrine/products/heels.png'); + final AssetBundle ab = new AssetBundle.fixed('', 'apple.txt,packages/flutter_gallery_assets/shrine/products/heels.png'); expect(ab.entries, isNotEmpty); expect(ab.entries.length, 2); - List archivePaths = ab.entries.keys.toList()..sort(); + final List archivePaths = ab.entries.keys.toList()..sort(); expect(archivePaths[0], 'apple.txt'); expect(archivePaths[1], 'packages/flutter_gallery_assets/shrine/products/heels.png'); }); test('file contents', () async { - AssetBundle ab = new AssetBundle.fixed(projectRoot, assetPath); + final AssetBundle ab = new AssetBundle.fixed(projectRoot, assetPath); expect(ab.entries, isNotEmpty); expect(ab.entries.length, 1); - String archivePath = ab.entries.keys.first; - DevFSContent content = ab.entries[archivePath]; + final String archivePath = ab.entries.keys.first; + final DevFSContent content = ab.entries[archivePath]; expect(archivePath, assetPath); expect(assetContents, UTF8.decode(await content.contentsAsBytes())); }); @@ -62,7 +62,7 @@ void main() { group('AssetBundle.build', () { test('nonempty', () async { - AssetBundle ab = new AssetBundle(); + final AssetBundle ab = new AssetBundle(); expect(await ab.build(), 0); expect(ab.entries.length, greaterThan(0)); }); diff --git a/packages/flutter_tools/test/base_utils_test.dart b/packages/flutter_tools/test/base_utils_test.dart index ad5a47d982..a1d46f3154 100644 --- a/packages/flutter_tools/test/base_utils_test.dart +++ b/packages/flutter_tools/test/base_utils_test.dart @@ -10,19 +10,19 @@ import 'package:test/test.dart'; void main() { group('ItemListNotifier', () { test('sends notifications', () async { - ItemListNotifier list = new ItemListNotifier(); + final ItemListNotifier list = new ItemListNotifier(); expect(list.items, isEmpty); - Future> addedStreamItems = list.onAdded.toList(); - Future> removedStreamItems = list.onRemoved.toList(); + final Future> addedStreamItems = list.onAdded.toList(); + final Future> removedStreamItems = list.onRemoved.toList(); list.updateWithNewList(['aaa']); list.updateWithNewList(['aaa', 'bbb']); list.updateWithNewList(['bbb']); list.dispose(); - List addedItems = await addedStreamItems; - List removedItems = await removedStreamItems; + final List addedItems = await addedStreamItems; + final List removedItems = await removedStreamItems; expect(addedItems.length, 2); expect(addedItems.first, 'aaa'); diff --git a/packages/flutter_tools/test/channel_test.dart b/packages/flutter_tools/test/channel_test.dart index 987fba2bf7..7e5fbac8a2 100644 --- a/packages/flutter_tools/test/channel_test.dart +++ b/packages/flutter_tools/test/channel_test.dart @@ -12,8 +12,8 @@ import 'src/context.dart'; void main() { group('channel', () { testUsingContext('list', () async { - ChannelCommand command = new ChannelCommand(); - CommandRunner runner = createTestCommandRunner(command); + final ChannelCommand command = new ChannelCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['channel']); expect(testLogger.errorText, hasLength(0)); // The bots may return an empty list of channels (network hiccup?) diff --git a/packages/flutter_tools/test/config_test.dart b/packages/flutter_tools/test/config_test.dart index 868dd3287e..2c36bc4797 100644 --- a/packages/flutter_tools/test/config_test.dart +++ b/packages/flutter_tools/test/config_test.dart @@ -10,8 +10,8 @@ void main() { Config config; setUp(() { - Directory tempDiretory = fs.systemTempDirectory.createTempSync('flutter_test'); - File file = fs.file(fs.path.join(tempDiretory.path, '.settings')); + final Directory tempDiretory = fs.systemTempDirectory.createTempSync('flutter_test'); + final File file = fs.file(fs.path.join(tempDiretory.path, '.settings')); config = new Config(file); }); diff --git a/packages/flutter_tools/test/context_test.dart b/packages/flutter_tools/test/context_test.dart index d6601233b0..365e3fa770 100644 --- a/packages/flutter_tools/test/context_test.dart +++ b/packages/flutter_tools/test/context_test.dart @@ -11,8 +11,8 @@ import 'package:test/test.dart'; void main() { group('AppContext', () { test('error', () async { - AppContext context = new AppContext(); - BufferLogger mockLogger = new BufferLogger(); + final AppContext context = new AppContext(); + final BufferLogger mockLogger = new BufferLogger(); context.setVariable(Logger, mockLogger); await context.runInZone(() { @@ -25,8 +25,8 @@ void main() { }); test('status', () async { - AppContext context = new AppContext(); - BufferLogger mockLogger = new BufferLogger(); + final AppContext context = new AppContext(); + final BufferLogger mockLogger = new BufferLogger(); context.setVariable(Logger, mockLogger); await context.runInZone(() { @@ -39,8 +39,8 @@ void main() { }); test('trace', () async { - AppContext context = new AppContext(); - BufferLogger mockLogger = new BufferLogger(); + final AppContext context = new AppContext(); + final BufferLogger mockLogger = new BufferLogger(); context.setVariable(Logger, mockLogger); await context.runInZone(() { @@ -53,11 +53,11 @@ void main() { }); test('awaitNestedZones', () async { - AppContext outerContext = new AppContext(); + final AppContext outerContext = new AppContext(); await outerContext.runInZone(() async { - AppContext middleContext = new AppContext(); + final AppContext middleContext = new AppContext(); await middleContext.runInZone(() async { - AppContext innerContext = new AppContext(); + final AppContext innerContext = new AppContext(); await innerContext.runInZone(() async { expect(innerContext.getVariable(String), isNull); }); @@ -66,11 +66,11 @@ void main() { }); test('fireAndForgetNestedZones', () async { - AppContext outerContext = new AppContext(); + final AppContext outerContext = new AppContext(); outerContext.runInZone(() async { - AppContext middleContext = new AppContext(); + final AppContext middleContext = new AppContext(); middleContext.runInZone(() async { - AppContext innerContext = new AppContext(); + final AppContext innerContext = new AppContext(); innerContext.runInZone(() async { expect(innerContext.getVariable(String), isNull); }); @@ -80,15 +80,15 @@ void main() { test('overriddenValuesInNestedZones', () async { expect(pkg.context, isNull); - AppContext outerContext = new AppContext(); + final AppContext outerContext = new AppContext(); outerContext.setVariable(String, 'outer'); outerContext.runInZone(() async { expect(pkg.context[String], 'outer'); - AppContext middleContext = new AppContext(); + final AppContext middleContext = new AppContext(); middleContext.setVariable(String, 'middle'); middleContext.runInZone(() async { expect(pkg.context[String], 'middle'); - AppContext innerContext = new AppContext(); + final AppContext innerContext = new AppContext(); innerContext.setVariable(String, 'inner'); innerContext.runInZone(() async { expect(pkg.context[String], 'inner'); diff --git a/packages/flutter_tools/test/crash_reporting_test.dart b/packages/flutter_tools/test/crash_reporting_test.dart index a6ef5feb50..b1172fbfb0 100644 --- a/packages/flutter_tools/test/crash_reporting_test.dart +++ b/packages/flutter_tools/test/crash_reporting_test.dart @@ -50,7 +50,7 @@ void main() { ); })); - int exitCode = await tools.run( + final int exitCode = await tools.run( ['crash'], [new _CrashCommand()], reportCrashes: true, @@ -71,12 +71,12 @@ void main() { 'version' : 'test-version', }, )); - BufferLogger logger = context[Logger]; + final BufferLogger logger = context[Logger]; expect(logger.statusText, 'Sending crash report to Google.\n' 'Crash report sent (report ID: test-report-id)\n'); // Verify that we've written the crash report to disk. - List writtenFiles = + final List writtenFiles = (await tools.crashFileSystem.directory('/').list(recursive: true).toList()) .map((FileSystemEntity e) => e.path).toList(); expect(writtenFiles, hasLength(1)); diff --git a/packages/flutter_tools/test/create_test.dart b/packages/flutter_tools/test/create_test.dart index 6c9ffedecc..1c6d2d0307 100644 --- a/packages/flutter_tools/test/create_test.dart +++ b/packages/flutter_tools/test/create_test.dart @@ -42,8 +42,8 @@ void main() { testUsingContext('content', () async { Cache.flutterRoot = '../..'; - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); @@ -53,14 +53,14 @@ void main() { expectExists('lib/main.dart'); for (FileSystemEntity file in temp.listSync(recursive: true)) { if (file is File && file.path.endsWith('.dart')) { - String original= file.readAsStringSync(); + final String original= file.readAsStringSync(); - Process process = await Process.start( + final Process process = await Process.start( sdkBinaryName('dartfmt'), [file.path], workingDirectory: temp.path, ); - String formatted = + final String formatted = await process.stdout.transform(UTF8.decoder).join(); expect(original, formatted, reason: file.path); @@ -68,10 +68,10 @@ void main() { } // Generated Xcode settings - String xcodeConfigPath = fs.path.join('ios', 'Flutter', 'Generated.xcconfig'); + final String xcodeConfigPath = fs.path.join('ios', 'Flutter', 'Generated.xcconfig'); expectExists(xcodeConfigPath); - File xcodeConfigFile = fs.file(fs.path.join(temp.path, xcodeConfigPath)); - String xcodeConfig = xcodeConfigFile.readAsStringSync(); + final File xcodeConfigFile = fs.file(fs.path.join(temp.path, xcodeConfigPath)); + final String xcodeConfig = xcodeConfigFile.readAsStringSync(); expect(xcodeConfig, contains('FLUTTER_ROOT=')); expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH=')); expect(xcodeConfig, contains('FLUTTER_FRAMEWORK_DIR=')); @@ -81,8 +81,8 @@ void main() { testUsingContext('can re-gen over existing project', () async { Cache.flutterRoot = '../..'; - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); @@ -93,8 +93,8 @@ void main() { testUsingContext('produces sensible error message', () async { Cache.flutterRoot = '../..'; - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); try { await runner.run(['create', temp.path, '--pub']); @@ -108,9 +108,9 @@ void main() { // Verify that we fail with an error code when the file exists. testUsingContext('fails when file exists', () async { Cache.flutterRoot = '../..'; - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); - File existingFile = fs.file("${temp.path.toString()}/bad"); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); + final File existingFile = fs.file("${temp.path.toString()}/bad"); if (!existingFile.existsSync()) existingFile.createSync(); try { await runner.run(['create', existingFile.path]); @@ -124,17 +124,17 @@ void main() { Future _createAndAnalyzeProject(Directory dir, List createArgs) async { Cache.flutterRoot = '../..'; - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); - List args = ['create']; + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); + final List args = ['create']; args.addAll(createArgs); args.add(dir.path); await runner.run(args); - String mainPath = fs.path.join(dir.path, 'lib', 'main.dart'); + final String mainPath = fs.path.join(dir.path, 'lib', 'main.dart'); expect(fs.file(mainPath).existsSync(), true); - String flutterToolsPath = fs.path.absolute(fs.path.join('bin', 'flutter_tools.dart')); - ProcessResult exec = Process.runSync( + final String flutterToolsPath = fs.path.absolute(fs.path.join('bin', 'flutter_tools.dart')); + final ProcessResult exec = Process.runSync( '$dartSdkPath/bin/dart', [flutterToolsPath, 'analyze'], workingDirectory: dir.path ); diff --git a/packages/flutter_tools/test/daemon_test.dart b/packages/flutter_tools/test/daemon_test.dart index b08f12106a..761a0bd5e4 100644 --- a/packages/flutter_tools/test/daemon_test.dart +++ b/packages/flutter_tools/test/daemon_test.dart @@ -47,15 +47,15 @@ void main() { }); _testUsingContext('daemon.version', () async { - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), notifyingLogger: notifyingLogger ); commands.add({'id': 0, 'method': 'daemon.version'}); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['result'], isNotEmpty); expect(response['result'] is String, true); @@ -65,20 +65,20 @@ void main() { _testUsingContext('daemon.logMessage', () { return appContext.runInZone(() async { - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), notifyingLogger: notifyingLogger ); printError('daemon.logMessage test'); - Map response = await responses.stream.where((Map map) { + final Map response = await responses.stream.where((Map map) { return map['event'] == 'daemon.logMessage' && map['params']['level'] == 'error'; }).first; expect(response['id'], isNull); expect(response['event'], 'daemon.logMessage'); - Map logMessage = response['params']; + final Map logMessage = response['params']; expect(logMessage['level'], 'error'); expect(logMessage['message'], 'daemon.logMessage test'); responses.close(); @@ -87,12 +87,12 @@ void main() { }); _testUsingContext('daemon.logMessage logToStdout', () async { - StringBuffer buffer = new StringBuffer(); + final StringBuffer buffer = new StringBuffer(); await runZoned(() async { return appContext.runInZone(() async { - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -111,8 +111,8 @@ void main() { }); _testUsingContext('daemon.shutdown', () async { - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -127,11 +127,11 @@ void main() { }); _testUsingContext('daemon.start', () async { - DaemonCommand command = new DaemonCommand(); + final DaemonCommand command = new DaemonCommand(); applyMocksToCommand(command); - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -140,7 +140,7 @@ void main() { ); commands.add({ 'id': 0, 'method': 'app.start' }); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['error'], contains('deviceId is required')); responses.close(); @@ -148,11 +148,11 @@ void main() { }); _testUsingContext('daemon.restart', () async { - DaemonCommand command = new DaemonCommand(); + final DaemonCommand command = new DaemonCommand(); applyMocksToCommand(command); - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -161,7 +161,7 @@ void main() { ); commands.add({ 'id': 0, 'method': 'app.restart' }); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['error'], contains('appId is required')); responses.close(); @@ -169,11 +169,11 @@ void main() { }); _testUsingContext('daemon.callServiceExtension', () async { - DaemonCommand command = new DaemonCommand(); + final DaemonCommand command = new DaemonCommand(); applyMocksToCommand(command); - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -188,7 +188,7 @@ void main() { 'methodName': 'ext.flutter.debugPaint' } }); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['error'], contains('appId is required')); responses.close(); @@ -196,11 +196,11 @@ void main() { }); _testUsingContext('daemon.stop', () async { - DaemonCommand command = new DaemonCommand(); + final DaemonCommand command = new DaemonCommand(); applyMocksToCommand(command); - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), @@ -209,7 +209,7 @@ void main() { ); commands.add({ 'id': 0, 'method': 'app.stop' }); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['error'], contains('appId is required')); responses.close(); @@ -217,15 +217,15 @@ void main() { }); _testUsingContext('device.getDevices', () async { - StreamController> commands = new StreamController>(); - StreamController> responses = new StreamController>(); + final StreamController> commands = new StreamController>(); + final StreamController> responses = new StreamController>(); daemon = new Daemon( commands.stream, (Map result) => responses.add(result), notifyingLogger: notifyingLogger ); commands.add({'id': 0, 'method': 'device.getDevices'}); - Map response = await responses.stream.where(_notEvent).first; + final Map response = await responses.stream.where(_notEvent).first; expect(response['id'], 0); expect(response['result'], isList); responses.close(); diff --git a/packages/flutter_tools/test/dart_dependencies_test.dart b/packages/flutter_tools/test/dart_dependencies_test.dart index 9784d6752c..960574ca04 100644 --- a/packages/flutter_tools/test/dart_dependencies_test.dart +++ b/packages/flutter_tools/test/dart_dependencies_test.dart @@ -16,9 +16,9 @@ void main() { final String testPath = fs.path.join(dataPath, 'good'); final String mainPath = fs.path.join(testPath, 'main.dart'); final String packagesPath = fs.path.join(testPath, '.packages'); - DartDependencySetBuilder builder = + final DartDependencySetBuilder builder = new DartDependencySetBuilder(mainPath, testPath, packagesPath); - Set dependencies = builder.build(); + final Set dependencies = builder.build(); expect(dependencies.contains(mainPath), isTrue); expect(dependencies.contains(fs.path.join(testPath, 'foo.dart')), isTrue); }); @@ -26,7 +26,7 @@ void main() { final String testPath = fs.path.join(dataPath, 'syntax_error'); final String mainPath = fs.path.join(testPath, 'main.dart'); final String packagesPath = fs.path.join(testPath, '.packages'); - DartDependencySetBuilder builder = + final DartDependencySetBuilder builder = new DartDependencySetBuilder(mainPath, testPath, packagesPath); try { builder.build(); diff --git a/packages/flutter_tools/test/dependency_checker_test.dart b/packages/flutter_tools/test/dependency_checker_test.dart index 30ea979677..e20cd05f25 100644 --- a/packages/flutter_tools/test/dependency_checker_test.dart +++ b/packages/flutter_tools/test/dependency_checker_test.dart @@ -30,13 +30,13 @@ void main() { final String fooPath = fs.path.join(testPath, 'foo.dart'); final String barPath = fs.path.join(testPath, 'lib', 'bar.dart'); final String packagesPath = fs.path.join(testPath, '.packages'); - DartDependencySetBuilder builder = + final DartDependencySetBuilder builder = new DartDependencySetBuilder(mainPath, testPath, packagesPath); - DependencyChecker dependencyChecker = + final DependencyChecker dependencyChecker = new DependencyChecker(builder, null); // Set file modification time on all dependencies to be in the past. - DateTime baseTime = new DateTime.now(); + final DateTime baseTime = new DateTime.now(); updateFileModificationTime(packagesPath, baseTime, -10); updateFileModificationTime(mainPath, baseTime, -10); updateFileModificationTime(fooPath, baseTime, -10); @@ -62,12 +62,12 @@ void main() { final String fooPath = fs.path.join(testPath, 'foo.dart'); final String packagesPath = fs.path.join(testPath, '.packages'); - DartDependencySetBuilder builder = + final DartDependencySetBuilder builder = new DartDependencySetBuilder(mainPath, testPath, packagesPath); - DependencyChecker dependencyChecker = + final DependencyChecker dependencyChecker = new DependencyChecker(builder, null); - DateTime baseTime = new DateTime.now(); + final DateTime baseTime = new DateTime.now(); // Set file modification time on all dependencies to be in the past. updateFileModificationTime(packagesPath, baseTime, -10); @@ -84,10 +84,10 @@ void main() { /// Tests that the flutter tool doesn't crash and displays a warning when its own location /// changed since it was last referenced to in a package's .packages file. testUsingContext('moved flutter sdk', () async { - Directory destinationPath = fs.systemTempDirectory.createTempSync('dependency_checker_test_'); + final Directory destinationPath = fs.systemTempDirectory.createTempSync('dependency_checker_test_'); // Copy the golden input and let the test run in an isolated temporary in-memory file system. - LocalFileSystem localFileSystem = const LocalFileSystem(); - Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location')); + final LocalFileSystem localFileSystem = const LocalFileSystem(); + final Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location')); copyDirectorySync(sourcePath, destinationPath); fs.currentDirectory = destinationPath; diff --git a/packages/flutter_tools/test/devfs_test.dart b/packages/flutter_tools/test/devfs_test.dart index c802a9befb..c21070f6dc 100644 --- a/packages/flutter_tools/test/devfs_test.dart +++ b/packages/flutter_tools/test/devfs_test.dart @@ -27,7 +27,7 @@ void main() { group('DevFSContent', () { test('bytes', () { - DevFSByteContent content = new DevFSByteContent([4, 5, 6]); + final DevFSByteContent content = new DevFSByteContent([4, 5, 6]); expect(content.bytes, orderedEquals([4, 5, 6])); expect(content.isModified, isTrue); expect(content.isModified, isFalse); @@ -37,7 +37,7 @@ void main() { expect(content.isModified, isFalse); }); test('string', () { - DevFSStringContent content = new DevFSStringContent('some string'); + final DevFSStringContent content = new DevFSStringContent('some string'); expect(content.string, 'some string'); expect(content.bytes, orderedEquals(UTF8.encode('some string'))); expect(content.isModified, isTrue); @@ -56,7 +56,7 @@ void main() { }); group('devfs local', () { - MockDevFSOperations devFSOperations = new MockDevFSOperations(); + final MockDevFSOperations devFSOperations = new MockDevFSOperations(); setUpAll(() { tempDir = _newTempDir(); @@ -66,7 +66,7 @@ void main() { testUsingContext('create dev file system', () async { // simulate workspace - File file = fs.file(fs.path.join(basePath, filePath)); + final File file = fs.file(fs.path.join(basePath, filePath)); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3]); _packages['my_project'] = fs.path.toUri('lib'); @@ -79,7 +79,7 @@ void main() { devFSOperations.expectMessages(['create test']); expect(devFS.assetPathsToEvict, isEmpty); - int bytes = await devFS.update(); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ 'writeFile test .packages', 'writeFile test lib/foo.txt', @@ -87,7 +87,7 @@ void main() { ]); expect(devFS.assetPathsToEvict, isEmpty); - List packageSpecOnDevice = LineSplitter.split(UTF8.decode( + final List packageSpecOnDevice = LineSplitter.split(UTF8.decode( await devFSOperations.devicePathToContent[fs.path.toUri('.packages')].contentsAsBytes() )).toList(); expect(packageSpecOnDevice, @@ -97,10 +97,10 @@ void main() { expect(bytes, 48); }); testUsingContext('add new file to local file system', () async { - File file = fs.file(fs.path.join(basePath, filePath2)); + final File file = fs.file(fs.path.join(basePath, filePath2)); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3, 4, 5, 6, 7]); - int bytes = await devFS.update(); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ 'writeFile test foo/bar.txt', ]); @@ -108,7 +108,7 @@ void main() { expect(bytes, 7); }); testUsingContext('modify existing file on local file system', () async { - File file = fs.file(fs.path.join(basePath, filePath)); + final File file = fs.file(fs.path.join(basePath, filePath)); // Set the last modified time to 5 seconds in the past. updateFileModificationTime(file.path, new DateTime.now(), -5); int bytes = await devFS.update(); @@ -125,9 +125,9 @@ void main() { expect(bytes, 6); }); testUsingContext('delete a file from the local file system', () async { - File file = fs.file(fs.path.join(basePath, filePath)); + final File file = fs.file(fs.path.join(basePath, filePath)); await file.delete(); - int bytes = await devFS.update(); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ 'deleteFile test lib/foo.txt', ]); @@ -136,7 +136,7 @@ void main() { }); testUsingContext('add new package', () async { await _createPackage('newpkg', 'anotherfile.txt'); - int bytes = await devFS.update(); + final int bytes = await devFS.update(); devFSOperations.expectMessages([ 'writeFile test .packages', 'writeFile test packages/newpkg/anotherfile.txt', @@ -146,7 +146,7 @@ void main() { }); testUsingContext('add an asset bundle', () async { assetBundle.entries['a.txt'] = new DevFSStringContent('abc'); - int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory('a.txt')}', ]); @@ -156,7 +156,7 @@ void main() { }); testUsingContext('add a file to the asset bundle - bundleDirty', () async { assetBundle.entries['b.txt'] = new DevFSStringContent('abcd'); - int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); // Expect entire asset bundle written because bundleDirty is true devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory('a.txt')}', @@ -169,7 +169,7 @@ void main() { }); testUsingContext('add a file to the asset bundle', () async { assetBundle.entries['c.txt'] = new DevFSStringContent('12'); - int bytes = await devFS.update(bundle: assetBundle); + final int bytes = await devFS.update(bundle: assetBundle); devFSOperations.expectMessages([ 'writeFile test ${_inAssetBuildDirectory('c.txt')}', ]); @@ -180,7 +180,7 @@ void main() { }); testUsingContext('delete a file from the asset bundle', () async { assetBundle.entries.remove('c.txt'); - int bytes = await devFS.update(bundle: assetBundle); + final int bytes = await devFS.update(bundle: assetBundle); devFSOperations.expectMessages([ 'deleteFile test ${_inAssetBuildDirectory('c.txt')}', ]); @@ -190,7 +190,7 @@ void main() { }); testUsingContext('delete all files from the asset bundle', () async { assetBundle.entries.clear(); - int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); + final int bytes = await devFS.update(bundle: assetBundle, bundleDirty: true); devFSOperations.expectMessages([ 'deleteFile test ${_inAssetBuildDirectory('a.txt')}', 'deleteFile test ${_inAssetBuildDirectory('b.txt')}', @@ -224,7 +224,7 @@ void main() { testUsingContext('create dev file system', () async { // simulate workspace - File file = fs.file(fs.path.join(basePath, filePath)); + final File file = fs.file(fs.path.join(basePath, filePath)); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3]); @@ -236,7 +236,7 @@ void main() { vmService.expectMessages(['create test']); expect(devFS.assetPathsToEvict, isEmpty); - int bytes = await devFS.update(); + final int bytes = await devFS.update(); vmService.expectMessages([ 'writeFile test .packages', 'writeFile test lib/foo.txt', @@ -273,8 +273,8 @@ class MockVMService extends BasicMock implements VMService { _server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 0); _httpAddress = Uri.parse('http://127.0.0.1:${_server.port}'); _server.listen((HttpRequest request) { - String fsName = request.headers.value('dev_fs_name'); - String devicePath = UTF8.decode(BASE64.decode(request.headers.value('dev_fs_path_b64'))); + final String fsName = request.headers.value('dev_fs_name'); + final String devicePath = UTF8.decode(BASE64.decode(request.headers.value('dev_fs_path_b64'))); messages.add('writeFile $fsName $devicePath'); request.drain>().then((List value) { request.response @@ -323,7 +323,7 @@ final List _tempDirs = []; final Map _packages = {}; Directory _newTempDir() { - Directory tempDir = fs.systemTempDirectory.createTempSync('devfs${_tempDirs.length}'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('devfs${_tempDirs.length}'); _tempDirs.add(tempDir); return tempDir; } @@ -336,11 +336,11 @@ void _cleanupTempDirs() { Future _createPackage(String pkgName, String pkgFileName) async { final Directory pkgTempDir = _newTempDir(); - File pkgFile = fs.file(fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName)); + final File pkgFile = fs.file(fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName)); await pkgFile.parent.create(recursive: true); pkgFile.writeAsBytesSync([11, 12, 13]); _packages[pkgName] = fs.path.toUri(pkgFile.parent.path); - StringBuffer sb = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); _packages.forEach((String pkgName, Uri pkgUri) { sb.writeln('$pkgName:$pkgUri'); }); diff --git a/packages/flutter_tools/test/device_test.dart b/packages/flutter_tools/test/device_test.dart index f85b442a89..f16d2e462d 100644 --- a/packages/flutter_tools/test/device_test.dart +++ b/packages/flutter_tools/test/device_test.dart @@ -13,17 +13,17 @@ void main() { group('DeviceManager', () { testUsingContext('getDevices', () async { // Test that DeviceManager.getDevices() doesn't throw. - DeviceManager deviceManager = new DeviceManager(); - List devices = await deviceManager.getDevices(); + final DeviceManager deviceManager = new DeviceManager(); + final List devices = await deviceManager.getDevices(); expect(devices, isList); }); testUsingContext('getDeviceById', () async { - _MockDevice device1 = new _MockDevice('Nexus 5', '0553790d0a4e726f'); - _MockDevice device2 = new _MockDevice('Nexus 5X', '01abfc49119c410e'); - _MockDevice device3 = new _MockDevice('iPod touch', '82564b38861a9a5'); - List devices = [device1, device2, device3]; - DeviceManager deviceManager = new TestDeviceManager(devices); + final _MockDevice device1 = new _MockDevice('Nexus 5', '0553790d0a4e726f'); + final _MockDevice device2 = new _MockDevice('Nexus 5X', '01abfc49119c410e'); + final _MockDevice device3 = new _MockDevice('iPod touch', '82564b38861a9a5'); + final List devices = [device1, device2, device3]; + final DeviceManager deviceManager = new TestDeviceManager(devices); Future expectDevice(String id, List expected) async { expect(await deviceManager.getDevicesById(id), expected); diff --git a/packages/flutter_tools/test/devices_test.dart b/packages/flutter_tools/test/devices_test.dart index 22245c4215..15645ac9e7 100644 --- a/packages/flutter_tools/test/devices_test.dart +++ b/packages/flutter_tools/test/devices_test.dart @@ -13,12 +13,12 @@ import 'src/context.dart'; void main() { group('devices', () { testUsingContext('returns 0 when called', () async { - DevicesCommand command = new DevicesCommand(); + final DevicesCommand command = new DevicesCommand(); await createTestCommandRunner(command).run(['devices']); }); testUsingContext('no error when no connected devices', () async { - DevicesCommand command = new DevicesCommand(); + final DevicesCommand command = new DevicesCommand(); await createTestCommandRunner(command).run(['devices']); expect(testLogger.statusText, contains('No devices detected')); }, overrides: { diff --git a/packages/flutter_tools/test/doctor_test.dart b/packages/flutter_tools/test/doctor_test.dart index f84a6baabe..9f48bec22a 100644 --- a/packages/flutter_tools/test/doctor_test.dart +++ b/packages/flutter_tools/test/doctor_test.dart @@ -11,7 +11,7 @@ import 'src/context.dart'; void main() { group('doctor', () { testUsingContext('intellij validator', () async { - ValidationResult result = await new IntelliJValidatorTestTarget('Test').validate(); + final ValidationResult result = await new IntelliJValidatorTestTarget('Test').validate(); expect(result.type, ValidationType.installed); expect(result.statusInfo, 'version test.test.test'); expect(result.messages, hasLength(2)); diff --git a/packages/flutter_tools/test/drive_test.dart b/packages/flutter_tools/test/drive_test.dart index 7c7bad5264..5dae69e62a 100644 --- a/packages/flutter_tools/test/drive_test.dart +++ b/packages/flutter_tools/test/drive_test.dart @@ -68,10 +68,10 @@ void main() { testUsingContext('returns 1 when test file is not found', () async { withMockDevice(); - String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); - List args = [ + final List args = [ 'drive', '--target=$testApp}', ]; @@ -90,14 +90,14 @@ void main() { withMockDevice(); appStarter = expectAsync1((DriveCommand command) async => null); - String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart'); - String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart'); + final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); - MemoryFileSystem memFs = fs; + final MemoryFileSystem memFs = fs; await memFs.file(testApp).writeAsString('main() { }'); await memFs.file(testFile).writeAsString('main() { }'); - List args = [ + final List args = [ 'drive', '--target=$testApp', ]; @@ -113,8 +113,8 @@ void main() { }); testUsingContext('returns 1 when app file is outside package', () async { - String appFile = fs.path.join(cwd.dirname, 'other_app', 'app.dart'); - List args = [ + final String appFile = fs.path.join(cwd.dirname, 'other_app', 'app.dart'); + final List args = [ 'drive', '--target=$appFile', ]; @@ -132,8 +132,8 @@ void main() { }); testUsingContext('returns 1 when app file is in the root dir', () async { - String appFile = fs.path.join(cwd.path, 'main.dart'); - List args = [ + final String appFile = fs.path.join(cwd.path, 'main.dart'); + final List args = [ 'drive', '--target=$appFile', ]; @@ -154,8 +154,8 @@ void main() { testUsingContext('returns 0 when test ends successfully', () async { withMockDevice(); - String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); @@ -168,11 +168,11 @@ void main() { return true; }); - MemoryFileSystem memFs = fs; + final MemoryFileSystem memFs = fs; await memFs.file(testApp).writeAsString('main() {}'); await memFs.file(testFile).writeAsString('main() {}'); - List args = [ + final List args = [ 'drive', '--target=$testApp', ]; @@ -185,8 +185,8 @@ void main() { testUsingContext('returns exitCode set by test runner', () async { withMockDevice(); - String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); @@ -198,11 +198,11 @@ void main() { return true; }); - MemoryFileSystem memFs = fs; + final MemoryFileSystem memFs = fs; await memFs.file(testApp).writeAsString('main() {}'); await memFs.file(testFile).writeAsString('main() {}'); - List args = [ + final List args = [ 'drive', '--target=$testApp', ]; @@ -224,7 +224,7 @@ void main() { when(mockDevice.name).thenReturn('specified-device'); when(mockDevice.id).thenReturn('123'); - Device device = await findTargetDevice(); + final Device device = await findTargetDevice(); expect(device.name, 'specified-device'); }, overrides: { FileSystem: () => fs, @@ -239,7 +239,7 @@ void main() { when(mockDevice.name).thenReturn('mock-simulator'); when(mockDevice.isLocalEmulator).thenReturn(true); - Device device = await findTargetDevice(); + final Device device = await findTargetDevice(); expect(device.name, 'mock-simulator'); }, overrides: { FileSystem: () => fs, @@ -252,7 +252,7 @@ void main() { when(mockDevice.isLocalEmulator).thenReturn(false); withMockDevice(mockDevice); - Device device = await findTargetDevice(); + final Device device = await findTargetDevice(); expect(device.name, 'mock-android-device'); }, overrides: { FileSystem: () => fs, @@ -261,12 +261,12 @@ void main() { testUsingContext('launches emulator', () async { when(SimControl.instance.boot()).thenReturn(true); - Device emulator = new MockDevice(); + final Device emulator = new MockDevice(); when(emulator.name).thenReturn('new-simulator'); when(IOSSimulatorUtils.instance.getAttachedDevices()) .thenReturn([emulator]); - Device device = await findTargetDevice(); + final Device device = await findTargetDevice(); expect(device.name, 'new-simulator'); }, overrides: { FileSystem: () => fs, @@ -291,7 +291,7 @@ void main() { when(mockDevice.name).thenReturn('mock-android-device'); withMockDevice(mockDevice); - Device device = await findTargetDevice(); + final Device device = await findTargetDevice(); expect(device.name, 'mock-android-device'); }, overrides: { FileSystem: () => fs, diff --git a/packages/flutter_tools/test/forbidden_imports_test.dart b/packages/flutter_tools/test/forbidden_imports_test.dart index 2846d0be8a..305c900af7 100644 --- a/packages/flutter_tools/test/forbidden_imports_test.dart +++ b/packages/flutter_tools/test/forbidden_imports_test.dart @@ -8,10 +8,10 @@ import 'package:test/test.dart'; void main() { setUp(() { - String flutterRoot = platform.environment['FLUTTER_ROOT']; + final String flutterRoot = platform.environment['FLUTTER_ROOT']; if (flutterRoot == null) throw new Exception('Please set FLUTTER_ROOT env var before running tests.'); - String flutterTools = fs.path.join(flutterRoot, 'packages', 'flutter_tools'); + final String flutterTools = fs.path.join(flutterRoot, 'packages', 'flutter_tools'); assert(fs.path.equals(fs.currentDirectory.path, flutterTools)); }); diff --git a/packages/flutter_tools/test/format_test.dart b/packages/flutter_tools/test/format_test.dart index e2d7bbd0fa..43c610d829 100644 --- a/packages/flutter_tools/test/format_test.dart +++ b/packages/flutter_tools/test/format_test.dart @@ -28,8 +28,8 @@ void main() { }); Future createProject() async { - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); } @@ -37,15 +37,15 @@ void main() { testUsingContext('a file', () async { await createProject(); - File srcFile = fs.file(fs.path.join(temp.path, 'lib', 'main.dart')); - String original = srcFile.readAsStringSync(); + final File srcFile = fs.file(fs.path.join(temp.path, 'lib', 'main.dart')); + final String original = srcFile.readAsStringSync(); srcFile.writeAsStringSync(original.replaceFirst('main()', 'main( )')); - FormatCommand command = new FormatCommand(); - CommandRunner runner = createTestCommandRunner(command); + final FormatCommand command = new FormatCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['format', srcFile.path]); - String formatted = srcFile.readAsStringSync(); + final String formatted = srcFile.readAsStringSync(); expect(formatted, original); }); }); diff --git a/packages/flutter_tools/test/install_test.dart b/packages/flutter_tools/test/install_test.dart index 9596c4c60c..8bda49b7aa 100644 --- a/packages/flutter_tools/test/install_test.dart +++ b/packages/flutter_tools/test/install_test.dart @@ -13,10 +13,10 @@ import 'src/mocks.dart'; void main() { group('install', () { testUsingContext('returns 0 when Android is connected and ready for an install', () async { - InstallCommand command = new InstallCommand(); + final InstallCommand command = new InstallCommand(); applyMocksToCommand(command); - MockAndroidDevice device = new MockAndroidDevice(); + final MockAndroidDevice device = new MockAndroidDevice(); when(device.isAppInstalled(any)).thenReturn(false); when(device.installApp(any)).thenReturn(true); testDeviceManager.addDevice(device); @@ -25,10 +25,10 @@ void main() { }); testUsingContext('returns 0 when iOS is connected and ready for an install', () async { - InstallCommand command = new InstallCommand(); + final InstallCommand command = new InstallCommand(); applyMocksToCommand(command); - MockIOSDevice device = new MockIOSDevice(); + final MockIOSDevice device = new MockIOSDevice(); when(device.isAppInstalled(any)).thenReturn(false); when(device.installApp(any)).thenReturn(true); testDeviceManager.addDevice(device); diff --git a/packages/flutter_tools/test/logs_test.dart b/packages/flutter_tools/test/logs_test.dart index ab1cb0b6ce..66d191db49 100644 --- a/packages/flutter_tools/test/logs_test.dart +++ b/packages/flutter_tools/test/logs_test.dart @@ -13,7 +13,7 @@ import 'src/mocks.dart'; void main() { group('logs', () { testUsingContext('fail with a bad device id', () async { - LogsCommand command = new LogsCommand(); + final LogsCommand command = new LogsCommand(); applyMocksToCommand(command); try { await createTestCommandRunner(command).run(['-d', 'abc123', 'logs']); diff --git a/packages/flutter_tools/test/os_utils_test.dart b/packages/flutter_tools/test/os_utils_test.dart index 43497bfa4d..695d2bb7a9 100644 --- a/packages/flutter_tools/test/os_utils_test.dart +++ b/packages/flutter_tools/test/os_utils_test.dart @@ -22,13 +22,13 @@ void main() { }); testUsingContext('makeExecutable', () async { - File file = fs.file(fs.path.join(temp.path, 'foo.script')); + final File file = fs.file(fs.path.join(temp.path, 'foo.script')); file.writeAsStringSync('hello world'); os.makeExecutable(file); // Skip this test on windows. if (!platform.isWindows) { - String mode = file.statSync().modeString(); + final String mode = file.statSync().modeString(); // rwxr--r-- expect(mode.substring(0, 3), endsWith('x')); } diff --git a/packages/flutter_tools/test/packages_test.dart b/packages/flutter_tools/test/packages_test.dart index 327e8da79a..d204d82181 100644 --- a/packages/flutter_tools/test/packages_test.dart +++ b/packages/flutter_tools/test/packages_test.dart @@ -26,8 +26,8 @@ void main() { }); Future createProject() async { - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); } @@ -35,8 +35,8 @@ void main() { Future runCommand(String verb) async { await createProject(); - PackagesCommand command = new PackagesCommand(); - CommandRunner runner = createTestCommandRunner(command); + final PackagesCommand command = new PackagesCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['packages', verb, temp.path]); } diff --git a/packages/flutter_tools/test/protocol_discovery_test.dart b/packages/flutter_tools/test/protocol_discovery_test.dart index 26ef9b420e..ed74397384 100644 --- a/packages/flutter_tools/test/protocol_discovery_test.dart +++ b/packages/flutter_tools/test/protocol_discovery_test.dart @@ -14,8 +14,8 @@ import 'src/mocks.dart'; void main() { group('service_protocol discovery', () { testUsingContext('no port forwarding', () async { - MockDeviceLogReader logReader = new MockDeviceLogReader(); - ProtocolDiscovery discoverer = + final MockDeviceLogReader logReader = new MockDeviceLogReader(); + final ProtocolDiscovery discoverer = new ProtocolDiscovery(logReader, ProtocolDiscovery.kObservatoryService); // Get next port future. @@ -41,8 +41,8 @@ void main() { nextUri = discoverer.nextUri(); // Inject a bad line. logReader.addLine('Observatory listening on http://127.0.0.1:apple'); - Uri timeoutUri = Uri.parse('http://timeout'); - Uri actualUri = await nextUri.timeout( + final Uri timeoutUri = Uri.parse('http://timeout'); + final Uri actualUri = await nextUri.timeout( const Duration(milliseconds: 100), onTimeout: () => timeoutUri); expect(actualUri, timeoutUri); @@ -72,17 +72,17 @@ void main() { }); testUsingContext('port forwarding - default port', () async { - MockDeviceLogReader logReader = new MockDeviceLogReader(); - ProtocolDiscovery discoverer = new ProtocolDiscovery( + final MockDeviceLogReader logReader = new MockDeviceLogReader(); + final ProtocolDiscovery discoverer = new ProtocolDiscovery( logReader, ProtocolDiscovery.kObservatoryService, portForwarder: new MockPortForwarder(99), defaultHostPort: 54777); // Get next port future. - Future nextUri = discoverer.nextUri(); + final Future nextUri = discoverer.nextUri(); logReader.addLine('I/flutter : Observatory listening on http://somehost:54804/PTwjm8Ii8qg=/'); - Uri uri = await nextUri; + final Uri uri = await nextUri; expect(uri.port, 54777); expect('$uri', 'http://somehost:54777/PTwjm8Ii8qg=/'); @@ -91,8 +91,8 @@ void main() { }); testUsingContext('port forwarding - specified port', () async { - MockDeviceLogReader logReader = new MockDeviceLogReader(); - ProtocolDiscovery discoverer = new ProtocolDiscovery( + final MockDeviceLogReader logReader = new MockDeviceLogReader(); + final ProtocolDiscovery discoverer = new ProtocolDiscovery( logReader, ProtocolDiscovery.kObservatoryService, portForwarder: new MockPortForwarder(99), @@ -100,9 +100,9 @@ void main() { defaultHostPort: 192); // Get next port future. - Future nextUri = discoverer.nextUri(); + final Future nextUri = discoverer.nextUri(); logReader.addLine('I/flutter : Observatory listening on http://somehost:54804/PTwjm8Ii8qg=/'); - Uri uri = await nextUri; + final Uri uri = await nextUri; expect(uri.port, 1243); expect('$uri', 'http://somehost:1243/PTwjm8Ii8qg=/'); diff --git a/packages/flutter_tools/test/run_test.dart b/packages/flutter_tools/test/run_test.dart index 0abd994249..0bad346dd1 100644 --- a/packages/flutter_tools/test/run_test.dart +++ b/packages/flutter_tools/test/run_test.dart @@ -13,7 +13,7 @@ import 'src/mocks.dart'; void main() { group('run', () { testUsingContext('fails when target not found', () async { - RunCommand command = new RunCommand(); + final RunCommand command = new RunCommand(); applyMocksToCommand(command); try { await createTestCommandRunner(command).run(['run', '-t', 'abc123']); diff --git a/packages/flutter_tools/test/src/base/file_system_test.dart b/packages/flutter_tools/test/src/base/file_system_test.dart index 74968e5510..5525ca168e 100644 --- a/packages/flutter_tools/test/src/base/file_system_test.dart +++ b/packages/flutter_tools/test/src/base/file_system_test.dart @@ -32,19 +32,19 @@ void main() { /// Test file_systems.copyDirectorySync() using MemoryFileSystem. /// Copies between 2 instances of file systems which is also supported by copyDirectorySync(). test('test directory copy', () async { - MemoryFileSystem sourceMemoryFs = new MemoryFileSystem(); - String sourcePath = '/some/origin'; - Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true); + final MemoryFileSystem sourceMemoryFs = new MemoryFileSystem(); + final String sourcePath = '/some/origin'; + final Directory sourceDirectory = await sourceMemoryFs.directory(sourcePath).create(recursive: true); sourceMemoryFs.currentDirectory = sourcePath; - File sourceFile1 = sourceMemoryFs.file('some_file.txt')..writeAsStringSync('bleh'); - DateTime writeTime = sourceFile1.lastModifiedSync(); + final File sourceFile1 = sourceMemoryFs.file('some_file.txt')..writeAsStringSync('bleh'); + final DateTime writeTime = sourceFile1.lastModifiedSync(); sourceMemoryFs.file('sub_dir/another_file.txt').createSync(recursive: true); sourceMemoryFs.directory('empty_directory').createSync(); // Copy to another memory file system instance. - MemoryFileSystem targetMemoryFs = new MemoryFileSystem(); - String targetPath = '/some/non-existent/target'; - Directory targetDirectory = targetMemoryFs.directory(targetPath); + final MemoryFileSystem targetMemoryFs = new MemoryFileSystem(); + final String targetPath = '/some/non-existent/target'; + final Directory targetDirectory = targetMemoryFs.directory(targetPath); copyDirectorySync(sourceDirectory, targetDirectory); expect(targetDirectory.existsSync(), true); diff --git a/packages/flutter_tools/test/src/common.dart b/packages/flutter_tools/test/src/common.dart index f09ff55f99..c11b6fb7ab 100644 --- a/packages/flutter_tools/test/src/common.dart +++ b/packages/flutter_tools/test/src/common.dart @@ -11,7 +11,7 @@ import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; CommandRunner createTestCommandRunner([FlutterCommand command]) { - FlutterCommandRunner runner = new FlutterCommandRunner(); + final FlutterCommandRunner runner = new FlutterCommandRunner(); if (command != null) runner.addCommand(command); return runner; @@ -21,7 +21,7 @@ CommandRunner createTestCommandRunner([FlutterCommand command]) { void updateFileModificationTime(String path, DateTime baseTime, int seconds) { - DateTime modificationTime = baseTime.add(new Duration(seconds: seconds)); + final DateTime modificationTime = baseTime.add(new Duration(seconds: seconds)); fs.file(path).setLastModifiedSync(modificationTime); } diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index 964253aabd..51a606a892 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart @@ -38,7 +38,7 @@ void testUsingContext(String description, dynamic testMethod(), { bool skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this }) { test(description, () async { - AppContext testContext = new AppContext(); + final AppContext testContext = new AppContext(); // Initialize the test context with some default mocks. // Seed these context entries first since others depend on them @@ -58,7 +58,7 @@ void testUsingContext(String description, dynamic testMethod(), { testContext.putIfAbsent(OperatingSystemUtils, () => new MockOperatingSystemUtils()); testContext.putIfAbsent(Xcode, () => new Xcode()); testContext.putIfAbsent(IOSSimulatorUtils, () { - MockIOSSimulatorUtils mock = new MockIOSSimulatorUtils(); + final MockIOSSimulatorUtils mock = new MockIOSSimulatorUtils(); when(mock.getAttachedDevices()).thenReturn([]); return mock; }); @@ -82,7 +82,7 @@ void testUsingContext(String description, dynamic testMethod(), { }); } catch (error) { if (testContext[Logger] is BufferLogger) { - BufferLogger bufferLogger = testContext[Logger]; + final BufferLogger bufferLogger = testContext[Logger]; if (bufferLogger.errorText.isNotEmpty) print(bufferLogger.errorText); } diff --git a/packages/flutter_tools/test/src/ios/ios_workflow_test.dart b/packages/flutter_tools/test/src/ios/ios_workflow_test.dart index 5967afbf1f..f24d6164e8 100644 --- a/packages/flutter_tools/test/src/ios/ios_workflow_test.dart +++ b/packages/flutter_tools/test/src/ios/ios_workflow_test.dart @@ -21,27 +21,27 @@ void main() { testUsingContext('Emit missing status when nothing is installed', () async { when(xcode.isInstalled).thenReturn(false); when(xcode.xcodeSelectPath).thenReturn(null); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() ..hasPythonSixModule = false ..hasHomebrew = false ..hasIosDeploy = false; - ValidationResult result = await workflow.validate(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.missing); }, overrides: { Xcode: () => xcode }); testUsingContext('Emits partial status when Xcode is not installed', () async { when(xcode.isInstalled).thenReturn(false); when(xcode.xcodeSelectPath).thenReturn(null); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); - ValidationResult result = await workflow.validate(); + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); testUsingContext('Emits partial status when Xcode is partially installed', () async { when(xcode.isInstalled).thenReturn(false); when(xcode.xcodeSelectPath).thenReturn('/Library/Developer/CommandLineTools'); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); - ValidationResult result = await workflow.validate(); + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -51,8 +51,8 @@ void main() { .thenReturn('Xcode 7.0.1\nBuild version 7C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(false); when(xcode.eulaSigned).thenReturn(true); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); - ValidationResult result = await workflow.validate(); + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -62,8 +62,8 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(false); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); - ValidationResult result = await workflow.validate(); + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -73,9 +73,9 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(true); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() ..hasPythonSixModule = false; - ValidationResult result = await workflow.validate(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -85,9 +85,9 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(true); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() ..hasHomebrew = false; - ValidationResult result = await workflow.validate(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -97,9 +97,9 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(true); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() ..hasIosDeploy = false; - ValidationResult result = await workflow.validate(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -109,9 +109,9 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(true); - IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() + final IOSWorkflowTestTarget workflow = new IOSWorkflowTestTarget() ..iosDeployVersionText = '1.8.0'; - ValidationResult result = await workflow.validate(); + final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }, overrides: { Xcode: () => xcode }); @@ -121,7 +121,7 @@ void main() { .thenReturn('Xcode 8.2.1\nBuild version 8C1002\n'); when(xcode.isInstalledAndMeetsVersionCheck).thenReturn(true); when(xcode.eulaSigned).thenReturn(true); - ValidationResult result = await new IOSWorkflowTestTarget().validate(); + final ValidationResult result = await new IOSWorkflowTestTarget().validate(); expect(result.type, ValidationType.installed); }, overrides: { Xcode: () => xcode }); }); diff --git a/packages/flutter_tools/test/src/ios/simulators_test.dart b/packages/flutter_tools/test/src/ios/simulators_test.dart index 9611f0f9ca..fd255a7896 100644 --- a/packages/flutter_tools/test/src/ios/simulators_test.dart +++ b/packages/flutter_tools/test/src/ios/simulators_test.dart @@ -18,7 +18,7 @@ void main() { group('compareIosVersions', () { test('compares correctly', () { // This list must be sorted in ascending preference order - List testList = [ + final List testList = [ '8', '8.0', '8.1', '8.2', '9', '9.0', '9.1', '9.2', '10', '10.0', '10.1', @@ -40,7 +40,7 @@ void main() { group('compareIphoneVersions', () { test('compares correctly', () { // This list must be sorted in ascending preference order - List testList = [ + final List testList = [ 'com.apple.CoreSimulator.SimDeviceType.iPhone-4s', 'com.apple.CoreSimulator.SimDeviceType.iPhone-5', 'com.apple.CoreSimulator.SimDeviceType.iPhone-5s', @@ -132,7 +132,7 @@ void main() { when(mockXcode.xcodeMajorVersion).thenReturn(8); when(mockXcode.xcodeMinorVersion).thenReturn(2); expect(deviceUnderTest.supportsScreenshot, true); - MockFile mockFile = new MockFile(); + final MockFile mockFile = new MockFile(); when(mockFile.path).thenReturn(fs.path.join('some', 'path', 'to', 'screenshot.png')); deviceUnderTest.takeScreenshot(mockFile); verify(mockProcessManager.runSync( diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index f0456ccc93..3aac5b56d9 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart @@ -80,7 +80,7 @@ class BasicMock { final List messages = new List(); void expectMessages(List expectedMessages) { - List actualMessages = new List.from(messages); + final List actualMessages = new List.from(messages); messages.clear(); expect(actualMessages, unorderedEquals(expectedMessages)); } @@ -88,7 +88,7 @@ class BasicMock { bool contains(String match) { print('Checking for `$match` in:'); print(messages); - bool result = messages.contains(match); + final bool result = messages.contains(match); messages.clear(); return result; } diff --git a/packages/flutter_tools/test/stop_test.dart b/packages/flutter_tools/test/stop_test.dart index 0401237f5c..8ca54d85b5 100644 --- a/packages/flutter_tools/test/stop_test.dart +++ b/packages/flutter_tools/test/stop_test.dart @@ -15,18 +15,18 @@ import 'src/mocks.dart'; void main() { group('stop', () { testUsingContext('returns 0 when Android is connected and ready to be stopped', () async { - StopCommand command = new StopCommand(); + final StopCommand command = new StopCommand(); applyMocksToCommand(command); - MockAndroidDevice device = new MockAndroidDevice(); + final MockAndroidDevice device = new MockAndroidDevice(); when(device.stopApp(any)).thenReturn(new Future.value(true)); testDeviceManager.addDevice(device); await createTestCommandRunner(command).run(['stop']); }); testUsingContext('returns 0 when iOS is connected and ready to be stopped', () async { - StopCommand command = new StopCommand(); + final StopCommand command = new StopCommand(); applyMocksToCommand(command); - MockIOSDevice device = new MockIOSDevice(); + final MockIOSDevice device = new MockIOSDevice(); when(device.stopApp(any)).thenReturn(new Future.value(true)); testDeviceManager.addDevice(device); diff --git a/packages/flutter_tools/test/trace_test.dart b/packages/flutter_tools/test/trace_test.dart index 3befcde6cb..b823f69634 100644 --- a/packages/flutter_tools/test/trace_test.dart +++ b/packages/flutter_tools/test/trace_test.dart @@ -13,7 +13,7 @@ import 'src/mocks.dart'; void main() { group('trace', () { testUsingContext('returns 1 when no Android device is connected', () async { - TraceCommand command = new TraceCommand(); + final TraceCommand command = new TraceCommand(); applyMocksToCommand(command); try { await createTestCommandRunner(command).run(['trace']); diff --git a/packages/flutter_tools/test/upgrade_test.dart b/packages/flutter_tools/test/upgrade_test.dart index b46e612c79..adb9758c83 100644 --- a/packages/flutter_tools/test/upgrade_test.dart +++ b/packages/flutter_tools/test/upgrade_test.dart @@ -47,19 +47,19 @@ void main() { }); Future createProject() async { - CreateCommand command = new CreateCommand(); - CommandRunner runner = createTestCommandRunner(command); + final CreateCommand command = new CreateCommand(); + final CommandRunner runner = createTestCommandRunner(command); await runner.run(['create', '--no-pub', temp.path]); } testUsingContext('in project', () async { await createProject(); - String proj = temp.path; + final String proj = temp.path; expect(findProjectRoot(proj), proj); expect(findProjectRoot(fs.path.join(proj, 'lib')), proj); - String hello = fs.path.join(Cache.flutterRoot, 'examples', 'hello_world'); + final String hello = fs.path.join(Cache.flutterRoot, 'examples', 'hello_world'); expect(findProjectRoot(hello), hello); expect(findProjectRoot(fs.path.join(hello, 'lib')), hello); }); diff --git a/packages/flutter_tools/test/utils_test.dart b/packages/flutter_tools/test/utils_test.dart index 75dfc206ac..ace2edfcce 100644 --- a/packages/flutter_tools/test/utils_test.dart +++ b/packages/flutter_tools/test/utils_test.dart @@ -9,7 +9,7 @@ import 'package:test/test.dart'; void main() { group('SettingsFile', () { test('parse', () { - SettingsFile file = new SettingsFile.parse(''' + final SettingsFile file = new SettingsFile.parse(''' # ignore comment foo=bar baz=qux @@ -23,8 +23,8 @@ baz=qux group('uuid', () { // xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx test('simple', () { - Uuid uuid = new Uuid(); - String result = uuid.generateV4(); + final Uuid uuid = new Uuid(); + final String result = uuid.generateV4(); expect(result.length, 36); expect(result[8], '-'); expect(result[13], '-'); @@ -33,8 +33,8 @@ baz=qux }); test('can parse', () { - Uuid uuid = new Uuid(); - String result = uuid.generateV4(); + final Uuid uuid = new Uuid(); + final String result = uuid.generateV4(); expect(int.parse(result.substring(0, 8), radix: 16), isNotNull); expect(int.parse(result.substring(9, 13), radix: 16), isNotNull); expect(int.parse(result.substring(14, 18), radix: 16), isNotNull); @@ -43,7 +43,7 @@ baz=qux }); test('special bits', () { - Uuid uuid = new Uuid(); + final Uuid uuid = new Uuid(); String result = uuid.generateV4(); expect(result[14], '4'); expect(result[19].toLowerCase(), isIn('89ab')); @@ -56,25 +56,25 @@ baz=qux }); test('is pretty random', () { - Set set = new Set(); + final Set set = new Set(); Uuid uuid = new Uuid(); for (int i = 0; i < 64; i++) { - String val = uuid.generateV4(); + final String val = uuid.generateV4(); expect(set, isNot(contains(val))); set.add(val); } uuid = new Uuid(); for (int i = 0; i < 64; i++) { - String val = uuid.generateV4(); + final String val = uuid.generateV4(); expect(set, isNot(contains(val))); set.add(val); } uuid = new Uuid(); for (int i = 0; i < 64; i++) { - String val = uuid.generateV4(); + final String val = uuid.generateV4(); expect(set, isNot(contains(val))); set.add(val); } @@ -86,30 +86,30 @@ baz=qux expect(Version.unknown.toString(), equals('unknown')); expect(new Version(null, null, null).toString(), equals('0')); - Version v1 = new Version.parse('1'); + final Version v1 = new Version.parse('1'); expect(v1.major, equals(1)); expect(v1.minor, equals(0)); expect(v1.patch, equals(0)); expect(v1, greaterThan(Version.unknown)); - Version v2 = new Version.parse('1.2'); + final Version v2 = new Version.parse('1.2'); expect(v2.major, equals(1)); expect(v2.minor, equals(2)); expect(v2.patch, equals(0)); - Version v3 = new Version.parse('1.2.3'); + final Version v3 = new Version.parse('1.2.3'); expect(v3.major, equals(1)); expect(v3.minor, equals(2)); expect(v3.patch, equals(3)); - Version v4 = new Version.parse('1.12'); + final Version v4 = new Version.parse('1.12'); expect(v4, greaterThan(v2)); expect(v3, greaterThan(v2)); expect(v2, greaterThan(v1)); - Version v5 = new Version(1, 2, 0, text: 'foo'); + final Version v5 = new Version(1, 2, 0, text: 'foo'); expect(v5, equals(v2)); expect(new Version.parse('Preview2.2'), isNull); diff --git a/packages/flutter_tools/tool/daemon_client.dart b/packages/flutter_tools/tool/daemon_client.dart index ca25ed4fa4..7516595935 100644 --- a/packages/flutter_tools/tool/daemon_client.dart +++ b/packages/flutter_tools/tool/daemon_client.dart @@ -28,7 +28,7 @@ Future main() async { stdout.write('> '); stdin.transform(UTF8.decoder).transform(const LineSplitter()).listen((String line) { - List words = line.split(' '); + final List words = line.split(' '); if (line == 'version' || line == 'v') { _send({'method': 'daemon.version'}); @@ -80,7 +80,7 @@ int id = 0; void _send(Map map) { map['id'] = id++; - String str = '[${JSON.encode(map)}]'; + final String str = '[${JSON.encode(map)}]'; daemon.stdin.writeln(str); print('==> $str'); }