From 6c97dd2c6ca94d7d453f5b791d97b83314e342e9 Mon Sep 17 00:00:00 2001 From: Chris Bracken Date: Fri, 3 Mar 2017 18:06:08 -0800 Subject: [PATCH] Declare locals as final where not reassigned (dev) (#8574) --- dev/benchmarks/complex_layout/lib/main.dart | 2 +- .../test_driver/scroll_perf_test.dart | 6 +-- .../microbenchmarks/lib/common.dart | 2 +- .../lib/gestures/velocity_tracker_bench.dart | 2 +- .../lib/stocks/animation_bench.dart | 2 +- .../lib/stocks/build_bench.dart | 4 +- .../lib/stocks/layout_bench.dart | 4 +- dev/bots/test.dart | 16 +++---- dev/devicelab/bin/run.dart | 14 +++--- .../tasks/analyzer_cli__analysis_time.dart | 6 +-- .../tasks/analyzer_server__analysis_time.dart | 6 +-- .../tasks/hot_mode_dev_cycle__benchmark.dart | 6 +-- .../bin/tasks/technical_debt__cost.dart | 4 +- dev/devicelab/lib/framework/adb.dart | 34 +++++++------- dev/devicelab/lib/framework/benchmarks.dart | 4 +- dev/devicelab/lib/framework/framework.dart | 12 ++--- dev/devicelab/lib/framework/manifest.dart | 8 ++-- dev/devicelab/lib/framework/runner.dart | 26 +++++------ dev/devicelab/lib/framework/utils.dart | 40 ++++++++-------- dev/devicelab/lib/tasks/gallery.dart | 16 +++---- dev/devicelab/lib/tasks/microbenchmarks.dart | 14 +++--- dev/devicelab/lib/tasks/perf_tests.dart | 46 +++++++++---------- dev/devicelab/lib/tasks/size_tests.dart | 2 +- dev/devicelab/test/adb_test.dart | 4 +- dev/devicelab/test/manifest_test.dart | 4 +- dev/devicelab/test/run_test.dart | 4 +- dev/manual_tests/card_collection.dart | 12 ++--- dev/manual_tests/drag_and_drop.dart | 6 +-- dev/manual_tests/overlay_geometry.dart | 16 +++---- dev/manual_tests/page_view.dart | 6 +-- .../test/card_collection_test.dart | 2 +- dev/tools/dartdoc.dart | 28 +++++------ dev/tools/javadoc.dart | 14 +++--- dev/tools/mega_gallery.dart | 30 ++++++------ dev/tools/update_icons.dart | 28 +++++------ 35 files changed, 215 insertions(+), 215 deletions(-) diff --git a/dev/benchmarks/complex_layout/lib/main.dart b/dev/benchmarks/complex_layout/lib/main.dart index 3157029bb2b..1d74418826c 100644 --- a/dev/benchmarks/complex_layout/lib/main.dart +++ b/dev/benchmarks/complex_layout/lib/main.dart @@ -449,7 +449,7 @@ class ItemGalleryBox extends StatelessWidget { @override Widget build(BuildContext context) { - List tabNames = [ + final List tabNames = [ 'A', 'B', 'C', 'D' ]; diff --git a/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart b/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart index f33a356b2ca..29e97d6ba12 100644 --- a/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart +++ b/dev/benchmarks/complex_layout/test_driver/scroll_perf_test.dart @@ -20,9 +20,9 @@ void main() { }); test('measure', () async { - Timeline timeline = await driver.traceAction(() async { + final Timeline timeline = await driver.traceAction(() async { // Find the scrollable stock list - SerializableFinder stockList = find.byValueKey('main-scroll'); + final SerializableFinder stockList = find.byValueKey('main-scroll'); expect(stockList, isNotNull); // Scroll down @@ -38,7 +38,7 @@ void main() { } }); - TimelineSummary summary = new TimelineSummary.summarize(timeline); + final TimelineSummary summary = new TimelineSummary.summarize(timeline); summary.writeSummaryToFile('complex_layout_scroll_perf', pretty: true); summary.writeTimelineToFile('complex_layout_scroll_perf', pretty: true); }); diff --git a/dev/benchmarks/microbenchmarks/lib/common.dart b/dev/benchmarks/microbenchmarks/lib/common.dart index 5100fe3a8b3..cb695f1b294 100644 --- a/dev/benchmarks/microbenchmarks/lib/common.dart +++ b/dev/benchmarks/microbenchmarks/lib/common.dart @@ -54,7 +54,7 @@ class BenchmarkResultPrinter { } String _printPlainText() { - StringBuffer buf = new StringBuffer(); + final StringBuffer buf = new StringBuffer(); for (_BenchmarkResult result in _results) { buf.writeln('${result.description}: ${result.value.toStringAsFixed(1)} ${result.unit}'); } diff --git a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart index 6c9beed2972..6c9cf68610e 100644 --- a/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/gestures/velocity_tracker_bench.dart @@ -24,7 +24,7 @@ void main() { } watch.stop(); - BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); + final BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); printer.addResult( description: 'Velocity tracker', value: watch.elapsedMicroseconds / _kNumIters, diff --git a/dev/benchmarks/microbenchmarks/lib/stocks/animation_bench.dart b/dev/benchmarks/microbenchmarks/lib/stocks/animation_bench.dart index 5312bed9ee3..7918fa9a52d 100644 --- a/dev/benchmarks/microbenchmarks/lib/stocks/animation_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/stocks/animation_bench.dart @@ -75,7 +75,7 @@ Future main() async { } }); - BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); + final BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); printer.addResult( description: 'Stock animation', value: wallClockWatch.elapsedMicroseconds / (1000 * 1000), diff --git a/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart b/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart index 9edc02c1548..37f6474547a 100644 --- a/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/stocks/build_bench.dart @@ -21,7 +21,7 @@ Future main() async { // This allows us to call onBeginFrame even when the engine didn't request it, // and have it actually do something: - LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); binding.allowAllFrames = true; final Stopwatch watch = new Stopwatch(); @@ -50,7 +50,7 @@ Future main() async { watch.stop(); }); - BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); + final BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); printer.addResult( description: 'Stock build', value: watch.elapsedMicroseconds / iterations, diff --git a/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart b/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart index d2d83c8080d..b3172102ea5 100644 --- a/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart +++ b/dev/benchmarks/microbenchmarks/lib/stocks/layout_bench.dart @@ -20,7 +20,7 @@ Future main() async { // This allows us to call onBeginFrame even when the engine didn't request it, // and have it actually do something: - LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); binding.allowAllFrames = true; final Stopwatch watch = new Stopwatch(); @@ -51,7 +51,7 @@ Future main() async { watch.stop(); }); - BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); + final BenchmarkResultPrinter printer = new BenchmarkResultPrinter(); printer.addResult( description: 'Stock layout', value: watch.elapsedMicroseconds / iterations, diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 737c54aa8f0..5c2a505f388 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -31,7 +31,7 @@ Future main() async { print('\x1B[32mDONE: Analysis successful.\x1B[0m'); } else { // Verify that the tests actually return failure on failure and success on success. - String automatedTests = p.join(flutterRoot, 'dev', 'automated_tests'); + final String automatedTests = p.join(flutterRoot, 'dev', 'automated_tests'); await _runFlutterTest(automatedTests, script: p.join('test_smoke_test', 'fail_test.dart'), expectFailure: true, @@ -67,7 +67,7 @@ Future main() async { printOutput: false, ); - List coverageFlags = []; + final List coverageFlags = []; if (Platform.environment['TRAVIS'] != null && Platform.environment['TRAVIS_PULL_REQUEST'] == 'false') coverageFlags.add('--coverage'); @@ -100,15 +100,15 @@ Future _runCmd(String executable, List arguments, { bool printOutput: true, bool skip: false, }) async { - String cmd = '${p.relative(executable)} ${arguments.join(' ')}'; - String relativeWorkingDir = p.relative(workingDirectory); + final String cmd = '${p.relative(executable)} ${arguments.join(' ')}'; + final String relativeWorkingDir = p.relative(workingDirectory); if (skip) { _printProgress('SKIPPING', relativeWorkingDir, cmd); return null; } _printProgress('RUNNING', relativeWorkingDir, cmd); - Process process = await Process.start(executable, arguments, + final Process process = await Process.start(executable, arguments, workingDirectory: workingDirectory, environment: environment, ); @@ -118,7 +118,7 @@ Future _runCmd(String executable, List arguments, { stderr.addStream(process.stderr); } - int exitCode = await process.exitCode; + final int exitCode = await process.exitCode; if ((exitCode == 0) == expectFailure) { print( '\x1B[31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1B[0m\n' @@ -136,7 +136,7 @@ Future _runFlutterTest(String workingDirectory, { List options: const [], bool skip: false, }) { - List args = ['test']..addAll(options); + final List args = ['test']..addAll(options); if (flutterTestArgs != null) args.add(flutterTestArgs); if (script != null) @@ -152,7 +152,7 @@ Future _runFlutterTest(String workingDirectory, { Future _runAllDartTests(String workingDirectory, { Map environment, }) { - List args = ['--checked', p.join('test', 'all.dart')]; + final List args = ['--checked', p.join('test', 'all.dart')]; return _runCmd(dart, args, workingDirectory: workingDirectory, environment: environment, diff --git a/dev/devicelab/bin/run.dart b/dev/devicelab/bin/run.dart index 0f683886cda..9400b1f0145 100644 --- a/dev/devicelab/bin/run.dart +++ b/dev/devicelab/bin/run.dart @@ -33,14 +33,14 @@ Future main(List rawArgs) async { if (!args.wasParsed('task')) { if (args.wasParsed('stage')) { - String stageName = args['stage']; - List tasks = loadTaskManifest().tasks; + final String stageName = args['stage']; + final List tasks = loadTaskManifest().tasks; for (ManifestTask task in tasks) { if (task.stage == stageName) _taskNames.add(task.name); } } else if (args.wasParsed('all')) { - List tasks = loadTaskManifest().tasks; + final List tasks = loadTaskManifest().tasks; for (ManifestTask task in tasks) { _taskNames.add(task.name); } @@ -53,11 +53,11 @@ Future main(List rawArgs) async { return null; } - bool silent = args['silent']; + final bool silent = args['silent']; for (String taskName in _taskNames) { section('Running task "$taskName"'); - Map result = await runTask(taskName, silent: silent); + final Map result = await runTask(taskName, silent: silent); if (!result['success']) exitCode = 1; @@ -82,8 +82,8 @@ final ArgParser _argParser = new ArgParser() 'This option may be repeated to specify multiple tasks.', callback: (List value) { for (String nameOrPath in value) { - List fragments = path.split(nameOrPath); - bool isDartFile = fragments.last.endsWith('.dart'); + final List fragments = path.split(nameOrPath); + final bool isDartFile = fragments.last.endsWith('.dart'); if (fragments.length == 1 && !isDartFile) { // Not a path diff --git a/dev/devicelab/bin/tasks/analyzer_cli__analysis_time.dart b/dev/devicelab/bin/tasks/analyzer_cli__analysis_time.dart index 7b0ebcad183..50ee992e050 100644 --- a/dev/devicelab/bin/tasks/analyzer_cli__analysis_time.dart +++ b/dev/devicelab/bin/tasks/analyzer_cli__analysis_time.dart @@ -9,9 +9,9 @@ import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/utils.dart'; Future main() async { - String revision = await getCurrentFlutterRepoCommit(); - DateTime revisionTimestamp = await getFlutterRepoCommitTimestamp(revision); - String dartSdkVersion = await getDartVersion(); + final String revision = await getCurrentFlutterRepoCommit(); + final DateTime revisionTimestamp = await getFlutterRepoCommitTimestamp(revision); + final String dartSdkVersion = await getDartVersion(); await task(createAnalyzerCliTest( sdk: dartSdkVersion, commit: revision, diff --git a/dev/devicelab/bin/tasks/analyzer_server__analysis_time.dart b/dev/devicelab/bin/tasks/analyzer_server__analysis_time.dart index c02b5375c47..922c8ce85e0 100644 --- a/dev/devicelab/bin/tasks/analyzer_server__analysis_time.dart +++ b/dev/devicelab/bin/tasks/analyzer_server__analysis_time.dart @@ -9,9 +9,9 @@ import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/utils.dart'; Future main() async { - String revision = await getCurrentFlutterRepoCommit(); - DateTime revisionTimestamp = await getFlutterRepoCommitTimestamp(revision); - String dartSdkVersion = await getDartVersion(); + final String revision = await getCurrentFlutterRepoCommit(); + final DateTime revisionTimestamp = await getFlutterRepoCommitTimestamp(revision); + final String dartSdkVersion = await getDartVersion(); await task(createAnalyzerServerTest( sdk: dartSdkVersion, commit: revision, diff --git a/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark.dart b/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark.dart index 9eeb3bdd34f..1b56bf94ceb 100644 --- a/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark.dart +++ b/dev/devicelab/bin/tasks/hot_mode_dev_cycle__benchmark.dart @@ -12,11 +12,11 @@ import 'package:flutter_devicelab/framework/utils.dart'; void main() { task(() async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); - Directory appDir = + final Directory appDir = dir(path.join(flutterDirectory.path, 'examples/flutter_gallery')); - File benchmarkFile = file(path.join(appDir.path, 'hot_benchmark.json')); + final File benchmarkFile = file(path.join(appDir.path, 'hot_benchmark.json')); rm(benchmarkFile); await inDirectory(appDir, () async { return await flutter('run', diff --git a/dev/devicelab/bin/tasks/technical_debt__cost.dart b/dev/devicelab/bin/tasks/technical_debt__cost.dart index b80aae0e560..14af90134f6 100644 --- a/dev/devicelab/bin/tasks/technical_debt__cost.dart +++ b/dev/devicelab/bin/tasks/technical_debt__cost.dart @@ -39,7 +39,7 @@ const String _kBenchmarkKey = 'technical_debt_in_dollars'; Future main() async { await task(() async { - Process git = await startProcess( + final Process git = await startProcess( 'git', ['ls-files', '--full-name', flutterDirectory.path], workingDirectory: flutterDirectory.path, @@ -47,7 +47,7 @@ Future main() async { double total = 0.0; await for (String entry in git.stdout.transform(UTF8.decoder).transform(const LineSplitter())) total += await findCostsForFile(new File(path.join(flutterDirectory.path, entry))); - int gitExitCode = await git.exitCode; + final int gitExitCode = await git.exitCode; if (gitExitCode != 0) throw new Exception('git exit with unexpected error code $gitExitCode'); return new TaskResult.success( diff --git a/dev/devicelab/lib/framework/adb.dart b/dev/devicelab/lib/framework/adb.dart index 6b707eb54d2..ebaaf5c0f4e 100644 --- a/dev/devicelab/lib/framework/adb.dart +++ b/dev/devicelab/lib/framework/adb.dart @@ -118,7 +118,7 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { /// [workingDevice]. @override Future chooseWorkingDevice() async { - List allDevices = (await discoverDevices()) + final List allDevices = (await discoverDevices()) .map((String id) => new AndroidDevice(deviceId: id)) .toList(); @@ -131,9 +131,9 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { @override Future> discoverDevices() async { - List output = (await eval(adbPath, ['devices', '-l'], canFail: false)) + final List output = (await eval(adbPath, ['devices', '-l'], canFail: false)) .trim().split('\n'); - List results = []; + final List results = []; for (String line in output) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) @@ -143,10 +143,10 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { 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]; if (!const ['unauthorized', 'offline'].contains(deviceState)) { results.add(deviceID); @@ -161,10 +161,10 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { @override Future> checkDevices() async { - Map results = {}; + final Map results = {}; for (String deviceId in await discoverDevices()) { try { - AndroidDevice device = new AndroidDevice(deviceId: deviceId); + final AndroidDevice device = new AndroidDevice(deviceId: deviceId); // Just a smoke test that we can read wakefulness state // TODO(yjbanov): check battery level await device._getWakefulness(); @@ -240,8 +240,8 @@ class AndroidDevice implements Device { /// /// See: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/PowerManagerInternal.java Future _getWakefulness() async { - String powerInfo = await shellEval('dumpsys', ['power']); - String wakefulness = grep('mWakefulness=', from: powerInfo).single.split('=')[1].trim(); + final String powerInfo = await shellEval('dumpsys', ['power']); + final String wakefulness = grep('mWakefulness=', from: powerInfo).single.split('=')[1].trim(); return wakefulness; } @@ -257,8 +257,8 @@ class AndroidDevice implements Device { @override Future> getMemoryStats(String packageName) async { - String meminfo = await shellEval('dumpsys', ['meminfo', packageName]); - Match match = new RegExp(r'TOTAL\s+(\d+)').firstMatch(meminfo); + final String meminfo = await shellEval('dumpsys', ['meminfo', packageName]); + final Match match = new RegExp(r'TOTAL\s+(\d+)').firstMatch(meminfo); return { 'total_kb': int.parse(match.group(1)), }; @@ -295,7 +295,7 @@ class IosDeviceDiscovery implements DeviceDiscovery { /// [workingDevice]. @override Future chooseWorkingDevice() async { - List allDevices = (await discoverDevices()) + final List allDevices = (await discoverDevices()) .map((String id) => new IosDevice(deviceId: id)) .toList(); @@ -309,7 +309,7 @@ class IosDeviceDiscovery implements DeviceDiscovery { @override Future> discoverDevices() async { // TODO: use the -k UniqueDeviceID option, which requires much less parsing. - List iosDeviceIds = grep('UniqueDeviceID', from: await eval('ideviceinfo', [])) + final List iosDeviceIds = grep('UniqueDeviceID', from: await eval('ideviceinfo', [])) .map((String line) => line.split(' ').last).toList(); if (iosDeviceIds.isEmpty) @@ -320,7 +320,7 @@ class IosDeviceDiscovery implements DeviceDiscovery { @override Future> checkDevices() async { - Map results = {}; + final Map results = {}; for (String deviceId in await discoverDevices()) { // TODO: do a more meaningful connectivity check than just recording the ID results['ios-device-$deviceId'] = new HealthCheckResult.success(); @@ -376,13 +376,13 @@ class IosDevice implements Device { /// Path to the `adb` executable. String get adbPath { - String androidHome = Platform.environment['ANDROID_HOME']; + final String androidHome = Platform.environment['ANDROID_HOME']; if (androidHome == null) throw 'ANDROID_HOME environment variable missing. This variable must ' 'point to the Android SDK directory containing platform-tools.'; - File adbPath = file(path.join(androidHome, 'platform-tools/adb')); + final File adbPath = file(path.join(androidHome, 'platform-tools/adb')); if (!adbPath.existsSync()) throw 'adb not found at: $adbPath'; diff --git a/dev/devicelab/lib/framework/benchmarks.dart b/dev/devicelab/lib/framework/benchmarks.dart index 7eccabe83e4..b4bddfc665c 100644 --- a/dev/devicelab/lib/framework/benchmarks.dart +++ b/dev/devicelab/lib/framework/benchmarks.dart @@ -33,7 +33,7 @@ Future runBenchmark(Benchmark benchmark, { }) async { await benchmark.init(); - List allRuns = []; + final List allRuns = []; num minValue; @@ -46,7 +46,7 @@ Future runBenchmark(Benchmark benchmark, { print(''); try { - num result = await benchmark.run(); + final num result = await benchmark.run(); allRuns.add(result); if (minValue == null || result < minValue) { diff --git a/dev/devicelab/lib/framework/framework.dart b/dev/devicelab/lib/framework/framework.dart index 71cf696408e..5d6d88ab626 100644 --- a/dev/devicelab/lib/framework/framework.dart +++ b/dev/devicelab/lib/framework/framework.dart @@ -43,7 +43,7 @@ Future task(TaskFunction task) { print('${rec.level.name}: ${rec.time}: ${rec.message}'); }); - _TaskRunner runner = new _TaskRunner(task); + final _TaskRunner runner = new _TaskRunner(task); runner.keepVmAliveUntilTaskRunRequested(); return runner.whenDone; } @@ -63,7 +63,7 @@ class _TaskRunner { _TaskRunner(this.task) { registerExtension('ext.cocoonRunTask', (String method, Map parameters) async { - TaskResult result = await run(); + final TaskResult result = await run(); return new ServiceExtensionResponse.result(JSON.encode(result.toJson())); }); registerExtension('ext.cocoonRunnerReady', @@ -78,7 +78,7 @@ class _TaskRunner { Future run() async { try { _taskStarted = true; - TaskResult result = await _performTask().timeout(taskTimeout); + final TaskResult result = await _performTask().timeout(taskTimeout); _completer.complete(result); return result; } on TimeoutException catch (_) { @@ -117,11 +117,11 @@ class _TaskRunner { } Future _performTask() { - Completer completer = new Completer(); + final Completer completer = new Completer(); Chain.capture(() async { completer.complete(await task()); }, onError: (dynamic taskError, Chain taskErrorStack) { - String message = 'Task failed: $taskError'; + final String message = 'Task failed: $taskError'; stderr ..writeln(message) ..writeln('\nStack trace:') @@ -210,7 +210,7 @@ class TaskResult { /// "reason": failure reason string valid only for unsuccessful results /// } Map toJson() { - Map json = { + final Map json = { 'success': succeeded, }; diff --git a/dev/devicelab/lib/framework/manifest.dart b/dev/devicelab/lib/framework/manifest.dart index 2bc97062c9f..3eac7a14e91 100644 --- a/dev/devicelab/lib/framework/manifest.dart +++ b/dev/devicelab/lib/framework/manifest.dart @@ -9,7 +9,7 @@ import 'utils.dart'; /// Loads manifest data from `manifest.yaml` file or from [yaml], if present. Manifest loadTaskManifest([ String yaml ]) { - dynamic manifestYaml = yaml == null + final dynamic manifestYaml = yaml == null ? loadYaml(file('manifest.yaml').readAsStringSync()) : loadYamlNode(yaml); @@ -33,7 +33,7 @@ class ManifestTask { @required this.stage, @required this.requiredAgentCapabilities, }) { - String taskName = 'task "$name"'; + final String taskName = 'task "$name"'; _checkIsNotBlank(name, 'Task name', taskName); _checkIsNotBlank(description, 'Task description', taskName); _checkIsNotBlank(stage, 'Task stage', taskName); @@ -84,7 +84,7 @@ ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) { 'required_agent_capabilities', ]); - List capabilities = _validateAndParseCapabilities(taskName, taskYaml['required_agent_capabilities']); + final List capabilities = _validateAndParseCapabilities(taskName, taskYaml['required_agent_capabilities']); return new ManifestTask._( name: taskName, description: taskYaml['description'], @@ -96,7 +96,7 @@ ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) { List _validateAndParseCapabilities(String taskName, dynamic capabilitiesYaml) { _checkType(capabilitiesYaml is List, capabilitiesYaml, 'required_agent_capabilities', 'list'); for (int i = 0; i < capabilitiesYaml.length; i++) { - dynamic capability = capabilitiesYaml[i]; + final dynamic capability = capabilitiesYaml[i]; _checkType(capability is String, capability, 'required_agent_capabilities[$i]', 'string'); } return capabilitiesYaml; diff --git a/dev/devicelab/lib/framework/runner.dart b/dev/devicelab/lib/framework/runner.dart index 49136f24178..c4fcac29353 100644 --- a/dev/devicelab/lib/framework/runner.dart +++ b/dev/devicelab/lib/framework/runner.dart @@ -23,13 +23,13 @@ const Duration taskTimeoutWithGracePeriod = const Duration(minutes: 11); /// Running the task in [silent] mode will suppress standard output from task /// processes and only print standard errors. Future> runTask(String taskName, { bool silent: false }) async { - String taskExecutable = 'bin/tasks/$taskName.dart'; + final String taskExecutable = 'bin/tasks/$taskName.dart'; if (!file(taskExecutable).existsSync()) throw 'Executable Dart file not found: $taskExecutable'; - int vmServicePort = await findAvailablePort(); - Process runner = await startProcess(dartBin, [ + final int vmServicePort = await findAvailablePort(); + final Process runner = await startProcess(dartBin, [ '--enable-vm-service=$vmServicePort', '--no-pause-isolates-on-exit', taskExecutable, @@ -41,7 +41,7 @@ Future> runTask(String taskName, { bool silent: false }) as runnerFinished = true; }); - StreamSubscription stdoutSub = runner.stdout + final StreamSubscription stdoutSub = runner.stdout .transform(const Utf8Decoder()) .transform(const LineSplitter()) .listen((String line) { @@ -50,7 +50,7 @@ Future> runTask(String taskName, { bool silent: false }) as } }); - StreamSubscription stderrSub = runner.stderr + final StreamSubscription stderrSub = runner.stderr .transform(const Utf8Decoder()) .transform(const LineSplitter()) .listen((String line) { @@ -59,9 +59,9 @@ Future> runTask(String taskName, { bool silent: false }) as String waitingFor = 'connection'; try { - VMIsolateRef isolate = await _connectToRunnerIsolate(vmServicePort); + final VMIsolateRef isolate = await _connectToRunnerIsolate(vmServicePort); waitingFor = 'task completion'; - Map taskResult = + final Map taskResult = await isolate.invokeExtension('ext.cocoonRunTask').timeout(taskTimeoutWithGracePeriod); waitingFor = 'task process to exit'; await runner.exitCode.timeout(const Duration(seconds: 1)); @@ -81,8 +81,8 @@ Future> runTask(String taskName, { bool silent: false }) as } Future _connectToRunnerIsolate(int vmServicePort) async { - String url = 'ws://localhost:$vmServicePort/ws'; - DateTime started = new DateTime.now(); + final String url = 'ws://localhost:$vmServicePort/ws'; + final DateTime started = new DateTime.now(); // TODO(yjbanov): due to lack of imagination at the moment the handshake with // the task process is very rudimentary and requires this small @@ -97,10 +97,10 @@ Future _connectToRunnerIsolate(int vmServicePort) async { await (await WebSocket.connect(url)).close(); // Look up the isolate. - VMServiceClient client = new VMServiceClient.connect(url); - VM vm = await client.getVM(); - VMIsolateRef isolate = vm.isolates.single; - String response = await isolate.invokeExtension('ext.cocoonRunnerReady'); + final VMServiceClient client = new VMServiceClient.connect(url); + final VM vm = await client.getVM(); + final VMIsolateRef isolate = vm.isolates.single; + final String response = await isolate.invokeExtension('ext.cocoonRunnerReady'); if (response != 'ready') throw 'not ready yet'; return isolate; } catch (error) { diff --git a/dev/devicelab/lib/framework/utils.dart b/dev/devicelab/lib/framework/utils.dart index eb07c889c0f..4daafda559b 100644 --- a/dev/devicelab/lib/framework/utils.dart +++ b/dev/devicelab/lib/framework/utils.dart @@ -46,7 +46,7 @@ class HealthCheckResult { @override String toString() { - StringBuffer buf = new StringBuffer(succeeded ? 'succeeded' : 'failed'); + final StringBuffer buf = new StringBuffer(succeeded ? 'succeeded' : 'failed'); if (details != null && details.trim().isNotEmpty) { buf.writeln(); // Indent details by 4 spaces @@ -89,7 +89,7 @@ Directory dir(String path) => new Directory(path); File file(String path) => new File(path); void copy(File sourceFile, Directory targetDirectory, {String name}) { - File target = file( + final File target = file( path.join(targetDirectory.path, name ?? path.basename(sourceFile.path))); target.writeAsBytesSync(sourceFile.readAsBytesSync()); } @@ -118,7 +118,7 @@ void section(String title) { Future getDartVersion() async { // The Dart VM returns the version text to stderr. - ProcessResult result = Process.runSync(dartBin, ['--version']); + final ProcessResult result = Process.runSync(dartBin, ['--version']); String version = result.stderr.trim(); // Convert: @@ -146,13 +146,13 @@ Future getCurrentFlutterRepoCommit() { Future getFlutterRepoCommitTimestamp(String commit) { // git show -s --format=%at 4b546df7f0b3858aaaa56c4079e5be1ba91fbb65 return inDirectory(flutterDirectory, () async { - String unixTimestamp = await eval('git', [ + final String unixTimestamp = await eval('git', [ 'show', '-s', '--format=%at', commit, ]); - int secondsSinceEpoch = int.parse(unixTimestamp); + final int secondsSinceEpoch = int.parse(unixTimestamp); return new DateTime.fromMillisecondsSinceEpoch(secondsSinceEpoch * 1000); }); } @@ -163,17 +163,17 @@ Future startProcess( Map environment, String workingDirectory, }) async { - String command = '$executable ${arguments?.join(" ") ?? ""}'; + final String command = '$executable ${arguments?.join(" ") ?? ""}'; print('Executing: $command'); environment ??= {}; environment['BOT'] = 'true'; - Process process = await Process.start( + final Process process = await Process.start( executable, arguments, environment: environment, workingDirectory: workingDirectory ?? cwd, ); - ProcessInfo processInfo = new ProcessInfo(command, process); + final ProcessInfo processInfo = new ProcessInfo(command, process); _runningProcesses.add(processInfo); process.exitCode.whenComplete(() { @@ -207,7 +207,7 @@ Future exec( Map environment, bool canFail: false, }) async { - Process process = await startProcess(executable, arguments, environment: environment); + final Process process = await startProcess(executable, arguments, environment: environment); process.stdout .transform(UTF8.decoder) @@ -218,7 +218,7 @@ Future exec( .transform(const LineSplitter()) .listen(stderr.writeln); - int exitCode = await process.exitCode; + final int exitCode = await process.exitCode; if (exitCode != 0 && !canFail) fail('Executable failed with exit code $exitCode.'); @@ -235,12 +235,12 @@ Future eval( Map environment, bool canFail: false, }) async { - Process process = await startProcess(executable, arguments, environment: environment); + final Process process = await startProcess(executable, arguments, environment: environment); process.stderr.listen((List data) { stderr.add(data); }); - String output = await UTF8.decodeStream(process.stdout); - int exitCode = await process.exitCode; + final String output = await UTF8.decodeStream(process.stdout); + final int exitCode = await process.exitCode; if (exitCode != 0 && !canFail) fail('Executable failed with exit code $exitCode.'); @@ -253,7 +253,7 @@ Future flutter(String command, { bool canFail: false, Map environment, }) { - List args = [command]..addAll(options); + final List args = [command]..addAll(options); return exec(path.join(flutterDirectory.path, 'bin', 'flutter'), args, canFail: canFail, environment: environment); } @@ -264,7 +264,7 @@ Future evalFlutter(String command, { bool canFail: false, Map environment, }) { - List args = [command]..addAll(options); + final List args = [command]..addAll(options); return eval(path.join(flutterDirectory.path, 'bin', 'flutter'), args, canFail: canFail, environment: environment); } @@ -275,7 +275,7 @@ String get dartBin => Future dart(List args) => exec(dartBin, args); Future inDirectory(dynamic directory, Future action()) async { - String previousCwd = cwd; + final String previousCwd = cwd; try { cd(directory); return await action(); @@ -303,7 +303,7 @@ void cd(dynamic directory) { Directory get flutterDirectory => dir('../..').absolute; String requireEnvVar(String name) { - String value = Platform.environment[name]; + final String value = Platform.environment[name]; if (value == null) fail('$name environment variable is missing. Quitting.'); @@ -313,7 +313,7 @@ String requireEnvVar(String name) { T requireConfigProperty(Map map, String propertyName) { if (!map.containsKey(propertyName)) fail('Configuration property not found: $propertyName'); - T result = map[propertyName]; + final T result = map[propertyName]; return result; } @@ -426,7 +426,7 @@ Iterable grep(Pattern pattern, {@required String from}) { /// /// } Future runAndCaptureAsyncStacks(Future callback()) { - Completer completer = new Completer(); + final Completer completer = new Completer(); Chain.capture(() async { await callback(); completer.complete(); @@ -441,7 +441,7 @@ Future findAvailablePort() async { int port = 20000; while (true) { try { - ServerSocket socket = + final ServerSocket socket = await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port); await socket.close(); return port; diff --git a/dev/devicelab/lib/tasks/gallery.dart b/dev/devicelab/lib/tasks/gallery.dart index 8463dccf62b..0dcd6b006ef 100644 --- a/dev/devicelab/lib/tasks/gallery.dart +++ b/dev/devicelab/lib/tasks/gallery.dart @@ -18,10 +18,10 @@ TaskFunction createGalleryTransitionTest() { class GalleryTransitionTest { Future call() async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); - String deviceId = device.deviceId; - Directory galleryDirectory = + final String deviceId = device.deviceId; + final Directory galleryDirectory = dir('${flutterDirectory.path}/examples/flutter_gallery'); await inDirectory(galleryDirectory, () async { await flutter('packages', options: ['get']); @@ -43,17 +43,17 @@ class GalleryTransitionTest { // Route paths contains slashes, which Firebase doesn't accept in keys, so we // remove them. - Map> original = JSON.decode(file( + final Map> original = JSON.decode(file( '${galleryDirectory.path}/build/transition_durations.timeline.json') .readAsStringSync()); - Map> transitions = new Map>.fromIterable( + final Map> transitions = new Map>.fromIterable( original.keys, key: (String key) => key.replaceAll('/', ''), value: (String key) => original[key]); - Map summary = JSON.decode(file('${galleryDirectory.path}/build/transitions.timeline_summary.json').readAsStringSync()); + final Map summary = JSON.decode(file('${galleryDirectory.path}/build/transitions.timeline_summary.json').readAsStringSync()); - Map data = { + final Map data = { 'transitions': transitions, 'missed_transition_count': _countMissedTransitions(transitions), }; @@ -75,7 +75,7 @@ int _countMissedTransitions(Map> transitions) { const int _kTransitionBudget = 100000; // µs int count = 0; transitions.forEach((String demoName, List durations) { - int longestDuration = durations.reduce(math.max); + final int longestDuration = durations.reduce(math.max); if (longestDuration > _kTransitionBudget) { print('$demoName missed transition time budget ($longestDuration µs > $_kTransitionBudget µs)'); count++; diff --git a/dev/devicelab/lib/tasks/microbenchmarks.dart b/dev/devicelab/lib/tasks/microbenchmarks.dart index fea216d5d3d..20106aa0e80 100644 --- a/dev/devicelab/lib/tasks/microbenchmarks.dart +++ b/dev/devicelab/lib/tasks/microbenchmarks.dart @@ -16,13 +16,13 @@ import 'package:flutter_devicelab/framework/utils.dart'; /// `dev/benchmarks/microbenchmarks` reports results to the dashboard. TaskFunction createMicrobenchmarkTask() { return () async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); Future> _runMicrobench(String benchmarkPath) async { print('Running $benchmarkPath'); - Directory appDir = dir(path.join(flutterDirectory.path, 'dev/benchmarks/microbenchmarks')); - Process flutterProcess = await inDirectory(appDir, () async { + final Directory appDir = dir(path.join(flutterDirectory.path, 'dev/benchmarks/microbenchmarks')); + final Process flutterProcess = await inDirectory(appDir, () async { return await _startFlutter( options: [ '--profile', // --release doesn't work on iOS due to code signing issues @@ -37,7 +37,7 @@ TaskFunction createMicrobenchmarkTask() { return await _readJsonResults(flutterProcess); } - Map allResults = {}; + final Map allResults = {}; allResults.addAll(await _runMicrobench('lib/stocks/layout_bench.dart')); allResults.addAll(await _runMicrobench('lib/stocks/build_bench.dart')); allResults.addAll(await _runMicrobench('lib/gestures/velocity_tracker_bench.dart')); @@ -53,7 +53,7 @@ Future _startFlutter({ bool canFail: false, Map environment, }) { - List args = ['run']..addAll(options); + final List args = ['run']..addAll(options); return startProcess(path.join(flutterDirectory.path, 'bin', 'flutter'), args, environment: environment); } @@ -62,8 +62,8 @@ Future> _readJsonResults(Process process) { const String jsonStart = '================ RESULTS ================'; const String jsonEnd = '================ FORMATTED =============='; bool jsonStarted = false; - StringBuffer jsonBuf = new StringBuffer(); - Completer> completer = new Completer>(); + final StringBuffer jsonBuf = new StringBuffer(); + final Completer> completer = new Completer>(); StreamSubscription stdoutSub; int prefixLength = 0; diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index b51ed4e76cd..960e4c77b44 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -77,7 +77,7 @@ class StartupTest { Future call() async { return await inDirectory(testDirectory, () async { - String deviceId = (await devices.workingDevice).deviceId; + final String deviceId = (await devices.workingDevice).deviceId; await flutter('packages', options: ['get']); if (deviceOperatingSystem == DeviceOperatingSystem.ios) { @@ -91,7 +91,7 @@ class StartupTest { '-d', deviceId, ]).timeout(_startupTimeout); - Map data = JSON.decode(file('$testDirectory/build/start_up_info.json').readAsStringSync()); + final Map data = JSON.decode(file('$testDirectory/build/start_up_info.json').readAsStringSync()); return new TaskResult.success(data, benchmarkScoreKeys: [ 'timeToFirstFrameMicros', ]); @@ -111,9 +111,9 @@ class PerfTest { Future call() { return inDirectory(testDirectory, () async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); - String deviceId = device.deviceId; + final String deviceId = device.deviceId; await flutter('packages', options: ['get']); if (deviceOperatingSystem == DeviceOperatingSystem.ios) { @@ -130,7 +130,7 @@ class PerfTest { '-d', deviceId, ]); - Map data = JSON.decode(file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync()); + final Map data = JSON.decode(file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync()); if (data['frame_count'] < 5) { return new TaskResult.failure( @@ -159,12 +159,12 @@ class BuildTest { Future call() async { return await inDirectory(testDirectory, () async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); await flutter('packages', options: ['get']); - Stopwatch watch = new Stopwatch()..start(); - String buildLog = await evalFlutter('build', options: [ + final Stopwatch watch = new Stopwatch()..start(); + final String buildLog = await evalFlutter('build', options: [ 'aot', '-v', '--profile', @@ -173,9 +173,9 @@ class BuildTest { ]); watch.stop(); - RegExp metricExpression = new RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)'); + final RegExp metricExpression = new RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)'); - Map data = new Map.fromIterable( + final Map data = new Map.fromIterable( metricExpression.allMatches(buildLog), key: (Match m) => _sdkNameToMetricName(m.group(1)), value: (Match m) => int.parse(m.group(2)), @@ -216,9 +216,9 @@ class MemoryTest { Future call() { return inDirectory(testDirectory, () async { - Device device = await devices.workingDevice; + final Device device = await devices.workingDevice; await device.unlock(); - String deviceId = device.deviceId; + final String deviceId = device.deviceId; await flutter('packages', options: ['get']); if (deviceOperatingSystem == DeviceOperatingSystem.ios) { @@ -226,9 +226,9 @@ class MemoryTest { await flutter('build', options: ['ios', '--profile']); } - int observatoryPort = await findAvailablePort(); + final int observatoryPort = await findAvailablePort(); - List runOptions = [ + final List runOptions = [ '-v', '--profile', '--trace-startup', // wait for the first frame to render @@ -241,9 +241,9 @@ class MemoryTest { runOptions.addAll(['-t', testTarget]); await flutter('run', options: runOptions); - Map startData = await device.getMemoryStats(packageName); + final Map startData = await device.getMemoryStats(packageName); - Map data = { + final Map data = { 'start_total_kb': startData['total_kb'], }; @@ -257,7 +257,7 @@ class MemoryTest { '--use-existing-app=http://localhost:$observatoryPort', ]); - Map endData = await device.getMemoryStats(packageName); + final Map endData = await device.getMemoryStats(packageName); data['end_total_kb'] = endData['total_kb']; data['diff_total_kb'] = endData['total_kb'] - startData['total_kb']; } @@ -283,9 +283,9 @@ class AndroidBackButtonMemoryTest { throw 'This test is only supported on Android'; } - AndroidDevice device = await devices.workingDevice; + final AndroidDevice device = await devices.workingDevice; await device.unlock(); - String deviceId = device.deviceId; + final String deviceId = device.deviceId; await flutter('packages', options: ['get']); await flutter('run', options: [ @@ -296,9 +296,9 @@ class AndroidBackButtonMemoryTest { deviceId, ]); - Map startData = await device.getMemoryStats(packageName); + final Map startData = await device.getMemoryStats(packageName); - Map data = { + final Map data = { 'start_total_kb': startData['total_kb'], }; @@ -306,14 +306,14 @@ class AndroidBackButtonMemoryTest { for (int i = 0; i < 10; i++) { await device.shellExec('input', ['keyevent', 'KEYCODE_BACK']); await new Future.delayed(const Duration(milliseconds: 1000)); - String output = await device.shellEval('am', ['start', '-n', 'io.flutter.examples.gallery/io.flutter.app.FlutterActivity']); + final String output = await device.shellEval('am', ['start', '-n', 'io.flutter.examples.gallery/io.flutter.app.FlutterActivity']); print(output); if (output.contains('Error')) return new TaskResult.failure('unable to launch activity'); await new Future.delayed(const Duration(milliseconds: 1000)); } - Map endData = await device.getMemoryStats(packageName); + final Map endData = await device.getMemoryStats(packageName); data['end_total_kb'] = endData['total_kb']; data['diff_total_kb'] = endData['total_kb'] - startData['total_kb']; diff --git a/dev/devicelab/lib/tasks/size_tests.dart b/dev/devicelab/lib/tasks/size_tests.dart index 422ae816fe9..e652bc179ae 100644 --- a/dev/devicelab/lib/tasks/size_tests.dart +++ b/dev/devicelab/lib/tasks/size_tests.dart @@ -12,7 +12,7 @@ import '../framework/utils.dart'; TaskFunction createBasicMaterialAppSizeTest() { return () async { const String sampleAppName = 'sample_flutter_app'; - Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); + final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); if (await sampleDir.exists()) rmTree(sampleDir); diff --git a/dev/devicelab/test/adb_test.dart b/dev/devicelab/test/adb_test.dart index 840758c3bc7..ca72310e1b9 100644 --- a/dev/devicelab/test/adb_test.dart +++ b/dev/devicelab/test/adb_test.dart @@ -129,7 +129,7 @@ class CommandArgs { if (other.runtimeType != CommandArgs) return false; - CommandArgs otherCmd = other; + final CommandArgs otherCmd = other; return otherCmd.command == this.command && const ListEquality().equals(otherCmd.arguments, this.arguments) && const MapEquality().equals(otherCmd.environment, this.environment); @@ -188,7 +188,7 @@ class FakeDevice extends AndroidDevice { arguments: arguments, environment: environment, )); - dynamic exitError = exitErrorFactory(); + final dynamic exitError = exitErrorFactory(); if (exitError != null) throw exitError; } diff --git a/dev/devicelab/test/manifest_test.dart b/dev/devicelab/test/manifest_test.dart index 28eb0d99a1f..2478e26b5ca 100644 --- a/dev/devicelab/test/manifest_test.dart +++ b/dev/devicelab/test/manifest_test.dart @@ -9,10 +9,10 @@ import 'package:flutter_devicelab/framework/manifest.dart'; void main() { group('production manifest', () { test('must be valid', () { - Manifest manifest = loadTaskManifest(); + final Manifest manifest = loadTaskManifest(); expect(manifest.tasks, isNotEmpty); - ManifestTask task = manifest.tasks.firstWhere((ManifestTask task) => task.name == 'flutter_gallery__start_up'); + final ManifestTask task = manifest.tasks.firstWhere((ManifestTask task) => task.name == 'flutter_gallery__start_up'); expect(task.description, 'Measures the startup time of the Flutter Gallery app on Android.\n'); expect(task.stage, 'devicelab'); expect(task.requiredAgentCapabilities, ['has-android-device']); diff --git a/dev/devicelab/test/run_test.dart b/dev/devicelab/test/run_test.dart index 3f7c77a98c2..4a1b2d59cb1 100644 --- a/dev/devicelab/test/run_test.dart +++ b/dev/devicelab/test/run_test.dart @@ -10,11 +10,11 @@ import 'package:test/test.dart'; void main() { group('run.dart script', () { Future runScript(List testNames) async { - List options = ['bin/run.dart']; + final List options = ['bin/run.dart']; for (String testName in testNames) { options..addAll(['-t', testName]); } - ProcessResult scriptProcess = Process.runSync( + final ProcessResult scriptProcess = Process.runSync( '../../bin/cache/dart-sdk/bin/dart', options, ); diff --git a/dev/manual_tests/card_collection.dart b/dev/manual_tests/card_collection.dart index b8a5b1e702b..0bfca126d93 100644 --- a/dev/manual_tests/card_collection.dart +++ b/dev/manual_tests/card_collection.dart @@ -42,7 +42,7 @@ class CardCollectionState extends State { bool _varyFontSizes = false; void _initVariableSizedCardModels() { - List cardHeights = [ + final List cardHeights = [ 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, @@ -119,7 +119,7 @@ class CardCollectionState extends State { } String _dismissDirectionText(DismissDirection direction) { - String s = direction.toString(); + final String s = direction.toString(); return "dismiss ${s.substring(s.indexOf('.') + 1)}"; } @@ -247,8 +247,8 @@ class CardCollectionState extends State { } Widget _buildCard(BuildContext context, int index) { - CardModel cardModel = _cardModels[index]; - Widget card = new Dismissable( + final CardModel cardModel = _cardModels[index]; + final Widget card = new Dismissable( key: new ObjectKey(cardModel), direction: _dismissDirection, onDismissed: (DismissDirection direction) { dismissCard(cardModel); }, @@ -318,7 +318,7 @@ class CardCollectionState extends State { // size of the background,card Stack will be based only on the card. The // Viewport ensures that when the card's resize animation occurs, the // background (text and icons) will just be clipped, not resized. - Widget background = new Positioned.fill( + final Widget background = new Positioned.fill( child: new Container( margin: const EdgeInsets.all(4.0), child: new SingleChildScrollView( @@ -376,7 +376,7 @@ class CardCollectionState extends State { ); } - Widget body = new Container( + final Widget body = new Container( padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0), color: _primaryColor[50], child: cardCollection, diff --git a/dev/manual_tests/drag_and_drop.dart b/dev/manual_tests/drag_and_drop.dart index d32ad69ea07..1986d25053f 100644 --- a/dev/manual_tests/drag_and_drop.dart +++ b/dev/manual_tests/drag_and_drop.dart @@ -97,7 +97,7 @@ class ExampleDragSource extends StatelessWidget { if (heavy) size *= kHeavyMultiplier; - Widget contents = new DefaultTextStyle( + final Widget contents = new DefaultTextStyle( style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center, child: new Dot( @@ -185,7 +185,7 @@ class MovableBall extends StatelessWidget { @override Widget build(BuildContext context) { - Widget ball = new DefaultTextStyle( + final Widget ball = new DefaultTextStyle( style: Theme.of(context).primaryTextTheme.body1, textAlign: TextAlign.center, child: new Dot( @@ -196,7 +196,7 @@ class MovableBall extends StatelessWidget { child: new Center(child: new Text('BALL')) ) ); - Widget dashedBall = new Container( + final Widget dashedBall = new Container( width: kBallSize, height: kBallSize, child: new CustomPaint( diff --git a/dev/manual_tests/overlay_geometry.dart b/dev/manual_tests/overlay_geometry.dart index 4efc6af0315..4c283b1449f 100644 --- a/dev/manual_tests/overlay_geometry.dart +++ b/dev/manual_tests/overlay_geometry.dart @@ -31,8 +31,8 @@ class _MarkerPainter extends CustomPainter { @override void paint(Canvas canvas, _) { - Paint paint = new Paint()..color = const Color(0x8000FF00); - double r = size / 2.0; + final Paint paint = new Paint()..color = const Color(0x8000FF00); + final double r = size / 2.0; canvas.drawCircle(new Point(r, r), r, paint); paint @@ -107,7 +107,7 @@ class CardBuilder extends SliverChildDelegate { Widget build(BuildContext context, int index) { if (index >= cardModels.length) return null; - CardModel cardModel = cardModels[index]; + final CardModel cardModel = cardModels[index]; return new GestureDetector( key: cardModel.key, onTapUp: (TapUpDetails details) { onTapUp(cardModel.targetKey, details.globalPosition); }, @@ -140,13 +140,13 @@ class OverlayGeometryAppState extends State { @override void initState() { super.initState(); - List cardHeights = [ + final List cardHeights = [ 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, 48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0, ]; cardModels = new List.generate(cardHeights.length, (int i) { - Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardHeights.length); + final Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardHeights.length); return new CardModel(i, cardHeights[i], color); }); } @@ -154,10 +154,10 @@ class OverlayGeometryAppState extends State { bool handleScrollNotification(ScrollNotification notification) { if (notification is ScrollUpdateNotification && notification.depth == 1) { setState(() { - double dy = markersScrollOffset - notification.metrics.extentBefore; + final double dy = markersScrollOffset - notification.metrics.extentBefore; markersScrollOffset = notification.metrics.extentBefore; for (MarkerType type in markers.keys) { - Point oldPosition = markers[type]; + final Point oldPosition = markers[type]; markers[type] = new Point(oldPosition.x, oldPosition.y + dy); } }); @@ -179,7 +179,7 @@ class OverlayGeometryAppState extends State { @override Widget build(BuildContext context) { - List layers = [ + final List layers = [ new Scaffold( appBar: new AppBar(title: new Text('Tap a Card')), body: new Container( diff --git a/dev/manual_tests/page_view.dart b/dev/manual_tests/page_view.dart index 724b816ff38..776fb64d211 100644 --- a/dev/manual_tests/page_view.dart +++ b/dev/manual_tests/page_view.dart @@ -31,7 +31,7 @@ class PageViewAppState extends State { ]; cardModels = new List.generate(cardSizes.length, (int i) { - Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardSizes.length); + final Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardSizes.length); return new CardModel(i, cardSizes[i], color); }); } @@ -45,7 +45,7 @@ class PageViewAppState extends State { bool itemsWrap = false; Widget buildCard(CardModel cardModel) { - Widget card = new Card( + final Widget card = new Card( color: cardModel.color, child: new Container( width: cardModel.size.width, @@ -55,7 +55,7 @@ class PageViewAppState extends State { ), ); - BoxConstraints constraints = (scrollDirection == Axis.vertical) + final BoxConstraints constraints = (scrollDirection == Axis.vertical) ? new BoxConstraints.tightFor(height: pageSize.height) : new BoxConstraints.tightFor(width: pageSize.width); diff --git a/dev/manual_tests/test/card_collection_test.dart b/dev/manual_tests/test/card_collection_test.dart index 34defcbb205..6afde78b109 100644 --- a/dev/manual_tests/test/card_collection_test.dart +++ b/dev/manual_tests/test/card_collection_test.dart @@ -13,7 +13,7 @@ void main() { await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame - Finder navigationMenu = find.byWidgetPredicate((Widget widget) { + final Finder navigationMenu = find.byWidgetPredicate((Widget widget) { if (widget is Tooltip) return widget.message == 'Open navigation menu'; return false; diff --git a/dev/tools/dartdoc.dart b/dev/tools/dartdoc.dart index 577d73438e6..3ae633aa8ac 100644 --- a/dev/tools/dartdoc.dart +++ b/dev/tools/dartdoc.dart @@ -25,7 +25,7 @@ Future main(List args) async { Directory.current = Directory.current.parent.parent; // Create the pubspec.yaml file. - StringBuffer buf = new StringBuffer(''' + final StringBuffer buf = new StringBuffer(''' name: Flutter dependencies: '''); @@ -40,10 +40,10 @@ dependencies: new File('dev/docs/pubspec.yaml').writeAsStringSync(buf.toString()); // Create the library file. - Directory libDir = new Directory('dev/docs/lib'); + final Directory libDir = new Directory('dev/docs/lib'); libDir.createSync(); - StringBuffer contents = new StringBuffer('library temp_doc;\n\n'); + final StringBuffer contents = new StringBuffer('library temp_doc;\n\n'); for (String libraryRef in libraryRefs()) { contents.writeln('import \'package:$libraryRef\';'); } @@ -58,14 +58,14 @@ dependencies: ); printStream(process.stdout); printStream(process.stderr); - int code = await process.exitCode; + final int code = await process.exitCode; if (code != 0) exit(code); createFooter('dev/docs/lib/footer.html'); // Generate the documentation. - List args = [ + final List args = [ 'global', 'run', 'dartdoc', '--header', 'styles.html', '--header', 'analytics.html', @@ -84,7 +84,7 @@ dependencies: process = await Process.start('pub', args, workingDirectory: 'dev/docs'); printStream(process.stdout); printStream(process.stderr); - int exitCode = await process.exitCode; + final int exitCode = await process.exitCode; if (exitCode != 0) exit(exitCode); @@ -95,10 +95,10 @@ dependencies: } void createFooter(String footerPath) { - ProcessResult gitResult = Process.runSync('git', ['rev-parse', 'HEAD']); - String gitHead = (gitResult.exitCode == 0) ? gitResult.stdout.trim() : 'unknown'; + final ProcessResult gitResult = Process.runSync('git', ['rev-parse', 'HEAD']); + final String gitHead = (gitResult.exitCode == 0) ? gitResult.stdout.trim() : 'unknown'; - String timestamp = new DateFormat('yyyy-MM-dd HH:mm').format(new DateTime.now()); + final String timestamp = new DateFormat('yyyy-MM-dd HH:mm').format(new DateTime.now()); new File(footerPath).writeAsStringSync( '

' @@ -107,7 +107,7 @@ void createFooter(String footerPath) { } void sanityCheckDocs() { - List canaries = [ + final List canaries = [ '$kDocRoot/api/dart-io/File-class.html', '$kDocRoot/api/dart-ui/Canvas-class.html', '$kDocRoot/api/dart-ui/Canvas/drawRect.html', @@ -151,7 +151,7 @@ void copyIndexToRootOfDocs() { } void addHtmlBaseToIndex() { - File indexFile = new File('$kDocRoot/index.html'); + final File indexFile = new File('$kDocRoot/index.html'); String indexContents = indexFile.readAsStringSync(); indexContents = indexContents.replaceFirst('\n', '\n \n'); @@ -163,7 +163,7 @@ void addHtmlBaseToIndex() { } void putRedirectInOldIndexLocation() { - String metaTag = ''; + final String metaTag = ''; new File('$kDocRoot/flutter/index.html').writeAsStringSync(metaTag); } @@ -178,7 +178,7 @@ List findPackages() { .where((FileSystemEntity entity) { if (entity is! Directory) return false; - File pubspec = new File('${entity.path}/pubspec.yaml'); + final File pubspec = new File('${entity.path}/pubspec.yaml'); // TODO(ianh): Use a real YAML parser here return !pubspec.readAsStringSync().contains('nodoc: true'); }) @@ -190,7 +190,7 @@ List findPackages() { /// diskPath toggles between import paths vs. disk paths. Iterable libraryRefs({ bool diskPath: false }) sync* { for (Directory dir in findPackages()) { - String dirName = path.basename(dir.path); + final String dirName = path.basename(dir.path); for (FileSystemEntity file in new Directory('${dir.path}/lib').listSync()) { if (file is File && file.path.endsWith('.dart')) { if (diskPath) diff --git a/dev/tools/javadoc.dart b/dev/tools/javadoc.dart index 1c857221d66..e888060bbff 100644 --- a/dev/tools/javadoc.dart +++ b/dev/tools/javadoc.dart @@ -13,26 +13,26 @@ const String kDocRoot = 'dev/docs/doc'; /// This script downloads an archive of Javadoc for the engine from the /// artifact store and extracts it to the location used for Dartdoc. Future main(List args) async { - String engineVersion = new File('bin/internal/engine.version').readAsStringSync().trim(); + final String engineVersion = new File('bin/internal/engine.version').readAsStringSync().trim(); - String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/android-javadoc.zip'; - http.Response response = await http.get(url); + final String url = 'https://storage.googleapis.com/flutter_infra/flutter/$engineVersion/android-javadoc.zip'; + final http.Response response = await http.get(url); - Archive archive = new ZipDecoder().decodeBytes(response.bodyBytes); + final Archive archive = new ZipDecoder().decodeBytes(response.bodyBytes); - Directory output = new Directory('$kDocRoot/javadoc'); + final Directory output = new Directory('$kDocRoot/javadoc'); print('Extracing javadoc to ${output.path}'); output.createSync(recursive: true); for (ArchiveFile af in archive) { if (af.isFile) { - File file = new File('${output.path}/${af.name}'); + final File file = new File('${output.path}/${af.name}'); file.createSync(recursive: true); file.writeAsBytesSync(af.content); } } - File testFile = new File('${output.path}/io/flutter/view/FlutterView.html'); + final File testFile = new File('${output.path}/io/flutter/view/FlutterView.html'); if (!testFile.existsSync()) { print('Expected file ${testFile.path} not found'); exit(1); diff --git a/dev/tools/mega_gallery.dart b/dev/tools/mega_gallery.dart index e53adc35883..fd68187264b 100644 --- a/dev/tools/mega_gallery.dart +++ b/dev/tools/mega_gallery.dart @@ -17,14 +17,14 @@ void main(List args) { if (path.basename(Directory.current.path) == 'tools') Directory.current = Directory.current.parent.parent; - ArgParser argParser = new ArgParser(); + final ArgParser argParser = new ArgParser(); // ../mega_gallery? dev/benchmarks/mega_gallery? argParser.addOption('out', defaultsTo: _normalize('dev/benchmarks/mega_gallery')); argParser.addOption('copies'); argParser.addFlag('delete', negatable: false); argParser.addFlag('help', abbr: 'h', negatable: false); - ArgResults results = argParser.parse(args); + final ArgResults results = argParser.parse(args); if (results['help']) { print('Generate n copies of flutter_gallery.\n'); @@ -33,8 +33,8 @@ void main(List args) { exit(0); } - Directory source = new Directory(_normalize('examples/flutter_gallery')); - Directory out = new Directory(_normalize(results['out'])); + final Directory source = new Directory(_normalize('examples/flutter_gallery')); + final Directory out = new Directory(_normalize(results['out'])); if (results['delete']) { if (out.existsSync()) { @@ -47,7 +47,7 @@ void main(List args) { int copies; if (!results.wasParsed('copies')) { - SourceStats stats = getStatsFor(_dir(source, 'lib')); + final SourceStats stats = getStatsFor(_dir(source, 'lib')); copies = (kTargetLineCount / stats.lines).round(); } else { copies = int.parse(results['copies']); @@ -59,7 +59,7 @@ void main(List args) { print(' packages/flutter : ${getStatsFor(new Directory("packages/flutter"))}'); print(' examples/flutter_gallery : ${getStatsFor(new Directory("examples/flutter_gallery"))}'); - Directory lib = _dir(out, 'lib'); + final Directory lib = _dir(out, 'lib'); if (lib.existsSync()) lib.deleteSync(recursive: true); @@ -86,15 +86,15 @@ void main(List args) { // TODO(devoncarew): Create an entry-point that builds a UI with all `n` copies. void _createEntry(File mainFile, int copies) { - StringBuffer imports = new StringBuffer(); - StringBuffer importRefs = new StringBuffer(); + final StringBuffer imports = new StringBuffer(); + final StringBuffer importRefs = new StringBuffer(); for (int i = 1; i < copies; i++) { imports.writeln("import 'gallery_$i/main.dart' as main_$i;"); importRefs.writeln(" main_$i.main;"); } - String contents = ''' + final String contents = ''' // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -116,8 +116,8 @@ void main() { } void _copyGallery(Directory galleryDir, int index) { - Directory lib = _dir(galleryDir, 'lib'); - Directory dest = _dir(lib, 'gallery_$index'); + final Directory lib = _dir(galleryDir, 'lib'); + final Directory dest = _dir(lib, 'gallery_$index'); dest.createSync(); // Copy demo/, gallery/, and main.dart. @@ -131,7 +131,7 @@ void _copy(Directory source, Directory target) { target.createSync(); for (FileSystemEntity entity in source.listSync(followLinks: false)) { - String name = path.basename(entity.path); + final String name = path.basename(entity.path); if (entity is Directory) { if (name == 'build' || name.startsWith('.')) @@ -140,7 +140,7 @@ void _copy(Directory source, Directory target) { } else if (entity is File) { if (name == '.packages' || name == 'pubspec.lock') continue; - File dest = new File(path.join(target.path, name)); + final File dest = new File(path.join(target.path, name)); dest.writeAsBytesSync(entity.readAsBytesSync()); } } @@ -162,7 +162,7 @@ SourceStats getStatsFor(Directory dir, [SourceStats stats]) { stats ??= new SourceStats(); for (FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) { - String name = path.basename(entity.path); + final String name = path.basename(entity.path); if (entity is File && name.endsWith('.dart')) { stats.files += 1; stats.lines += _lineCount(entity); @@ -184,7 +184,7 @@ int _lineCount(File file) { } String _comma(int count) { - String str = count.toString(); + final String str = count.toString(); if (str.length > 3) return str.substring(0, str.length - 3) + ',' + str.substring(str.length - 3); return str; diff --git a/dev/tools/update_icons.dart b/dev/tools/update_icons.dart index 690ad2ed3e4..0b3e46feb17 100644 --- a/dev/tools/update_icons.dart +++ b/dev/tools/update_icons.dart @@ -33,26 +33,26 @@ void main(List args) { if (path.basename(Directory.current.path) == 'tools') Directory.current = Directory.current.parent.parent; - ArgParser argParser = new ArgParser(); + final ArgParser argParser = new ArgParser(); argParser.addOption(kOptionCodepointsPath, defaultsTo: kDefaultCodepointsPath); argParser.addOption(kOptionIconsPath, defaultsTo: kDefaultIconsPath); argParser.addFlag(kOptionDryRun, defaultsTo: false); - ArgResults argResults = argParser.parse(args); + final ArgResults argResults = argParser.parse(args); - File iconFile = new File(path.absolute(argResults[kOptionIconsPath])); + final File iconFile = new File(path.absolute(argResults[kOptionIconsPath])); if (!iconFile.existsSync()) { stderr.writeln('Icons file not found: ${iconFile.path}'); exit(1); } - File codepointsFile = new File(path.absolute(argResults[kOptionCodepointsPath])); + final File codepointsFile = new File(path.absolute(argResults[kOptionCodepointsPath])); if (!codepointsFile.existsSync()) { stderr.writeln('Codepoints file not found: ${codepointsFile.path}'); exit(1); } - String iconData = iconFile.readAsStringSync(); - String codepointData = codepointsFile.readAsStringSync(); - String newIconData = regenerateIconsFile(iconData, codepointData); + final String iconData = iconFile.readAsStringSync(); + final String codepointData = codepointsFile.readAsStringSync(); + final String newIconData = regenerateIconsFile(iconData, codepointData); if (argResults[kOptionDryRun]) stdout.writeln(newIconData); @@ -61,14 +61,14 @@ void main(List args) { } String regenerateIconsFile(String iconData, String codepointData) { - StringBuffer buf = new StringBuffer(); + final StringBuffer buf = new StringBuffer(); bool generating = false; for (String line in LineSplitter.split(iconData)) { if (!generating) buf.writeln(line); if (line.contains(kBeginGeneratedMark)) { generating = true; - String iconDeclarations = generateIconDeclarations(codepointData); + final String iconDeclarations = generateIconDeclarations(codepointData); buf.write(iconDeclarations); } else if (line.contains(kEndGeneratedMark)) { generating = false; @@ -87,13 +87,13 @@ String generateIconDeclarations(String codepointData) { } String getIconDeclaration(String line) { - List tokens = line.split(' '); + final List tokens = line.split(' '); if (tokens.length != 2) throw new FormatException('Unexpected codepoint data: $line'); - String name = tokens[0]; - String codepoint = tokens[1]; - String identifier = kIdentifierRewrites[name] ?? name; - String description = name.replaceAll('_', ' '); + final String name = tokens[0]; + final String codepoint = tokens[1]; + final String identifier = kIdentifierRewrites[name] ?? name; + final String description = name.replaceAll('_', ' '); return ''' ///

$name — material icon named "$description".