Unverified Commit ec1a0150 authored by Alexandre Ardhuin's avatar Alexandre Ardhuin Committed by GitHub

implicit-casts:false in dev (#45787)

parent fa0c49d7
...@@ -278,7 +278,7 @@ class AnimatedBezierState extends State<AnimatedBezier> ...@@ -278,7 +278,7 @@ class AnimatedBezierState extends State<AnimatedBezier>
//From http://wiki.roblox.com/index.php?title=File:Beziereq4.png //From http://wiki.roblox.com/index.php?title=File:Beziereq4.png
double _getCubicPoint(double t, double p0, double p1, double p2, double p3) { double _getCubicPoint(double t, double p0, double p1, double p2, double p3) {
return pow(1 - t, 3) * p0 + return (pow(1 - t, 3) as double) * p0 +
3 * pow(1 - t, 2) * t * p1 + 3 * pow(1 - t, 2) * t * p1 +
3 * (1 - t) * pow(t, 2) * p2 + 3 * (1 - t) * pow(t, 2) * p2 +
pow(t, 3) * p3; pow(t, 3) * p3;
......
...@@ -19,7 +19,7 @@ Future<void> main() async { ...@@ -19,7 +19,7 @@ Future<void> main() async {
// We control the framePolicy below to prevent us from scheduling frames in // We control the framePolicy below to prevent us from scheduling frames in
// the engine, so that the engine does not interfere with our timings. // the engine, so that the engine does not interfere with our timings.
final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as LiveTestWidgetsFlutterBinding;
final Stopwatch watch = Stopwatch(); final Stopwatch watch = Stopwatch();
int iterations = 0; int iterations = 0;
......
...@@ -20,7 +20,7 @@ Future<void> main() async { ...@@ -20,7 +20,7 @@ Future<void> main() async {
// We control the framePolicy below to prevent us from scheduling frames in // We control the framePolicy below to prevent us from scheduling frames in
// the engine, so that the engine does not interfere with our timings. // the engine, so that the engine does not interfere with our timings.
final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as LiveTestWidgetsFlutterBinding;
final Stopwatch watch = Stopwatch(); final Stopwatch watch = Stopwatch();
int iterations = 0; int iterations = 0;
......
...@@ -78,7 +78,7 @@ void main(List<String> arguments) { ...@@ -78,7 +78,7 @@ void main(List<String> arguments) {
final ArgResults parsedArguments = argParser.parse(arguments); final ArgResults parsedArguments = argParser.parse(arguments);
if (parsedArguments['help']) { if (parsedArguments['help'] as bool) {
print(argParser.usage); print(argParser.usage);
exit(0); exit(0);
} }
...@@ -93,8 +93,9 @@ void main(List<String> arguments) { ...@@ -93,8 +93,9 @@ void main(List<String> arguments) {
Directory tempDirectory; Directory tempDirectory;
if (parsedArguments.wasParsed('temp')) { if (parsedArguments.wasParsed('temp')) {
tempDirectory = Directory(path.join(Directory.systemTemp.absolute.path, path.basename(parsedArguments['temp']))); final String tempArg = parsedArguments['temp'] as String;
if (path.basename(parsedArguments['temp']) != parsedArguments['temp']) { tempDirectory = Directory(path.join(Directory.systemTemp.absolute.path, path.basename(tempArg)));
if (path.basename(tempArg) != tempArg) {
stderr.writeln('Supplied temporary directory name should be a name, not a path. Using ${tempDirectory.absolute.path} instead.'); stderr.writeln('Supplied temporary directory name should be a name, not a path. Using ${tempDirectory.absolute.path} instead.');
} }
print('Leaving temporary output in ${tempDirectory.absolute.path}.'); print('Leaving temporary output in ${tempDirectory.absolute.path}.');
...@@ -106,7 +107,11 @@ void main(List<String> arguments) { ...@@ -106,7 +107,11 @@ void main(List<String> arguments) {
tempDirectory.createSync(); tempDirectory.createSync();
} }
try { try {
exitCode = SampleChecker(flutterPackage, tempDirectory: tempDirectory, verbose: parsedArguments['verbose']).checkSamples(); exitCode = SampleChecker(
flutterPackage,
tempDirectory: tempDirectory,
verbose: parsedArguments['verbose'] as bool,
).checkSamples();
} on SampleCheckerException catch (e) { } on SampleCheckerException catch (e) {
stderr.write(e); stderr.write(e);
exit(1); exit(1);
......
...@@ -290,10 +290,11 @@ const Set<String> _exemptTestImports = <String>{ ...@@ -290,10 +290,11 @@ const Set<String> _exemptTestImports = <String>{
Future<void> verifyNoTestImports(String workingDirectory) async { Future<void> verifyNoTestImports(String workingDirectory) async {
final List<String> errors = <String>[]; final List<String> errors = <String>[];
assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern)); assert("// foo\nimport 'binding_test.dart' as binding;\n'".contains(_testImportPattern));
for (FileSystemEntity entity in Directory(path.join(workingDirectory, 'packages')) final Iterable<File> dartFiles = Directory(path.join(workingDirectory, 'packages'))
.listSync(recursive: true) .listSync(recursive: true)
.where((FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart')) { .whereType<File>()
final File file = entity; .where((File file) => path.extension(file.path) == '.dart');
for (File file in dartFiles) {
for (String line in file.readAsLinesSync()) { for (String line in file.readAsLinesSync()) {
final Match match = _testImportPattern.firstMatch(line); final Match match = _testImportPattern.firstMatch(line);
if (match != null && !_exemptTestImports.contains(match.group(2))) if (match != null && !_exemptTestImports.contains(match.group(2)))
...@@ -316,11 +317,9 @@ Future<void> verifyNoTestPackageImports(String workingDirectory) async { ...@@ -316,11 +317,9 @@ Future<void> verifyNoTestPackageImports(String workingDirectory) async {
final List<String> shims = <String>[]; final List<String> shims = <String>[];
final List<String> errors = Directory(workingDirectory) final List<String> errors = Directory(workingDirectory)
.listSync(recursive: true) .listSync(recursive: true)
.where((FileSystemEntity entity) { .whereType<File>()
return entity is File && entity.path.endsWith('.dart'); .where((File file) => file.path.endsWith('.dart'))
}) .map<String>((File file) {
.map<String>((FileSystemEntity entity) {
final File file = entity;
final String name = Uri.file(path.relative(file.path, final String name = Uri.file(path.relative(file.path,
from: workingDirectory)).toFilePath(windows: false); from: workingDirectory)).toFilePath(windows: false);
if (name.startsWith('bin/cache') || if (name.startsWith('bin/cache') ||
...@@ -395,14 +394,10 @@ Future<void> verifyGeneratedPluginRegistrants(String flutterRoot) async { ...@@ -395,14 +394,10 @@ Future<void> verifyGeneratedPluginRegistrants(String flutterRoot) async {
final Map<String, List<File>> packageToRegistrants = <String, List<File>>{}; final Map<String, List<File>> packageToRegistrants = <String, List<File>>{};
for (FileSystemEntity entity in flutterRootDir.listSync(recursive: true)) { for (File file in flutterRootDir.listSync(recursive: true).whereType<File>().where(_isGeneratedPluginRegistrant)) {
if (entity is! File) final String package = _getPackageFor(file, flutterRootDir);
continue; final List<File> registrants = packageToRegistrants.putIfAbsent(package, () => <File>[]);
if (_isGeneratedPluginRegistrant(entity)) { registrants.add(file);
final String package = _getPackageFor(entity, flutterRootDir);
final List<File> registrants = packageToRegistrants.putIfAbsent(package, () => <File>[]);
registrants.add(entity);
}
} }
final Set<String> outOfDate = <String>{}; final Set<String> outOfDate = <String>{};
...@@ -497,10 +492,11 @@ Future<void> verifyNoBadImportsInFlutter(String workingDirectory) async { ...@@ -497,10 +492,11 @@ Future<void> verifyNoBadImportsInFlutter(String workingDirectory) async {
Future<void> verifyNoBadImportsInFlutterTools(String workingDirectory) async { Future<void> verifyNoBadImportsInFlutterTools(String workingDirectory) async {
final List<String> errors = <String>[]; final List<String> errors = <String>[];
for (FileSystemEntity entity in Directory(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib')) final Iterable<File> files = Directory(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'))
.listSync(recursive: true) .listSync(recursive: true)
.where((FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart')) { .whereType<File>()
final File file = entity; .where((File file) => path.extension(file.path) == '.dart');
for (File file in files) {
if (file.readAsStringSync().contains('package:flutter_tools/')) { if (file.readAsStringSync().contains('package:flutter_tools/')) {
errors.add('$yellow${file.path}$reset imports flutter_tools.'); errors.add('$yellow${file.path}$reset imports flutter_tools.');
} }
...@@ -745,31 +741,33 @@ final RegExp _importPattern = RegExp(r'''^\s*import (['"])package:flutter/([^.]+ ...@@ -745,31 +741,33 @@ final RegExp _importPattern = RegExp(r'''^\s*import (['"])package:flutter/([^.]+
final RegExp _importMetaPattern = RegExp(r'''^\s*import (['"])package:meta/meta\.dart\1'''); final RegExp _importMetaPattern = RegExp(r'''^\s*import (['"])package:meta/meta\.dart\1''');
Set<String> _findFlutterDependencies(String srcPath, List<String> errors, { bool checkForMeta = false }) { Set<String> _findFlutterDependencies(String srcPath, List<String> errors, { bool checkForMeta = false }) {
return Directory(srcPath).listSync(recursive: true).where((FileSystemEntity entity) { return Directory(srcPath)
return entity is File && path.extension(entity.path) == '.dart'; .listSync(recursive: true)
}).map<Set<String>>((FileSystemEntity entity) { .whereType<File>()
final Set<String> result = <String>{}; .where((File file) => path.extension(file.path) == '.dart')
final File file = entity; .map<Set<String>>((File file) {
for (String line in file.readAsLinesSync()) { final Set<String> result = <String>{};
Match match = _importPattern.firstMatch(line); for (String line in file.readAsLinesSync()) {
if (match != null) Match match = _importPattern.firstMatch(line);
result.add(match.group(2)); if (match != null)
if (checkForMeta) { result.add(match.group(2));
match = _importMetaPattern.firstMatch(line); if (checkForMeta) {
if (match != null) { match = _importMetaPattern.firstMatch(line);
errors.add( if (match != null) {
'${file.path}\nThis package imports the ${yellow}meta$reset package.\n' errors.add(
'You should instead import the "foundation.dart" library.' '${file.path}\nThis package imports the ${yellow}meta$reset package.\n'
); 'You should instead import the "foundation.dart" library.'
);
}
} }
} }
} return result;
return result; })
}).reduce((Set<String> value, Set<String> element) { .reduce((Set<String> value, Set<String> element) {
value ??= <String>{}; value ??= <String>{};
value.addAll(element); value.addAll(element);
return value; return value;
}); });
} }
List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) { List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) {
......
...@@ -82,9 +82,9 @@ class FlutterCompactFormatter { ...@@ -82,9 +82,9 @@ class FlutterCompactFormatter {
print(raw); print(raw);
return null; return null;
} }
final Map<String, dynamic> decoded = json.decode(raw); final Map<String, dynamic> decoded = json.decode(raw) as Map<String, dynamic>;
final TestResult originalResult = _tests[decoded['testID']]; final TestResult originalResult = _tests[decoded['testID']];
switch (decoded['type']) { switch (decoded['type'] as String) {
case 'done': case 'done':
stdout.write(_clearLine); stdout.write(_clearLine);
stdout.write('$_bold${_stopwatch.elapsed}$_noColor '); stdout.write('$_bold${_stopwatch.elapsed}$_noColor ');
...@@ -92,7 +92,7 @@ class FlutterCompactFormatter { ...@@ -92,7 +92,7 @@ class FlutterCompactFormatter {
'$_green+$successes $_yellow~$skips $_red-$failures:$_bold$_gray Done.$_noColor'); '$_green+$successes $_yellow~$skips $_red-$failures:$_bold$_gray Done.$_noColor');
break; break;
case 'testStart': case 'testStart':
final Map<String, dynamic> testData = decoded['test']; final Map<String, dynamic> testData = decoded['test'] as Map<String, dynamic>;
if (testData['url'] == null) { if (testData['url'] == null) {
started += 1; started += 1;
stdout.write(_clearLine); stdout.write(_clearLine);
...@@ -101,20 +101,20 @@ class FlutterCompactFormatter { ...@@ -101,20 +101,20 @@ class FlutterCompactFormatter {
'$_green+$successes $_yellow~$skips $_red-$failures: $_gray${testData['name']}$_noColor'); '$_green+$successes $_yellow~$skips $_red-$failures: $_gray${testData['name']}$_noColor');
break; break;
} }
_tests[testData['id']] = TestResult( _tests[testData['id'] as int] = TestResult(
id: testData['id'], id: testData['id'] as int,
name: testData['name'], name: testData['name'] as String,
line: testData['root_line'] ?? testData['line'], line: testData['root_line'] as int ?? testData['line'] as int,
column: testData['root_column'] ?? testData['column'], column: testData['root_column'] as int ?? testData['column'] as int,
path: testData['root_url'] ?? testData['url'], path: testData['root_url'] as String ?? testData['url'] as String,
startTime: decoded['time'], startTime: decoded['time'] as int,
); );
break; break;
case 'testDone': case 'testDone':
if (originalResult == null) { if (originalResult == null) {
break; break;
} }
originalResult.endTime = decoded['time']; originalResult.endTime = decoded['time'] as int;
if (decoded['skipped'] == true) { if (decoded['skipped'] == true) {
skips += 1; skips += 1;
originalResult.status = TestStatus.skipped; originalResult.status = TestStatus.skipped;
...@@ -129,8 +129,8 @@ class FlutterCompactFormatter { ...@@ -129,8 +129,8 @@ class FlutterCompactFormatter {
} }
break; break;
case 'error': case 'error':
final String error = decoded['error']; final String error = decoded['error'] as String;
final String stackTrace = decoded['stackTrace']; final String stackTrace = decoded['stackTrace'] as String;
if (originalResult != null) { if (originalResult != null) {
originalResult.errorMessage = error; originalResult.errorMessage = error;
originalResult.stackTrace = stackTrace; originalResult.stackTrace = stackTrace;
...@@ -143,7 +143,7 @@ class FlutterCompactFormatter { ...@@ -143,7 +143,7 @@ class FlutterCompactFormatter {
break; break;
case 'print': case 'print':
if (originalResult != null) { if (originalResult != null) {
originalResult.messages.add(decoded['message']); originalResult.messages.add(decoded['message'] as String);
} }
break; break;
case 'group': case 'group':
......
...@@ -39,7 +39,7 @@ class PreparePackageException implements Exception { ...@@ -39,7 +39,7 @@ class PreparePackageException implements Exception {
if (message != null) { if (message != null) {
output += ': $message'; output += ': $message';
} }
final String stderr = result?.stderr ?? ''; final String stderr = result?.stderr as String ?? '';
if (stderr.isNotEmpty) { if (stderr.isNotEmpty) {
output += ':\n$stderr'; output += ':\n$stderr';
} }
...@@ -526,15 +526,15 @@ class ArchivePublisher { ...@@ -526,15 +526,15 @@ class ArchivePublisher {
newEntry['sha256'] = await _getChecksum(outputFile); newEntry['sha256'] = await _getChecksum(outputFile);
// Search for any entries with the same hash and channel and remove them. // Search for any entries with the same hash and channel and remove them.
final List<dynamic> releases = jsonData['releases']; final List<dynamic> releases = jsonData['releases'] as List<dynamic>;
jsonData['releases'] = <Map<String, dynamic>>[ jsonData['releases'] = <Map<String, dynamic>>[
for (Map<String, dynamic> entry in releases) for (Map<String, dynamic> entry in releases.cast<Map<String, dynamic>>())
if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel']) if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel'])
entry, entry,
newEntry, newEntry,
]..sort((Map<String, dynamic> a, Map<String, dynamic> b) { ]..sort((Map<String, dynamic> a, Map<String, dynamic> b) {
final DateTime aDate = DateTime.parse(a['release_date']); final DateTime aDate = DateTime.parse(a['release_date'] as String);
final DateTime bDate = DateTime.parse(b['release_date']); final DateTime bDate = DateTime.parse(b['release_date'] as String);
return bDate.compareTo(aDate); return bDate.compareTo(aDate);
}); });
return jsonData; return jsonData;
...@@ -556,7 +556,7 @@ class ArchivePublisher { ...@@ -556,7 +556,7 @@ class ArchivePublisher {
Map<String, dynamic> jsonData; Map<String, dynamic> jsonData;
try { try {
jsonData = json.decode(currentMetadata); jsonData = json.decode(currentMetadata) as Map<String, dynamic>;
} on FormatException catch (e) { } on FormatException catch (e) {
throw PreparePackageException('Unable to parse JSON metadata received from cloud: $e'); throw PreparePackageException('Unable to parse JSON metadata received from cloud: $e');
} }
...@@ -665,7 +665,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -665,7 +665,7 @@ Future<void> main(List<String> rawArguments) async {
final ArgResults parsedArguments = argParser.parse(rawArguments); final ArgResults parsedArguments = argParser.parse(rawArguments);
if (parsedArguments['help']) { if (parsedArguments['help'] as bool) {
print(argParser.usage); print(argParser.usage);
exit(0); exit(0);
} }
...@@ -676,7 +676,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -676,7 +676,7 @@ Future<void> main(List<String> rawArguments) async {
exit(exitCode); exit(exitCode);
} }
final String revision = parsedArguments['revision']; final String revision = parsedArguments['revision'] as String;
if (revision.isEmpty) { if (revision.isEmpty) {
errorExit('Invalid argument: --revision must be specified.'); errorExit('Invalid argument: --revision must be specified.');
} }
...@@ -684,19 +684,20 @@ Future<void> main(List<String> rawArguments) async { ...@@ -684,19 +684,20 @@ Future<void> main(List<String> rawArguments) async {
errorExit('Invalid argument: --revision must be the entire hash, not just a prefix.'); errorExit('Invalid argument: --revision must be the entire hash, not just a prefix.');
} }
if (parsedArguments['branch'].isEmpty) { if ((parsedArguments['branch'] as String).isEmpty) {
errorExit('Invalid argument: --branch must be specified.'); errorExit('Invalid argument: --branch must be specified.');
} }
final String tempDirArg = parsedArguments['temp_dir'] as String;
Directory tempDir; Directory tempDir;
bool removeTempDir = false; bool removeTempDir = false;
if (parsedArguments['temp_dir'] == null || parsedArguments['temp_dir'].isEmpty) { if (tempDirArg == null || tempDirArg.isEmpty) {
tempDir = Directory.systemTemp.createTempSync('flutter_package.'); tempDir = Directory.systemTemp.createTempSync('flutter_package.');
removeTempDir = true; removeTempDir = true;
} else { } else {
tempDir = Directory(parsedArguments['temp_dir']); tempDir = Directory(tempDirArg);
if (!tempDir.existsSync()) { if (!tempDir.existsSync()) {
errorExit("Temporary directory ${parsedArguments['temp_dir']} doesn't exist."); errorExit("Temporary directory $tempDirArg doesn't exist.");
} }
} }
...@@ -704,20 +705,20 @@ Future<void> main(List<String> rawArguments) async { ...@@ -704,20 +705,20 @@ Future<void> main(List<String> rawArguments) async {
if (parsedArguments['output'] == null) { if (parsedArguments['output'] == null) {
outputDir = tempDir; outputDir = tempDir;
} else { } else {
outputDir = Directory(parsedArguments['output']); outputDir = Directory(parsedArguments['output'] as String);
if (!outputDir.existsSync()) { if (!outputDir.existsSync()) {
outputDir.createSync(recursive: true); outputDir.createSync(recursive: true);
} }
} }
final Branch branch = fromBranchName(parsedArguments['branch']); final Branch branch = fromBranchName(parsedArguments['branch'] as String);
final ArchiveCreator creator = ArchiveCreator(tempDir, outputDir, revision, branch, strict: parsedArguments['publish']); final ArchiveCreator creator = ArchiveCreator(tempDir, outputDir, revision, branch, strict: parsedArguments['publish'] as bool);
int exitCode = 0; int exitCode = 0;
String message; String message;
try { try {
final String version = await creator.initializeRepo(); final String version = await creator.initializeRepo();
final File outputFile = await creator.createArchive(); final File outputFile = await creator.createArchive();
if (parsedArguments['publish']) { if (parsedArguments['publish'] as bool) {
final ArchivePublisher publisher = ArchivePublisher( final ArchivePublisher publisher = ArchivePublisher(
tempDir, tempDir,
revision, revision,
......
...@@ -47,7 +47,7 @@ class FakeProcessManager extends Mock implements ProcessManager { ...@@ -47,7 +47,7 @@ class FakeProcessManager extends Mock implements ProcessManager {
void verifyCalls(List<String> calls) { void verifyCalls(List<String> calls) {
int index = 0; int index = 0;
for (String call in calls) { for (String call in calls) {
expect(call.split(' '), orderedEquals(invocations[index].positionalArguments[0])); expect(call.split(' '), orderedEquals(invocations[index].positionalArguments[0] as Iterable<dynamic>));
index++; index++;
} }
expect(invocations.length, equals(calls.length)); expect(invocations.length, equals(calls.length));
...@@ -66,17 +66,17 @@ class FakeProcessManager extends Mock implements ProcessManager { ...@@ -66,17 +66,17 @@ class FakeProcessManager extends Mock implements ProcessManager {
Future<Process> _nextProcess(Invocation invocation) async { Future<Process> _nextProcess(Invocation invocation) async {
invocations.add(invocation); invocations.add(invocation);
return Future<Process>.value(_popProcess(invocation.positionalArguments[0])); return Future<Process>.value(_popProcess(invocation.positionalArguments[0] as List<String>));
} }
ProcessResult _nextResultSync(Invocation invocation) { ProcessResult _nextResultSync(Invocation invocation) {
invocations.add(invocation); invocations.add(invocation);
return _popResult(invocation.positionalArguments[0]); return _popResult(invocation.positionalArguments[0] as List<String>);
} }
Future<ProcessResult> _nextResult(Invocation invocation) async { Future<ProcessResult> _nextResult(Invocation invocation) async {
invocations.add(invocation); invocations.add(invocation);
return Future<ProcessResult>.value(_popResult(invocation.positionalArguments[0])); return Future<ProcessResult>.value(_popResult(invocation.positionalArguments[0] as List<String>));
} }
void _setupMock() { void _setupMock() {
...@@ -117,8 +117,8 @@ class FakeProcessManager extends Mock implements ProcessManager { ...@@ -117,8 +117,8 @@ class FakeProcessManager extends Mock implements ProcessManager {
/// A fake process that can be used to interact with a process "started" by the FakeProcessManager. /// A fake process that can be used to interact with a process "started" by the FakeProcessManager.
class FakeProcess extends Mock implements Process { class FakeProcess extends Mock implements Process {
FakeProcess(ProcessResult result, {void stdinResults(String input)}) FakeProcess(ProcessResult result, {void stdinResults(String input)})
: stdoutStream = Stream<List<int>>.fromIterable(<List<int>>[result.stdout.codeUnits]), : stdoutStream = Stream<List<int>>.value((result.stdout as String).codeUnits),
stderrStream = Stream<List<int>>.fromIterable(<List<int>>[result.stderr.codeUnits]), stderrStream = Stream<List<int>>.value((result.stderr as String).codeUnits),
desiredExitCode = result.exitCode, desiredExitCode = result.exitCode,
stdinSink = IOSink(StringStreamConsumer(stdinResults)) { stdinSink = IOSink(StringStreamConsumer(stdinResults)) {
_setupMock(); _setupMock();
......
...@@ -328,13 +328,13 @@ void main() { ...@@ -328,13 +328,13 @@ void main() {
expect(contents, contains('"channel": "dev"')); expect(contents, contains('"channel": "dev"'));
// Make sure old matching entries are removed. // Make sure old matching entries are removed.
expect(contents, isNot(contains('v0.0.0'))); expect(contents, isNot(contains('v0.0.0')));
final Map<String, dynamic> jsonData = json.decode(contents); final Map<String, dynamic> jsonData = json.decode(contents) as Map<String, dynamic>;
final List<dynamic> releases = jsonData['releases']; final List<dynamic> releases = jsonData['releases'] as List<dynamic>;
expect(releases.length, equals(3)); expect(releases.length, equals(3));
// Make sure the new entry is first (and hopefully it takes less than a // Make sure the new entry is first (and hopefully it takes less than a
// minute to go from publishArchive above to this line!). // minute to go from publishArchive above to this line!).
expect( expect(
DateTime.now().difference(DateTime.parse(releases[0]['release_date'])), DateTime.now().difference(DateTime.parse(releases[0]['release_date'] as String)),
lessThan(const Duration(minutes: 1)), lessThan(const Duration(minutes: 1)),
); );
const JsonEncoder encoder = JsonEncoder.withIndent(' '); const JsonEncoder encoder = JsonEncoder.withIndent(' ');
......
...@@ -41,7 +41,7 @@ class UnpublishException implements Exception { ...@@ -41,7 +41,7 @@ class UnpublishException implements Exception {
if (message != null) { if (message != null) {
output += ': $message'; output += ': $message';
} }
final String stderr = result?.stderr ?? ''; final String stderr = result?.stderr as String ?? '';
if (stderr.isNotEmpty) { if (stderr.isNotEmpty) {
output += ':\n$stderr'; output += ':\n$stderr';
} }
...@@ -242,8 +242,8 @@ class ArchiveUnpublisher { ...@@ -242,8 +242,8 @@ class ArchiveUnpublisher {
/// Remove the archive from Google Storage. /// Remove the archive from Google Storage.
Future<void> unpublishArchive() async { Future<void> unpublishArchive() async {
final Map<String, dynamic> jsonData = await _loadMetadata(); final Map<String, dynamic> jsonData = await _loadMetadata();
final List<Map<String, String>> releases = jsonData['releases'].map<Map<String, String>>((dynamic entry) { final List<Map<String, String>> releases = (jsonData['releases'] as List<dynamic>).map<Map<String, String>>((dynamic entry) {
final Map<String, dynamic> mapEntry = entry; final Map<String, dynamic> mapEntry = entry as Map<String, dynamic>;
return mapEntry.cast<String, String>(); return mapEntry.cast<String, String>();
}).toList(); }).toList();
final Map<Channel, Map<String, String>> paths = await _getArchivePaths(releases); final Map<Channel, Map<String, String>> paths = await _getArchivePaths(releases);
...@@ -306,7 +306,7 @@ class ArchiveUnpublisher { ...@@ -306,7 +306,7 @@ class ArchiveUnpublisher {
Map<String, dynamic> jsonData; Map<String, dynamic> jsonData;
try { try {
jsonData = json.decode(currentMetadata); jsonData = json.decode(currentMetadata) as Map<String, dynamic>;
} on FormatException catch (e) { } on FormatException catch (e) {
throw UnpublishException('Unable to parse JSON metadata received from cloud: $e'); throw UnpublishException('Unable to parse JSON metadata received from cloud: $e');
} }
...@@ -449,7 +449,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -449,7 +449,7 @@ Future<void> main(List<String> rawArguments) async {
final ArgResults parsedArguments = argParser.parse(rawArguments); final ArgResults parsedArguments = argParser.parse(rawArguments);
if (parsedArguments['help']) { if (parsedArguments['help'] as bool) {
print(argParser.usage); print(argParser.usage);
exit(0); exit(0);
} }
...@@ -460,7 +460,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -460,7 +460,7 @@ Future<void> main(List<String> rawArguments) async {
exit(exitCode); exit(exitCode);
} }
final List<String> revisions = parsedArguments['revision']; final List<String> revisions = parsedArguments['revision'] as List<String>;
if (revisions.isEmpty) { if (revisions.isEmpty) {
errorExit('Invalid argument: at least one --revision must be specified.'); errorExit('Invalid argument: at least one --revision must be specified.');
} }
...@@ -473,25 +473,28 @@ Future<void> main(List<String> rawArguments) async { ...@@ -473,25 +473,28 @@ Future<void> main(List<String> rawArguments) async {
} }
} }
final String tempDirArg = parsedArguments['temp_dir'] as String;
Directory tempDir; Directory tempDir;
bool removeTempDir = false; bool removeTempDir = false;
if (parsedArguments['temp_dir'] == null || parsedArguments['temp_dir'].isEmpty) { if (tempDirArg == null || tempDirArg.isEmpty) {
tempDir = Directory.systemTemp.createTempSync('flutter_package.'); tempDir = Directory.systemTemp.createTempSync('flutter_package.');
removeTempDir = true; removeTempDir = true;
} else { } else {
tempDir = Directory(parsedArguments['temp_dir']); tempDir = Directory(tempDirArg);
if (!tempDir.existsSync()) { if (!tempDir.existsSync()) {
errorExit("Temporary directory ${parsedArguments['temp_dir']} doesn't exist."); errorExit("Temporary directory $tempDirArg doesn't exist.");
} }
} }
if (!parsedArguments['confirm']) { if (!(parsedArguments['confirm'] as bool)) {
_printBanner('This will be just a dry run. To actually perform the changes below, re-run with --confirm argument.'); _printBanner('This will be just a dry run. To actually perform the changes below, re-run with --confirm argument.');
} }
final List<String> channelOptions = parsedArguments['channel'].isNotEmpty ? parsedArguments['channel'] : allowedChannelValues; final List<String> channelArg = parsedArguments['channel'] as List<String>;
final List<String> channelOptions = channelArg.isNotEmpty ? channelArg : allowedChannelValues;
final Set<Channel> channels = channelOptions.map<Channel>((String value) => fromChannelName(value)).toSet(); final Set<Channel> channels = channelOptions.map<Channel>((String value) => fromChannelName(value)).toSet();
final List<String> platformOptions = parsedArguments['platform'].isNotEmpty ? parsedArguments['platform'] : allowedPlatformNames; final List<String> platformArg = parsedArguments['platform'] as List<String>;
final List<String> platformOptions = platformArg.isNotEmpty ? platformArg : allowedPlatformNames;
final List<PublishedPlatform> platforms = platformOptions.map<PublishedPlatform>((String value) => fromPublishedPlatform(value)).toList(); final List<PublishedPlatform> platforms = platformOptions.map<PublishedPlatform>((String value) => fromPublishedPlatform(value)).toList();
int exitCode = 0; int exitCode = 0;
String message; String message;
...@@ -503,7 +506,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -503,7 +506,7 @@ Future<void> main(List<String> rawArguments) async {
revisions.toSet(), revisions.toSet(),
channels, channels,
platform, platform,
confirmed: parsedArguments['confirm'], confirmed: parsedArguments['confirm'] as bool,
); );
await publisher.unpublishArchive(); await publisher.unpublishArchive();
} }
...@@ -522,7 +525,7 @@ Future<void> main(List<String> rawArguments) async { ...@@ -522,7 +525,7 @@ Future<void> main(List<String> rawArguments) async {
if (exitCode != 0) { if (exitCode != 0) {
errorExit('$message\n$stack', exitCode: exitCode); errorExit('$message\n$stack', exitCode: exitCode);
} }
if (!parsedArguments['confirm']) { if (!(parsedArguments['confirm'] as bool)) {
_printBanner('This was just a dry run. To actually perform the above changes, re-run with --confirm argument.'); _printBanner('This was just a dry run. To actually perform the above changes, re-run with --confirm argument.');
} }
exit(0); exit(0);
......
...@@ -65,11 +65,11 @@ Future<bool> run(List<String> arguments) async { ...@@ -65,11 +65,11 @@ Future<bool> run(List<String> arguments) async {
exit(1); exit(1);
} }
final int repeat = int.tryParse(parsedArguments['repeat']); final int repeat = int.tryParse(parsedArguments['repeat'] as String);
final bool skipOnFetchFailure = parsedArguments['skip-on-fetch-failure']; final bool skipOnFetchFailure = parsedArguments['skip-on-fetch-failure'] as bool;
final bool skipTemplate = parsedArguments['skip-template']; final bool skipTemplate = parsedArguments['skip-template'] as bool;
final bool verbose = parsedArguments['verbose']; final bool verbose = parsedArguments['verbose'] as bool;
final bool help = parsedArguments['help']; final bool help = parsedArguments['help'] as bool;
final List<File> files = parsedArguments final List<File> files = parsedArguments
.rest .rest
.expand((String path) => Glob(path).listSync()) .expand((String path) => Glob(path).listSync())
......
...@@ -55,9 +55,9 @@ Future<void> main(List<String> rawArgs) async { ...@@ -55,9 +55,9 @@ Future<void> main(List<String> rawArgs) async {
return; return;
} }
final bool silent = args['silent']; final bool silent = args['silent'] as bool;
final String localEngine = args['local-engine']; final String localEngine = args['local-engine'] as String;
final String localEngineSrcPath = args['local-engine-src-path']; final String localEngineSrcPath = args['local-engine-src-path'] as String;
for (String taskName in _taskNames) { for (String taskName in _taskNames) {
section('Running task "$taskName"'); section('Running task "$taskName"');
...@@ -72,9 +72,9 @@ Future<void> main(List<String> rawArgs) async { ...@@ -72,9 +72,9 @@ Future<void> main(List<String> rawArgs) async {
print(const JsonEncoder.withIndent(' ').convert(result)); print(const JsonEncoder.withIndent(' ').convert(result));
section('Finished task "$taskName"'); section('Finished task "$taskName"');
if (!result['success']) { if (!(result['success'] as bool)) {
exitCode = 1; exitCode = 1;
if (args['exit']) { if (args['exit'] as bool) {
return; return;
} }
} }
...@@ -94,10 +94,10 @@ void addTasks({ ...@@ -94,10 +94,10 @@ void addTasks({
tasks.removeRange(0, index); tasks.removeRange(0, index);
} }
// Only start skipping if user specified a task to continue from // Only start skipping if user specified a task to continue from
final String stage = args['stage']; final String stage = args['stage'] as String;
for (ManifestTask task in tasks) { for (ManifestTask task in tasks) {
final bool isQualifyingStage = stage == null || task.stage == stage; final bool isQualifyingStage = stage == null || task.stage == stage;
final bool isQualifyingHost = !args['match-host-platform'] || task.isSupportedByHost(); final bool isQualifyingHost = !(args['match-host-platform'] as bool) || task.isSupportedByHost();
if (isQualifyingHost && isQualifyingStage) { if (isQualifyingHost && isQualifyingStage) {
taskNames.add(task.name); taskNames.add(task.name);
} }
......
...@@ -86,7 +86,7 @@ void main() { ...@@ -86,7 +86,7 @@ void main() {
const String kActivityId = '$kAppId/com.yourcompany.integration_ui.MainActivity'; const String kActivityId = '$kAppId/com.yourcompany.integration_ui.MainActivity';
task(() async { task(() async {
final AndroidDevice device = await devices.workingDevice; final AndroidDevice device = await devices.workingDevice as AndroidDevice;
await device.unlock(); await device.unlock();
final Directory appDir = dir(path.join(flutterDirectory.path, 'dev/integration_tests/ui')); final Directory appDir = dir(path.join(flutterDirectory.path, 'dev/integration_tests/ui'));
await inDirectory(appDir, () async { await inDirectory(appDir, () async {
......
...@@ -19,7 +19,7 @@ class BackButtonMemoryTest extends MemoryTest { ...@@ -19,7 +19,7 @@ class BackButtonMemoryTest extends MemoryTest {
BackButtonMemoryTest() : super('${flutterDirectory.path}/examples/flutter_gallery', 'test_memory/back_button.dart', packageName); BackButtonMemoryTest() : super('${flutterDirectory.path}/examples/flutter_gallery', 'test_memory/back_button.dart', packageName);
@override @override
AndroidDevice get device => super.device; AndroidDevice get device => super.device as AndroidDevice;
@override @override
int get iterationCount => 5; int get iterationCount => 5;
......
...@@ -178,7 +178,7 @@ Future<void> main() async { ...@@ -178,7 +178,7 @@ Future<void> main() async {
if (result.exitCode == 0) if (result.exitCode == 0)
throw failure( throw failure(
'Gradle did not exit with error as expected', result); 'Gradle did not exit with error as expected', result);
final String output = result.stdout + '\n' + result.stderr; final String output = '${result.stdout}\n${result.stderr}';
if (output.contains('GradleException') || if (output.contains('GradleException') ||
output.contains('Failed to notify') || output.contains('Failed to notify') ||
output.contains('at org.gradle')) output.contains('at org.gradle'))
...@@ -197,7 +197,7 @@ Future<void> main() async { ...@@ -197,7 +197,7 @@ Future<void> main() async {
if (result.exitCode == 0) if (result.exitCode == 0)
throw failure( throw failure(
'flutter build apk should fail when Gradle does', result); 'flutter build apk should fail when Gradle does', result);
final String output = result.stdout + '\n' + result.stderr; final String output = '${result.stdout}\n${result.stderr}';
if (!output.contains('Build failed') || !output.contains('builTypes')) if (!output.contains('Build failed') || !output.contains('builTypes'))
throw failure( throw failure(
'flutter build apk output should contain a readable Gradle error message', 'flutter build apk output should contain a readable Gradle error message',
......
...@@ -19,7 +19,7 @@ const String _kSecondIsolateName = 'second isolate name'; ...@@ -19,7 +19,7 @@ const String _kSecondIsolateName = 'second isolate name';
void main() { void main() {
task(() async { task(() async {
final AndroidDevice device = await devices.workingDevice; final AndroidDevice device = await devices.workingDevice as AndroidDevice;
await device.unlock(); await device.unlock();
section('Compile and run the tester app'); section('Compile and run the tester app');
......
...@@ -17,7 +17,7 @@ void main() { ...@@ -17,7 +17,7 @@ void main() {
Map<String, dynamic> parseFlutterResponse(String line) { Map<String, dynamic> parseFlutterResponse(String line) {
if (line.startsWith('[') && line.endsWith(']')) { if (line.startsWith('[') && line.endsWith(']')) {
try { try {
return json.decode(line)[0]; return json.decode(line)[0] as Map<String, dynamic>;
} catch (e) { } catch (e) {
// Not valid JSON, so likely some other output that was surrounded by [brackets] // Not valid JSON, so likely some other output that was surrounded by [brackets]
return null; return null;
...@@ -60,10 +60,10 @@ void main() { ...@@ -60,10 +60,10 @@ void main() {
final dynamic json = parseFlutterResponse(line); final dynamic json = parseFlutterResponse(line);
if (json != null) { if (json != null) {
if (json['event'] == 'app.debugPort') { if (json['event'] == 'app.debugPort') {
vmServiceUri = Uri.parse(json['params']['wsUri']); vmServiceUri = Uri.parse(json['params']['wsUri'] as String);
print('service protocol connection available at $vmServiceUri'); print('service protocol connection available at $vmServiceUri');
} else if (json['event'] == 'app.started') { } else if (json['event'] == 'app.started') {
appId = json['params']['appId']; appId = json['params']['appId'] as String;
print('application identifier is $appId'); print('application identifier is $appId');
} }
} }
...@@ -129,7 +129,7 @@ void main() { ...@@ -129,7 +129,7 @@ void main() {
if (!ok) if (!ok)
throw 'App failed or crashed during hot reloads.'; throw 'App failed or crashed during hot reloads.';
final List<dynamic> responses = results; final List<dynamic> responses = results as List<dynamic>;
final List<dynamic> errorResponses = responses.where( final List<dynamic> errorResponses = responses.where(
(dynamic r) => r['error'] != null (dynamic r) => r['error'] != null
).toList(); ).toList();
...@@ -141,7 +141,7 @@ void main() { ...@@ -141,7 +141,7 @@ void main() {
if (errorResponses.length != 1) if (errorResponses.length != 1)
throw 'Did not receive the expected (exactly one) hot reload error response.'; throw 'Did not receive the expected (exactly one) hot reload error response.';
final String errorMessage = errorResponses.first['error']; final String errorMessage = (errorResponses.first as Map<String, dynamic>)['error'] as String;
if (!errorMessage.contains('in progress')) if (!errorMessage.contains('in progress'))
throw 'Error response was not that hot reload was in progress.'; throw 'Error response was not that hot reload was in progress.';
if (successResponses.length != 1) if (successResponses.length != 1)
......
...@@ -81,15 +81,15 @@ void main() { ...@@ -81,15 +81,15 @@ void main() {
// validate the fields // validate the fields
// {number: 8, startTime: 0, elapsed: 1437, build: 600, raster: 800} // {number: 8, startTime: 0, elapsed: 1437, build: 600, raster: 800}
expect(event.data['number'] is int); expect(event.data['number'] is int);
expect(event.data['number'] >= 0); expect((event.data['number'] as int) >= 0);
expect(event.data['startTime'] is int); expect(event.data['startTime'] is int);
expect(event.data['startTime'] >= 0); expect((event.data['startTime'] as int) >= 0);
expect(event.data['elapsed'] is int); expect(event.data['elapsed'] is int);
expect(event.data['elapsed'] >= 0); expect((event.data['elapsed'] as int) >= 0);
expect(event.data['build'] is int); expect(event.data['build'] is int);
expect(event.data['build'] >= 0); expect((event.data['build'] as int) >= 0);
expect(event.data['raster'] is int); expect(event.data['raster'] is int);
expect(event.data['raster'] >= 0); expect((event.data['raster'] as int) >= 0);
final Future<VMExtensionEvent> navigationFuture = navigationEvents.first; final Future<VMExtensionEvent> navigationFuture = navigationEvents.first;
// This tap triggers a navigation event. // This tap triggers a navigation event.
...@@ -98,10 +98,10 @@ void main() { ...@@ -98,10 +98,10 @@ void main() {
final VMExtensionEvent navigationEvent = await navigationFuture; final VMExtensionEvent navigationEvent = await navigationFuture;
// validate the fields // validate the fields
expect(navigationEvent.data['route'] is Map<dynamic, dynamic>); expect(navigationEvent.data['route'] is Map<dynamic, dynamic>);
final Map<dynamic, dynamic> route = navigationEvent.data['route']; final Map<dynamic, dynamic> route = navigationEvent.data['route'] as Map<dynamic, dynamic>;
expect(route['description'] is String); expect(route['description'] is String);
expect(route['settings'] is Map<dynamic, dynamic>); expect(route['settings'] is Map<dynamic, dynamic>);
final Map<dynamic, dynamic> settings = route['settings']; final Map<dynamic, dynamic> settings = route['settings'] as Map<dynamic, dynamic>;
expect(settings.containsKey('name')); expect(settings.containsKey('name'));
expect(settings['isInitialRoute'] is bool); expect(settings['isInitialRoute'] is bool);
......
...@@ -128,8 +128,8 @@ class AndroidDeviceDiscovery implements DeviceDiscovery { ...@@ -128,8 +128,8 @@ class AndroidDeviceDiscovery implements DeviceDiscovery {
/// [workingDevice]. /// [workingDevice].
@override @override
Future<void> chooseWorkingDevice() async { Future<void> chooseWorkingDevice() async {
final List<Device> allDevices = (await discoverDevices()) final List<AndroidDevice> allDevices = (await discoverDevices())
.map<Device>((String id) => AndroidDevice(deviceId: id)) .map<AndroidDevice>((String id) => AndroidDevice(deviceId: id))
.toList(); .toList();
if (allDevices.isEmpty) if (allDevices.isEmpty)
......
...@@ -194,8 +194,10 @@ class TaskResult { ...@@ -194,8 +194,10 @@ class TaskResult {
/// Constructs a successful result using JSON data stored in a file. /// Constructs a successful result using JSON data stored in a file.
factory TaskResult.successFromFile(File file, factory TaskResult.successFromFile(File file,
{List<String> benchmarkScoreKeys}) { {List<String> benchmarkScoreKeys}) {
return TaskResult.success(json.decode(file.readAsStringSync()), return TaskResult.success(
benchmarkScoreKeys: benchmarkScoreKeys); json.decode(file.readAsStringSync()) as Map<String, dynamic>,
benchmarkScoreKeys: benchmarkScoreKeys,
);
} }
/// Constructs an unsuccessful result. /// Constructs an unsuccessful result.
......
...@@ -47,7 +47,7 @@ Future<Map<String, dynamic>> measureIosCpuGpu({ ...@@ -47,7 +47,7 @@ Future<Map<String, dynamic>> measureIosCpuGpu({
'-l', '-l',
'${duration.inMilliseconds}', '${duration.inMilliseconds}',
]); ]);
return json.decode(file('$cwd/result.json').readAsStringSync()); return json.decode(file('$cwd/result.json').readAsStringSync()) as Map<String, dynamic>;
} }
Future<String> dylibSymbols(String pathToDylib) { Future<String> dylibSymbols(String pathToDylib) {
......
...@@ -17,8 +17,8 @@ Manifest loadTaskManifest([ String yaml ]) { ...@@ -17,8 +17,8 @@ Manifest loadTaskManifest([ String yaml ]) {
? loadYaml(file('manifest.yaml').readAsStringSync()) ? loadYaml(file('manifest.yaml').readAsStringSync())
: loadYamlNode(yaml); : loadYamlNode(yaml);
_checkType(manifestYaml is Map, manifestYaml, 'Manifest', 'dictionary'); _checkType(manifestYaml is YamlMap, manifestYaml, 'Manifest', 'dictionary');
return _validateAndParseManifest(manifestYaml); return _validateAndParseManifest(manifestYaml as YamlMap);
} }
/// Contains CI task information. /// Contains CI task information.
...@@ -93,21 +93,21 @@ class ManifestError extends Error { ...@@ -93,21 +93,21 @@ class ManifestError extends Error {
// There's no good YAML validator, at least not for Dart, so we validate // There's no good YAML validator, at least not for Dart, so we validate
// manually. It's not too much code and produces good error messages. // manually. It's not too much code and produces good error messages.
Manifest _validateAndParseManifest(Map<dynamic, dynamic> manifestYaml) { Manifest _validateAndParseManifest(YamlMap manifestYaml) {
_checkKeys(manifestYaml, 'manifest', const <String>['tasks']); _checkKeys(manifestYaml, 'manifest', const <String>['tasks']);
return Manifest._(_validateAndParseTasks(manifestYaml['tasks'])); return Manifest._(_validateAndParseTasks(manifestYaml['tasks']));
} }
List<ManifestTask> _validateAndParseTasks(dynamic tasksYaml) { List<ManifestTask> _validateAndParseTasks(dynamic tasksYaml) {
_checkType(tasksYaml is Map, tasksYaml, 'Value of "tasks"', 'dictionary'); _checkType(tasksYaml is YamlMap, tasksYaml, 'Value of "tasks"', 'dictionary');
final List<dynamic> sortedKeys = tasksYaml.keys.toList()..sort(); final List<dynamic> sortedKeys = (tasksYaml as YamlMap).keys.toList()..sort();
return sortedKeys.map<ManifestTask>((dynamic taskName) => _validateAndParseTask(taskName, tasksYaml[taskName])).toList(); return sortedKeys.map<ManifestTask>((dynamic taskName) => _validateAndParseTask(taskName, tasksYaml[taskName])).toList();
} }
ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) { ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) {
_checkType(taskName is String, taskName, 'Task name', 'string'); _checkType(taskName is String, taskName, 'Task name', 'string');
_checkType(taskYaml is Map, taskYaml, 'Value of task "$taskName"', 'dictionary'); _checkType(taskYaml is YamlMap, taskYaml, 'Value of task "$taskName"', 'dictionary');
_checkKeys(taskYaml, 'Value of task "$taskName"', const <String>[ _checkKeys(taskYaml as YamlMap, 'Value of task "$taskName"', const <String>[
'description', 'description',
'stage', 'stage',
'required_agent_capabilities', 'required_agent_capabilities',
...@@ -125,24 +125,24 @@ ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) { ...@@ -125,24 +125,24 @@ ManifestTask _validateAndParseTask(dynamic taskName, dynamic taskYaml) {
_checkType(timeoutInMinutes is int, timeoutInMinutes, 'timeout_in_minutes', 'integer'); _checkType(timeoutInMinutes is int, timeoutInMinutes, 'timeout_in_minutes', 'integer');
} }
final List<dynamic> capabilities = _validateAndParseCapabilities(taskName, taskYaml['required_agent_capabilities']); final List<dynamic> capabilities = _validateAndParseCapabilities(taskName as String, taskYaml['required_agent_capabilities']);
return ManifestTask._( return ManifestTask._(
name: taskName, name: taskName as String,
description: taskYaml['description'], description: taskYaml['description'] as String,
stage: taskYaml['stage'], stage: taskYaml['stage'] as String,
requiredAgentCapabilities: capabilities, requiredAgentCapabilities: capabilities as List<String>,
isFlaky: isFlaky ?? false, isFlaky: isFlaky as bool ?? false,
timeoutInMinutes: timeoutInMinutes, timeoutInMinutes: timeoutInMinutes as int,
); );
} }
List<String> _validateAndParseCapabilities(String taskName, dynamic capabilitiesYaml) { List<String> _validateAndParseCapabilities(String taskName, dynamic capabilitiesYaml) {
_checkType(capabilitiesYaml is List, capabilitiesYaml, 'required_agent_capabilities', 'list'); _checkType(capabilitiesYaml is List, capabilitiesYaml, 'required_agent_capabilities', 'list');
for (int i = 0; i < capabilitiesYaml.length; i++) { for (int i = 0; i < (capabilitiesYaml as List<dynamic>).length; i++) {
final dynamic capability = capabilitiesYaml[i]; final dynamic capability = capabilitiesYaml[i];
_checkType(capability is String, capability, 'required_agent_capabilities[$i]', 'string'); _checkType(capability is String, capability, 'required_agent_capabilities[$i]', 'string');
} }
return capabilitiesYaml.cast<String>(); return (capabilitiesYaml as List<dynamic>).cast<String>();
} }
void _checkType(bool isValid, dynamic value, String variableName, String typeName) { void _checkType(bool isValid, dynamic value, String variableName, String typeName) {
...@@ -154,13 +154,13 @@ void _checkType(bool isValid, dynamic value, String variableName, String typeNam ...@@ -154,13 +154,13 @@ void _checkType(bool isValid, dynamic value, String variableName, String typeNam
} }
void _checkIsNotBlank(dynamic value, String variableName, String ownerName) { void _checkIsNotBlank(dynamic value, String variableName, String ownerName) {
if (value == null || value.isEmpty) { if (value == null || value is String && value.isEmpty || value is List<dynamic> && value.isEmpty) {
throw ManifestError('$variableName must not be empty in $ownerName.'); throw ManifestError('$variableName must not be empty in $ownerName.');
} }
} }
void _checkKeys(Map<dynamic, dynamic> map, String variableName, List<String> allowedKeys) { void _checkKeys(Map<dynamic, dynamic> map, String variableName, List<String> allowedKeys) {
for (String key in map.keys) { for (String key in map.keys.cast<String>()) {
if (!allowedKeys.contains(key)) { if (!allowedKeys.contains(key)) {
throw ManifestError( throw ManifestError(
'Unrecognized property "$key" in $variableName. ' 'Unrecognized property "$key" in $variableName. '
......
...@@ -69,7 +69,7 @@ Future<Map<String, dynamic>> runTask( ...@@ -69,7 +69,7 @@ Future<Map<String, dynamic>> runTask(
try { try {
final VMIsolateRef isolate = await _connectToRunnerIsolate(await uri.future); final VMIsolateRef isolate = await _connectToRunnerIsolate(await uri.future);
final Map<String, dynamic> taskResult = await isolate.invokeExtension('ext.cocoonRunTask'); final Map<String, dynamic> taskResult = await isolate.invokeExtension('ext.cocoonRunTask') as Map<String, dynamic>;
await runner.exitCode; await runner.exitCode;
return taskResult; return taskResult;
} finally { } finally {
...@@ -100,7 +100,7 @@ Future<VMIsolateRef> _connectToRunnerIsolate(Uri vmServiceUri) async { ...@@ -100,7 +100,7 @@ Future<VMIsolateRef> _connectToRunnerIsolate(Uri vmServiceUri) async {
final VMServiceClient client = VMServiceClient.connect(url); final VMServiceClient client = VMServiceClient.connect(url);
final VM vm = await client.getVM(); final VM vm = await client.getVM();
final VMIsolateRef isolate = vm.isolates.single; final VMIsolateRef isolate = vm.isolates.single;
final String response = await isolate.invokeExtension('ext.cocoonRunnerReady'); final String response = await isolate.invokeExtension('ext.cocoonRunnerReady') as String;
if (response != 'ready') if (response != 'ready')
throw 'not ready yet'; throw 'not ready yet';
return isolate; return isolate;
......
...@@ -100,7 +100,7 @@ Stream<RunningProcessInfo> windowsRunningProcesses(String processName) async* { ...@@ -100,7 +100,7 @@ Stream<RunningProcessInfo> windowsRunningProcesses(String processName) async* {
print(result.stdout); print(result.stdout);
return; return;
} }
for (RunningProcessInfo info in processPowershellOutput(result.stdout)) { for (RunningProcessInfo info in processPowershellOutput(result.stdout as String)) {
yield info; yield info;
} }
} }
...@@ -191,7 +191,7 @@ Stream<RunningProcessInfo> posixRunningProcesses( ...@@ -191,7 +191,7 @@ Stream<RunningProcessInfo> posixRunningProcesses(
print(result.stdout); print(result.stdout);
return; return;
} }
for (RunningProcessInfo info in processPsOutput(result.stdout, processName)) { for (RunningProcessInfo info in processPsOutput(result.stdout as String, processName)) {
yield info; yield info;
} }
} }
......
...@@ -186,7 +186,7 @@ void section(String title) { ...@@ -186,7 +186,7 @@ void section(String title) {
Future<String> getDartVersion() async { Future<String> getDartVersion() async {
// The Dart VM returns the version text to stderr. // The Dart VM returns the version text to stderr.
final ProcessResult result = _processManager.runSync(<String>[dartBin, '--version']); final ProcessResult result = _processManager.runSync(<String>[dartBin, '--version']);
String version = result.stderr.trim(); String version = (result.stderr as String).trim();
// Convert: // Convert:
// Dart VM version: 1.17.0-dev.2.0 (Tue May 3 12:14:52 2016) on "macos_x64" // Dart VM version: 1.17.0-dev.2.0 (Tue May 3 12:14:52 2016) on "macos_x64"
...@@ -465,7 +465,7 @@ String requireEnvVar(String name) { ...@@ -465,7 +465,7 @@ String requireEnvVar(String name) {
T requireConfigProperty<T>(Map<String, dynamic> map, String propertyName) { T requireConfigProperty<T>(Map<String, dynamic> map, String propertyName) {
if (!map.containsKey(propertyName)) if (!map.containsKey(propertyName))
fail('Configuration property not found: $propertyName'); fail('Configuration property not found: $propertyName');
final T result = map[propertyName]; final T result = map[propertyName] as T;
return result; return result;
} }
...@@ -571,7 +571,7 @@ String extractCloudAuthTokenArg(List<String> rawArgs) { ...@@ -571,7 +571,7 @@ String extractCloudAuthTokenArg(List<String> rawArgs) {
return null; return null;
} }
final String token = args['cloud-auth-token']; final String token = args['cloud-auth-token'] as String;
if (token == null) { if (token == null) {
stderr.writeln('Required option --cloud-auth-token not found'); stderr.writeln('Required option --cloud-auth-token not found');
return null; return null;
......
...@@ -46,16 +46,17 @@ class GalleryTransitionTest { ...@@ -46,16 +46,17 @@ class GalleryTransitionTest {
// Route paths contains slashes, which Firebase doesn't accept in keys, so we // Route paths contains slashes, which Firebase doesn't accept in keys, so we
// remove them. // remove them.
final Map<String, dynamic> original = Map<String, dynamic>.from( final Map<String, dynamic> original = json.decode(
json.decode( file('${galleryDirectory.path}/build/transition_durations.timeline.json').readAsStringSync(),
file('${galleryDirectory.path}/build/transition_durations.timeline.json').readAsStringSync() ) as Map<String, dynamic>;
));
final Map<String, List<int>> transitions = <String, List<int>>{}; final Map<String, List<int>> transitions = <String, List<int>>{};
for (String key in original.keys) { for (String key in original.keys) {
transitions[key.replaceAll('/', '')] = List<int>.from(original[key]); transitions[key.replaceAll('/', '')] = List<int>.from(original[key] as List<dynamic>);
} }
final Map<String, dynamic> summary = json.decode(file('${galleryDirectory.path}/build/transitions.timeline_summary.json').readAsStringSync()); final Map<String, dynamic> summary = json.decode(
file('${galleryDirectory.path}/build/transitions.timeline_summary.json').readAsStringSync(),
) as Map<String, dynamic>;
final Map<String, dynamic> data = <String, dynamic>{ final Map<String, dynamic> data = <String, dynamic>{
'transitions': transitions, 'transitions': transitions,
......
...@@ -90,7 +90,7 @@ TaskFunction createHotModeTest({String deviceIdOverride, Map<String, String> env ...@@ -90,7 +90,7 @@ TaskFunction createHotModeTest({String deviceIdOverride, Map<String, String> env
<Future<void>>[stdoutDone.future, stderrDone.future]); <Future<void>>[stdoutDone.future, stderrDone.future]);
await process.exitCode; await process.exitCode;
twoReloadsData = json.decode(benchmarkFile.readAsStringSync()); twoReloadsData = json.decode(benchmarkFile.readAsStringSync()) as Map<String, dynamic>;
} }
benchmarkFile.deleteSync(); benchmarkFile.deleteSync();
...@@ -129,7 +129,7 @@ TaskFunction createHotModeTest({String deviceIdOverride, Map<String, String> env ...@@ -129,7 +129,7 @@ TaskFunction createHotModeTest({String deviceIdOverride, Map<String, String> env
await process.exitCode; await process.exitCode;
freshRestartReloadsData = freshRestartReloadsData =
json.decode(benchmarkFile.readAsStringSync()); json.decode(benchmarkFile.readAsStringSync()) as Map<String, dynamic>;
} }
}); });
}); });
......
...@@ -128,7 +128,7 @@ Future<Map<String, double>> _readJsonResults(Process process) { ...@@ -128,7 +128,7 @@ Future<Map<String, double>> _readJsonResults(Process process) {
// Also send a kill signal in case the `q` above didn't work. // Also send a kill signal in case the `q` above didn't work.
process.kill(ProcessSignal.sigint); process.kill(ProcessSignal.sigint);
try { try {
completer.complete(Map<String, double>.from(json.decode(jsonOutput))); completer.complete(Map<String, double>.from(json.decode(jsonOutput) as Map<String, dynamic>));
} catch (ex) { } catch (ex) {
completer.completeError('Decoding JSON failed ($ex). JSON string was: $jsonOutput'); completer.completeError('Decoding JSON failed ($ex). JSON string was: $jsonOutput');
} }
......
...@@ -167,7 +167,9 @@ class StartupTest { ...@@ -167,7 +167,9 @@ class StartupTest {
'-d', '-d',
deviceId, deviceId,
]); ]);
final Map<String, dynamic> data = json.decode(file('$testDirectory/build/start_up_info.json').readAsStringSync()); final Map<String, dynamic> data = json.decode(
file('$testDirectory/build/start_up_info.json').readAsStringSync(),
) as Map<String, dynamic>;
if (!reportMetrics) if (!reportMetrics)
return TaskResult.success(data); return TaskResult.success(data);
...@@ -211,9 +213,11 @@ class PerfTest { ...@@ -211,9 +213,11 @@ class PerfTest {
'-d', '-d',
deviceId, deviceId,
]); ]);
final Map<String, dynamic> data = json.decode(file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync()); final Map<String, dynamic> data = json.decode(
file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync(),
) as Map<String, dynamic>;
if (data['frame_count'] < 5) { if (data['frame_count'] as int < 5) {
return TaskResult.failure( return TaskResult.failure(
'Timeline contains too few frames: ${data['frame_count']}. Possibly ' 'Timeline contains too few frames: ${data['frame_count']}. Possibly '
'trace events are not being captured.', 'trace events are not being captured.',
...@@ -308,8 +312,8 @@ class WebCompileTest { ...@@ -308,8 +312,8 @@ class WebCompileTest {
final ProcessResult result = await Process.run('du', <String>['-k', output]); final ProcessResult result = await Process.run('du', <String>['-k', output]);
await Process.run('gzip',<String>['-k', '9', output]); await Process.run('gzip',<String>['-k', '9', output]);
final ProcessResult resultGzip = await Process.run('du', <String>['-k', output + '.gz']); final ProcessResult resultGzip = await Process.run('du', <String>['-k', output + '.gz']);
metrics['${metric}_dart2js_size'] = _parseDu(result.stdout); metrics['${metric}_dart2js_size'] = _parseDu(result.stdout as String);
metrics['${metric}_dart2js_size_gzip'] = _parseDu(resultGzip.stdout); metrics['${metric}_dart2js_size_gzip'] = _parseDu(resultGzip.stdout as String);
} }
static int _parseDu(String source) { static int _parseDu(String source) {
...@@ -636,9 +640,9 @@ class MemoryTest { ...@@ -636,9 +640,9 @@ class MemoryTest {
assert(_startMemoryUsage != null); assert(_startMemoryUsage != null);
print('snapshotting memory usage...'); print('snapshotting memory usage...');
final Map<String, dynamic> endMemoryUsage = await device.getMemoryStats(package); final Map<String, dynamic> endMemoryUsage = await device.getMemoryStats(package);
_startMemory.add(_startMemoryUsage['total_kb']); _startMemory.add(_startMemoryUsage['total_kb'] as int);
_endMemory.add(endMemoryUsage['total_kb']); _endMemory.add(endMemoryUsage['total_kb'] as int);
_diffMemory.add(endMemoryUsage['total_kb'] - _startMemoryUsage['total_kb']); _diffMemory.add((endMemoryUsage['total_kb'] as int) - (_startMemoryUsage['total_kb'] as int));
} }
} }
......
...@@ -43,7 +43,7 @@ class Upload { ...@@ -43,7 +43,7 @@ class Upload {
if (retryCount == 0) if (retryCount == 0)
return const Duration(milliseconds: 1000); return const Duration(milliseconds: 1000);
random ??= math.Random(); random ??= math.Random();
return Duration(milliseconds: random.nextInt(1000) + math.pow(2, retryCount) * 1000); return Duration(milliseconds: random.nextInt(1000) + (math.pow(2, retryCount) as int) * 1000);
} }
Future<bool> save(HttpClient client, String name, List<int> content) async { Future<bool> save(HttpClient client, String name, List<int> content) async {
......
...@@ -138,11 +138,10 @@ class CommandArgs { ...@@ -138,11 +138,10 @@ class CommandArgs {
bool operator==(Object other) { bool operator==(Object other) {
if (other.runtimeType != CommandArgs) if (other.runtimeType != CommandArgs)
return false; return false;
return other is CommandArgs
final CommandArgs otherCmd = other; && other.command == command
return otherCmd.command == command && && const ListEquality<String>().equals(other.arguments, arguments)
const ListEquality<String>().equals(otherCmd.arguments, arguments) && && const MapEquality<String, String>().equals(other.environment, environment);
const MapEquality<String, String>().equals(otherCmd.environment, environment);
} }
@override @override
......
...@@ -52,19 +52,19 @@ class AndroidSemanticsNode { ...@@ -52,19 +52,19 @@ class AndroidSemanticsNode {
/// ] /// ]
/// } /// }
factory AndroidSemanticsNode.deserialize(String value) { factory AndroidSemanticsNode.deserialize(String value) {
return AndroidSemanticsNode._(json.decode(value)); return AndroidSemanticsNode._(json.decode(value) as Map<String, Object>);
} }
final Map<String, Object> _values; final Map<String, Object> _values;
final List<AndroidSemanticsNode> _children = <AndroidSemanticsNode>[]; final List<AndroidSemanticsNode> _children = <AndroidSemanticsNode>[];
Map<String, Object> get _flags => _values['flags']; Map<String, Object> get _flags => _values['flags'] as Map<String, Object>;
/// The text value of the semantics node. /// The text value of the semantics node.
/// ///
/// This is produced by combining the value, label, and hint fields from /// This is produced by combining the value, label, and hint fields from
/// the Flutter [SemanticsNode]. /// the Flutter [SemanticsNode].
String get text => _values['text']; String get text => _values['text'] as String;
/// The contentDescription of the semantics node. /// The contentDescription of the semantics node.
/// ///
...@@ -74,7 +74,7 @@ class AndroidSemanticsNode { ...@@ -74,7 +74,7 @@ class AndroidSemanticsNode {
/// ///
/// This is produced by combining the value, label, and hint fields from /// This is produced by combining the value, label, and hint fields from
/// the Flutter [SemanticsNode]. /// the Flutter [SemanticsNode].
String get contentDescription => _values['contentDescription']; String get contentDescription => _values['contentDescription'] as String;
/// The className of the semantics node. /// The className of the semantics node.
/// ///
...@@ -83,10 +83,10 @@ class AndroidSemanticsNode { ...@@ -83,10 +83,10 @@ class AndroidSemanticsNode {
/// ///
/// If a more specific value isn't provided, it defaults to /// If a more specific value isn't provided, it defaults to
/// "android.view.View". /// "android.view.View".
String get className => _values['className']; String get className => _values['className'] as String;
/// The identifier for this semantics node. /// The identifier for this semantics node.
int get id => _values['id']; int get id => _values['id'] as int;
/// The children of this semantics node. /// The children of this semantics node.
List<AndroidSemanticsNode> get children => _children; List<AndroidSemanticsNode> get children => _children;
...@@ -94,44 +94,44 @@ class AndroidSemanticsNode { ...@@ -94,44 +94,44 @@ class AndroidSemanticsNode {
/// Whether the node is currently in a checked state. /// Whether the node is currently in a checked state.
/// ///
/// Equivalent to [SemanticsFlag.isChecked]. /// Equivalent to [SemanticsFlag.isChecked].
bool get isChecked => _flags['isChecked']; bool get isChecked => _flags['isChecked'] as bool;
/// Whether the node can be in a checked state. /// Whether the node can be in a checked state.
/// ///
/// Equivalent to [SemanticsFlag.hasCheckedState] /// Equivalent to [SemanticsFlag.hasCheckedState]
bool get isCheckable => _flags['isCheckable']; bool get isCheckable => _flags['isCheckable'] as bool;
/// Whether the node is editable. /// Whether the node is editable.
/// ///
/// This is usually only applied to text fields, which map /// This is usually only applied to text fields, which map
/// to "android.widget.EditText". /// to "android.widget.EditText".
bool get isEditable => _flags['isEditable']; bool get isEditable => _flags['isEditable'] as bool;
/// Whether the node is enabled. /// Whether the node is enabled.
bool get isEnabled => _flags['isEnabled']; bool get isEnabled => _flags['isEnabled'] as bool;
/// Whether the node is focusable. /// Whether the node is focusable.
bool get isFocusable => _flags['isFocusable']; bool get isFocusable => _flags['isFocusable'] as bool;
/// Whether the node is focused. /// Whether the node is focused.
bool get isFocused => _flags['isFocused']; bool get isFocused => _flags['isFocused'] as bool;
/// Whether the node is considered a heading. /// Whether the node is considered a heading.
bool get isHeading => _flags['isHeading']; bool get isHeading => _flags['isHeading'] as bool;
/// Whether the node represents a password field. /// Whether the node represents a password field.
/// ///
/// Equivalent to [SemanticsFlag.isObscured]. /// Equivalent to [SemanticsFlag.isObscured].
bool get isPassword => _flags['isPassword']; bool get isPassword => _flags['isPassword'] as bool;
/// Whether the node is long clickable. /// Whether the node is long clickable.
/// ///
/// Equivalent to having [SemanticsAction.longPress]. /// Equivalent to having [SemanticsAction.longPress].
bool get isLongClickable => _flags['isLongClickable']; bool get isLongClickable => _flags['isLongClickable'] as bool;
/// Gets a [Rect] which defines the position and size of the semantics node. /// Gets a [Rect] which defines the position and size of the semantics node.
Rect getRect() { Rect getRect() {
final Map<String, Object> rawRect = _values['rect']; final Map<String, Object> rawRect = _values['rect'] as Map<String, Object>;
final Map<String, int> rect = rawRect.cast<String, int>(); final Map<String, int> rect = rawRect.cast<String, int>();
return Rect.fromLTRB( return Rect.fromLTRB(
rect['left'].toDouble(), rect['left'].toDouble(),
...@@ -149,7 +149,7 @@ class AndroidSemanticsNode { ...@@ -149,7 +149,7 @@ class AndroidSemanticsNode {
/// Gets a list of [AndroidSemanticsActions] which are defined for the node. /// Gets a list of [AndroidSemanticsActions] which are defined for the node.
List<AndroidSemanticsAction> getActions() => <AndroidSemanticsAction>[ List<AndroidSemanticsAction> getActions() => <AndroidSemanticsAction>[
for (int id in _values['actions']) AndroidSemanticsAction.deserialize(id), for (int id in (_values['actions'] as List<dynamic>).cast<int>()) AndroidSemanticsAction.deserialize(id),
]; ];
@override @override
...@@ -189,11 +189,11 @@ class Rect { ...@@ -189,11 +189,11 @@ class Rect {
bool operator ==(Object other) { bool operator ==(Object other) {
if (other.runtimeType != runtimeType) if (other.runtimeType != runtimeType)
return false; return false;
final Rect typedOther = other; return other is Rect
return typedOther.top == top && && other.top == top
typedOther.left == left && && other.left == left
typedOther.right == right && && other.right == right
typedOther.bottom == bottom; && other.bottom == bottom;
} }
@override @override
...@@ -221,8 +221,9 @@ class Size { ...@@ -221,8 +221,9 @@ class Size {
bool operator ==(Object other) { bool operator ==(Object other) {
if (other.runtimeType != runtimeType) if (other.runtimeType != runtimeType)
return false; return false;
final Size typedOther = other; return other is Size
return typedOther.width == width && typedOther.height == height; && other.width == width
&& other.height == height;
} }
@override @override
......
...@@ -196,8 +196,8 @@ class AndroidSemanticsAction { ...@@ -196,8 +196,8 @@ class AndroidSemanticsAction {
bool operator ==(Object other) { bool operator ==(Object other) {
if (other.runtimeType != runtimeType) if (other.runtimeType != runtimeType)
return false; return false;
final AndroidSemanticsAction typedOther = other; return other is AndroidSemanticsAction
return id == typedOther.id; && other.id == id;
} }
/// Creates a new [AndroidSemanticsAction] from an integer `value`. /// Creates a new [AndroidSemanticsAction] from an integer `value`.
......
...@@ -177,7 +177,7 @@ class _AndroidSemanticsMatcher extends Matcher { ...@@ -177,7 +177,7 @@ class _AndroidSemanticsMatcher extends Matcher {
@override @override
Description describeMismatch(Object item, Description mismatchDescription, Description describeMismatch(Object item, Description mismatchDescription,
Map<Object, Object> matchState, bool verbose) { Map<Object, Object> matchState, bool verbose) {
return mismatchDescription.add(matchState['failure']); return mismatchDescription.add(matchState['failure'] as String);
} }
bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) { bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) {
......
...@@ -47,8 +47,8 @@ Future<void> _waitForSplashToDisappear(FlutterDriver driver) async { ...@@ -47,8 +47,8 @@ Future<void> _waitForSplashToDisappear(FlutterDriver driver) async {
while (waitingForSplashToDisappear) { while (waitingForSplashToDisappear) {
final String response = await driver.requestData('splash_test_log',); final String response = await driver.requestData('splash_test_log',);
final Map<String, dynamic> splashTestLog = jsonDecode(response); final Map<String, dynamic> splashTestLog = jsonDecode(response) as Map<String, dynamic>;
final List<dynamic> events = splashTestLog['events']; final List<dynamic> events = splashTestLog['events'] as List<dynamic>;
if (events.length == 3) { if (events.length == 3) {
expect( expect(
events[0], events[0],
......
...@@ -40,12 +40,12 @@ String diffMotionEvents( ...@@ -40,12 +40,12 @@ String diffMotionEvents(
void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent) { Map<String, dynamic> synthesizedEvent) {
final int synthesizedActionMasked = final int synthesizedActionMasked =
getActionMasked(synthesizedEvent['action']); getActionMasked(synthesizedEvent['action'] as int);
final int originalActionMasked = getActionMasked(originalEvent['action']); final int originalActionMasked = getActionMasked(originalEvent['action'] as int);
final String synthesizedActionName = final String synthesizedActionName =
getActionName(synthesizedActionMasked, synthesizedEvent['action']); getActionName(synthesizedActionMasked, synthesizedEvent['action'] as int);
final String originalActionName = final String originalActionName =
getActionName(originalActionMasked, originalEvent['action']); getActionName(originalActionMasked, originalEvent['action'] as int);
if (synthesizedActionMasked != originalActionMasked) if (synthesizedActionMasked != originalActionMasked)
diffBuffer.write( diffBuffer.write(
...@@ -53,8 +53,8 @@ void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, ...@@ -53,8 +53,8 @@ void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent,
if (kPointerActions.contains(originalActionMasked) && if (kPointerActions.contains(originalActionMasked) &&
originalActionMasked == synthesizedActionMasked) { originalActionMasked == synthesizedActionMasked) {
final int originalPointer = getPointerIdx(originalEvent['action']); final int originalPointer = getPointerIdx(originalEvent['action'] as int);
final int synthesizedPointer = getPointerIdx(synthesizedEvent['action']); final int synthesizedPointer = getPointerIdx(synthesizedEvent['action'] as int);
if (originalPointer != synthesizedPointer) if (originalPointer != synthesizedPointer)
diffBuffer.write( diffBuffer.write(
'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName '); 'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName ');
...@@ -64,9 +64,9 @@ void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent, ...@@ -64,9 +64,9 @@ void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent,
void diffPointerProperties(StringBuffer diffBuffer, void diffPointerProperties(StringBuffer diffBuffer,
Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) { Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) {
final List<Map<dynamic, dynamic>> expectedList = final List<Map<dynamic, dynamic>> expectedList =
originalEvent['pointerProperties'].cast<Map<dynamic, dynamic>>(); (originalEvent['pointerProperties'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
final List<Map<dynamic, dynamic>> actualList = final List<Map<dynamic, dynamic>> actualList =
synthesizedEvent['pointerProperties'].cast<Map<dynamic, dynamic>>(); (synthesizedEvent['pointerProperties'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
if (expectedList.length != actualList.length) { if (expectedList.length != actualList.length) {
diffBuffer.write( diffBuffer.write(
...@@ -86,9 +86,9 @@ void diffPointerProperties(StringBuffer diffBuffer, ...@@ -86,9 +86,9 @@ void diffPointerProperties(StringBuffer diffBuffer,
void diffPointerCoordsList(StringBuffer diffBuffer, void diffPointerCoordsList(StringBuffer diffBuffer,
Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) { Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) {
final List<Map<dynamic, dynamic>> expectedList = final List<Map<dynamic, dynamic>> expectedList =
originalEvent['pointerCoords'].cast<Map<dynamic, dynamic>>(); (originalEvent['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
final List<Map<dynamic, dynamic>> actualList = final List<Map<dynamic, dynamic>> actualList =
synthesizedEvent['pointerCoords'].cast<Map<dynamic, dynamic>>(); (synthesizedEvent['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
if (expectedList.length != actualList.length) { if (expectedList.length != actualList.length) {
diffBuffer.write( diffBuffer.write(
......
...@@ -115,7 +115,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> { ...@@ -115,7 +115,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
const StandardMessageCodec codec = StandardMessageCodec(); const StandardMessageCodec codec = StandardMessageCodec();
try { try {
final ByteData data = await rootBundle.load('packages/assets_for_android_views/assets/touchEvents'); final ByteData data = await rootBundle.load('packages/assets_for_android_views/assets/touchEvents');
final List<dynamic> unTypedRecordedEvents = codec.decodeMessage(data); final List<dynamic> unTypedRecordedEvents = codec.decodeMessage(data) as List<dynamic>;
final List<Map<String, dynamic>> recordedEvents = unTypedRecordedEvents final List<Map<String, dynamic>> recordedEvents = unTypedRecordedEvents
.cast<Map<dynamic, dynamic>>() .cast<Map<dynamic, dynamic>>()
.map<Map<String, dynamic>>((Map<dynamic, dynamic> e) =>e.cast<String, dynamic>()) .map<Map<String, dynamic>>((Map<dynamic, dynamic> e) =>e.cast<String, dynamic>())
...@@ -204,7 +204,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> { ...@@ -204,7 +204,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
Future<dynamic> onMethodChannelCall(MethodCall call) { Future<dynamic> onMethodChannelCall(MethodCall call) {
switch (call.method) { switch (call.method) {
case 'onTouch': case 'onTouch':
final Map<dynamic, dynamic> map = call.arguments; final Map<dynamic, dynamic> map = call.arguments as Map<dynamic, dynamic>;
flutterViewEvents.insert(0, map.cast<String, dynamic>()); flutterViewEvents.insert(0, map.cast<String, dynamic>());
if (flutterViewEvents.length > kEventsBufferSize) if (flutterViewEvents.length > kEventsBufferSize)
flutterViewEvents.removeLast(); flutterViewEvents.removeLast();
...@@ -217,7 +217,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> { ...@@ -217,7 +217,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
Future<dynamic> onViewMethodChannelCall(MethodCall call) { Future<dynamic> onViewMethodChannelCall(MethodCall call) {
switch (call.method) { switch (call.method) {
case 'onTouch': case 'onTouch':
final Map<dynamic, dynamic> map = call.arguments; final Map<dynamic, dynamic> map = call.arguments as Map<dynamic, dynamic>;
embeddedViewEvents.insert(0, map.cast<String, dynamic>()); embeddedViewEvents.insert(0, map.cast<String, dynamic>());
if (embeddedViewEvents.length > kEventsBufferSize) if (embeddedViewEvents.length > kEventsBufferSize)
embeddedViewEvents.removeLast(); embeddedViewEvents.removeLast();
...@@ -248,7 +248,7 @@ class TouchEventDiff extends StatelessWidget { ...@@ -248,7 +248,7 @@ class TouchEventDiff extends StatelessWidget {
Color color; Color color;
final String diff = diffMotionEvents(originalEvent, synthesizedEvent); final String diff = diffMotionEvents(originalEvent, synthesizedEvent);
String msg; String msg;
final int action = synthesizedEvent['action']; final int action = synthesizedEvent['action'] as int;
final String actionName = getActionName(getActionMasked(action), action); final String actionName = getActionName(getActionMasked(action), action);
if (diff.isEmpty) { if (diff.isEmpty) {
color = Colors.green; color = Colors.green;
...@@ -274,7 +274,7 @@ class TouchEventDiff extends StatelessWidget { ...@@ -274,7 +274,7 @@ class TouchEventDiff extends StatelessWidget {
void prettyPrintEvent(Map<String, dynamic> event) { void prettyPrintEvent(Map<String, dynamic> event) {
final StringBuffer buffer = StringBuffer(); final StringBuffer buffer = StringBuffer();
final int action = event['action']; final int action = event['action'] as int;
final int maskedAction = getActionMasked(action); final int maskedAction = getActionMasked(action);
final String actionName = getActionName(maskedAction, action); final String actionName = getActionName(maskedAction, action);
...@@ -283,7 +283,7 @@ class TouchEventDiff extends StatelessWidget { ...@@ -283,7 +283,7 @@ class TouchEventDiff extends StatelessWidget {
buffer.write('pointer: ${getPointerIdx(action)} '); buffer.write('pointer: ${getPointerIdx(action)} ');
} }
final List<Map<dynamic, dynamic>> coords = event['pointerCoords'].cast<Map<dynamic, dynamic>>(); final List<Map<dynamic, dynamic>> coords = (event['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
for (int i = 0; i < coords.length; i++) { for (int i = 0; i < coords.length; i++) {
buffer.write('p$i x: ${coords[i]['x']} y: ${coords[i]['y']}, pressure: ${coords[i]['pressure']} '); buffer.write('p$i x: ${coords[i]['x']} y: ${coords[i]['y']}, pressure: ${coords[i]['pressure']} ');
} }
......
...@@ -46,7 +46,7 @@ class TestStepResult { ...@@ -46,7 +46,7 @@ class TestStepResult {
if (snapshot.hasData) { if (snapshot.hasData) {
return snapshot.data; return snapshot.data;
} else { } else {
final TestStepResult result = snapshot.error; final TestStepResult result = snapshot.error as TestStepResult;
return result; return result;
} }
break; break;
......
...@@ -45,6 +45,6 @@ class _ExampleWidgetState extends State<ExampleWidget> { ...@@ -45,6 +45,6 @@ class _ExampleWidgetState extends State<ExampleWidget> {
class GeneratedWidget extends StatelessWidget { class GeneratedWidget extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Text(generated.message); return Text(generated.message as String);
} }
} }
...@@ -12,7 +12,7 @@ class _MarqueeText extends AnimatedWidget { ...@@ -12,7 +12,7 @@ class _MarqueeText extends AnimatedWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Animation<double> animation = listenable; final Animation<double> animation = listenable as Animation<double>;
return Container( return Container(
margin: EdgeInsets.only(left: animation.value), margin: EdgeInsets.only(left: animation.value),
child: const Text( child: const Text(
......
...@@ -25,7 +25,7 @@ class TestStepResult { ...@@ -25,7 +25,7 @@ class TestStepResult {
if (snapshot.hasData) { if (snapshot.hasData) {
return snapshot.data; return snapshot.data;
} else { } else {
final TestStepResult result = snapshot.error; final TestStepResult result = snapshot.error as TestStepResult;
return result; return result;
} }
break; break;
......
...@@ -166,7 +166,7 @@ class UndoIntent extends Intent { ...@@ -166,7 +166,7 @@ class UndoIntent extends Intent {
@override @override
bool isEnabled(BuildContext context) { bool isEnabled(BuildContext context) {
final UndoableActionDispatcher manager = Actions.of(context, nullOk: true); final UndoableActionDispatcher manager = Actions.of(context, nullOk: true) as UndoableActionDispatcher;
return manager.canUndo; return manager.canUndo;
} }
} }
...@@ -176,7 +176,7 @@ class RedoIntent extends Intent { ...@@ -176,7 +176,7 @@ class RedoIntent extends Intent {
@override @override
bool isEnabled(BuildContext context) { bool isEnabled(BuildContext context) {
final UndoableActionDispatcher manager = Actions.of(context, nullOk: true); final UndoableActionDispatcher manager = Actions.of(context, nullOk: true) as UndoableActionDispatcher;
return manager.canRedo; return manager.canRedo;
} }
} }
...@@ -189,7 +189,7 @@ final Action kUndoAction = CallbackAction( ...@@ -189,7 +189,7 @@ final Action kUndoAction = CallbackAction(
if (node?.context == null) { if (node?.context == null) {
return; return;
} }
final UndoableActionDispatcher manager = Actions.of(node.context, nullOk: true); final UndoableActionDispatcher manager = Actions.of(node.context, nullOk: true) as UndoableActionDispatcher;
manager?.undo(); manager?.undo();
}, },
); );
...@@ -202,7 +202,7 @@ final Action kRedoAction = CallbackAction( ...@@ -202,7 +202,7 @@ final Action kRedoAction = CallbackAction(
if (node?.context == null) { if (node?.context == null) {
return; return;
} }
final UndoableActionDispatcher manager = Actions.of(node.context, nullOk: true); final UndoableActionDispatcher manager = Actions.of(node.context, nullOk: true) as UndoableActionDispatcher;
manager?.redo(); manager?.redo();
}, },
); );
......
...@@ -231,7 +231,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -231,7 +231,7 @@ class CardCollectionState extends State<CardCollection> {
); );
} }
Widget _buildAppBar(BuildContext context) { AppBar _buildAppBar(BuildContext context) {
return AppBar( return AppBar(
actions: <Widget>[ actions: <Widget>[
Text(_dismissDirectionText(_dismissDirection)), Text(_dismissDirectionText(_dismissDirection)),
......
...@@ -139,7 +139,7 @@ class _PointDemoState extends State<_PointDemo> { ...@@ -139,7 +139,7 @@ class _PointDemoState extends State<_PointDemo> {
if (_dragTarget != null) if (_dragTarget != null)
return _IgnoreDrag(); return _IgnoreDrag();
final RenderBox box = _painterKey.currentContext.findRenderObject(); final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
final double startOffset = (box.localToGlobal(_begin) - position).distanceSquared; final double startOffset = (box.localToGlobal(_begin) - position).distanceSquared;
final double endOffset = (box.localToGlobal(_end) - position).distanceSquared; final double endOffset = (box.localToGlobal(_end) - position).distanceSquared;
setState(() { setState(() {
...@@ -307,7 +307,7 @@ class _RectangleDemoState extends State<_RectangleDemo> { ...@@ -307,7 +307,7 @@ class _RectangleDemoState extends State<_RectangleDemo> {
if (_dragTarget != null) if (_dragTarget != null)
return _IgnoreDrag(); return _IgnoreDrag();
final RenderBox box = _painterKey.currentContext.findRenderObject(); final RenderBox box = _painterKey.currentContext.findRenderObject() as RenderBox;
final double startOffset = (box.localToGlobal(_begin.center) - position).distanceSquared; final double startOffset = (box.localToGlobal(_begin.center) - position).distanceSquared;
final double endOffset = (box.localToGlobal(_end.center) - position).distanceSquared; final double endOffset = (box.localToGlobal(_end.center) - position).distanceSquared;
setState(() { setState(() {
......
...@@ -171,7 +171,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> { ...@@ -171,7 +171,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
void handleTapUp(GlobalKey target, Offset globalPosition) { void handleTapUp(GlobalKey target, Offset globalPosition) {
setState(() { setState(() {
markers[MarkerType.touch] = globalPosition; markers[MarkerType.touch] = globalPosition;
final RenderBox box = target.currentContext.findRenderObject(); final RenderBox box = target.currentContext.findRenderObject() as RenderBox;
markers[MarkerType.topLeft] = box.localToGlobal(const Offset(0.0, 0.0)); markers[MarkerType.topLeft] = box.localToGlobal(const Offset(0.0, 0.0));
final Size size = box.size; final Size size = box.size;
markers[MarkerType.bottomRight] = box.localToGlobal(Offset(size.width, size.height)); markers[MarkerType.bottomRight] = box.localToGlobal(Offset(size.width, size.height));
......
...@@ -111,7 +111,7 @@ class PageViewAppState extends State<PageViewApp> { ...@@ -111,7 +111,7 @@ class PageViewAppState extends State<PageViewApp> {
); );
} }
Widget _buildAppBar() { AppBar _buildAppBar() {
return AppBar( return AppBar(
title: const Text('PageView'), title: const Text('PageView'),
actions: <Widget>[ actions: <Widget>[
......
...@@ -156,7 +156,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin { ...@@ -156,7 +156,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
return TextSpan( return TextSpan(
text: _fiddleWithText(node.text), text: _fiddleWithText(node.text),
style: _fiddleWithStyle(node.style), style: _fiddleWithStyle(node.style),
children: _fiddleWithChildren(node.children?.map((InlineSpan child) => _fiddleWith(child))?.toList() ?? <InlineSpan>[]), children: _fiddleWithChildren(node.children?.map((InlineSpan child) => _fiddleWith(child as TextSpan))?.toList() ?? <TextSpan>[]),
); );
} }
...@@ -343,7 +343,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin { ...@@ -343,7 +343,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
if (node.children == null || node.children.isEmpty) if (node.children == null || node.children.isEmpty)
return 0; return 0;
int result = 0; int result = 0;
for (TextSpan child in node.children) for (TextSpan child in node.children.cast<TextSpan>())
result = math.max(result, depthOf(child)); result = math.max(result, depthOf(child));
return result; return result;
} }
......
...@@ -21,10 +21,10 @@ MockHttpClient createMockImageHttpClient(SecurityContext _) { ...@@ -21,10 +21,10 @@ MockHttpClient createMockImageHttpClient(SecurityContext _) {
when(response.contentLength).thenReturn(kTransparentImage.length); when(response.contentLength).thenReturn(kTransparentImage.length);
when(response.statusCode).thenReturn(HttpStatus.ok); when(response.statusCode).thenReturn(HttpStatus.ok);
when(response.listen(any)).thenAnswer((Invocation invocation) { when(response.listen(any)).thenAnswer((Invocation invocation) {
final void Function(List<int>) onData = invocation.positionalArguments[0]; final void Function(List<int>) onData = invocation.positionalArguments[0] as void Function(List<int>);
final void Function() onDone = invocation.namedArguments[#onDone]; final void Function() onDone = invocation.namedArguments[#onDone] as void Function();
final void Function(Object, [StackTrace]) onError = invocation.namedArguments[#onError]; final void Function(Object, [StackTrace]) onError = invocation.namedArguments[#onError] as void Function(Object, [StackTrace]);
final bool cancelOnError = invocation.namedArguments[#cancelOnError]; final bool cancelOnError = invocation.namedArguments[#cancelOnError] as bool;
return Stream<List<int>>.fromIterable(<List<int>>[kTransparentImage]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError); return Stream<List<int>>.fromIterable(<List<int>>[kTransparentImage]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError);
}); });
return client; return client;
......
...@@ -99,7 +99,7 @@ void main(List<String> argList) { ...@@ -99,7 +99,7 @@ void main(List<String> argList) {
final ArgResults args = parser.parse(argList); final ArgResults args = parser.parse(argList);
if (args[_kHelpOption]) { if (args[_kHelpOption] as bool) {
stderr.writeln(parser.usage); stderr.writeln(parser.usage);
exit(0); exit(0);
} }
...@@ -119,28 +119,30 @@ void main(List<String> argList) { ...@@ -119,28 +119,30 @@ void main(List<String> argList) {
'line, or in the INPUT environment variable.'); 'line, or in the INPUT environment variable.');
} }
final File input = File(args['input']); final File input = File(args['input'] as String);
if (!input.existsSync()) { if (!input.existsSync()) {
errorExit('The input file ${input.path} does not exist.'); errorExit('The input file ${input.path} does not exist.');
} }
String template; String template;
if (snippetType == SnippetType.application) { if (snippetType == SnippetType.application) {
if (args[_kTemplateOption] == null || args[_kTemplateOption].isEmpty) { final String templateArg = args[_kTemplateOption] as String;
if (templateArg == null || templateArg.isEmpty) {
stderr.writeln(parser.usage); stderr.writeln(parser.usage);
errorExit('The --$_kTemplateOption option must be specified on the command ' errorExit('The --$_kTemplateOption option must be specified on the command '
'line for application snippets.'); 'line for application snippets.');
} }
template = args[_kTemplateOption].toString().replaceAll(RegExp(r'.tmpl$'), ''); template = templateArg.replaceAll(RegExp(r'.tmpl$'), '');
} }
final String packageName = args[_kPackageOption] != null && args[_kPackageOption].isNotEmpty ? args[_kPackageOption] : null; String emptyToNull(String value) => value?.isEmpty ?? true ? null : value;
final String libraryName = args[_kLibraryOption] != null && args[_kLibraryOption].isNotEmpty ? args[_kLibraryOption] : null; final String packageName = emptyToNull(args[_kPackageOption] as String);
final String elementName = args[_kElementOption] != null && args[_kElementOption].isNotEmpty ? args[_kElementOption] : null; final String libraryName = emptyToNull(args[_kLibraryOption] as String);
final String serial = args[_kSerialOption] != null && args[_kSerialOption].isNotEmpty ? args[_kSerialOption] : null; final String elementName = emptyToNull(args[_kElementOption] as String);
final String serial = emptyToNull(args[_kSerialOption] as String);
final List<String> id = <String>[]; final List<String> id = <String>[];
if (args[_kOutputOption] != null) { if (args[_kOutputOption] != null) {
id.add(path.basename(path.basenameWithoutExtension(args[_kOutputOption]))); id.add(path.basename(path.basenameWithoutExtension(args[_kOutputOption] as String)));
} else { } else {
if (packageName != null && packageName != 'flutter') { if (packageName != null && packageName != 'flutter') {
id.add(packageName); id.add(packageName);
...@@ -165,9 +167,9 @@ void main(List<String> argList) { ...@@ -165,9 +167,9 @@ void main(List<String> argList) {
stdout.write(generator.generate( stdout.write(generator.generate(
input, input,
snippetType, snippetType,
showDartPad: args[_kShowDartPad], showDartPad: args[_kShowDartPad] as bool,
template: template, template: template,
output: args[_kOutputOption] != null ? File(args[_kOutputOption]) : null, output: args[_kOutputOption] != null ? File(args[_kOutputOption] as String) : null,
metadata: <String, Object>{ metadata: <String, Object>{
'sourcePath': environment['SOURCE_PATH'], 'sourcePath': environment['SOURCE_PATH'],
'sourceLine': environment['SOURCE_LINE'] != null 'sourceLine': environment['SOURCE_LINE'] != null
......
...@@ -129,8 +129,8 @@ class SnippetGenerator { ...@@ -129,8 +129,8 @@ class SnippetGenerator {
'code': htmlEscape.convert(result.join('\n')), 'code': htmlEscape.convert(result.join('\n')),
'language': language ?? 'dart', 'language': language ?? 'dart',
'serial': '', 'serial': '',
'id': metadata['id'], 'id': metadata['id'] as String,
'element': metadata['element'] ?? '', 'element': metadata['element'] as String ?? '',
'app': '', 'app': '',
}; };
if (type == SnippetType.application) { if (type == SnippetType.application) {
...@@ -253,7 +253,7 @@ class SnippetGenerator { ...@@ -253,7 +253,7 @@ class SnippetGenerator {
} }
snippetData.add(_ComponentTuple('app', app.split('\n'))); snippetData.add(_ComponentTuple('app', app.split('\n')));
final File outputFile = output ?? getOutputFile(metadata['id']); final File outputFile = output ?? getOutputFile(metadata['id'] as String);
stderr.writeln('Writing to ${outputFile.absolute.path}'); stderr.writeln('Writing to ${outputFile.absolute.path}');
outputFile.writeAsStringSync(app); outputFile.writeAsStringSync(app);
......
...@@ -191,7 +191,7 @@ void main() { ...@@ -191,7 +191,7 @@ void main() {
metadata: <String, Object>{'sourcePath': 'some/path.dart', 'id': 'id'}, metadata: <String, Object>{'sourcePath': 'some/path.dart', 'id': 'id'},
); );
expect(expectedMetadataFile.existsSync(), isTrue); expect(expectedMetadataFile.existsSync(), isTrue);
final Map<String, dynamic> json = jsonDecode(expectedMetadataFile.readAsStringSync()); final Map<String, dynamic> json = jsonDecode(expectedMetadataFile.readAsStringSync()) as Map<String, dynamic>;
expect(json['id'], equals('id')); expect(json['id'], equals('id'));
expect(json['file'], equals('snippet_out.dart')); expect(json['file'], equals('snippet_out.dart'));
expect(json['description'], equals('A description of the snippet.\n\nOn several lines.')); expect(json['description'], equals('A description of the snippet.\n\nOn several lines.'));
......
...@@ -31,7 +31,7 @@ const String kSnippetsRoot = 'dev/snippets'; ...@@ -31,7 +31,7 @@ const String kSnippetsRoot = 'dev/snippets';
Future<void> main(List<String> arguments) async { Future<void> main(List<String> arguments) async {
final ArgParser argParser = _createArgsParser(); final ArgParser argParser = _createArgsParser();
final ArgResults args = argParser.parse(arguments); final ArgResults args = argParser.parse(arguments);
if (args['help']) { if (args['help'] as bool) {
print ('Usage:'); print ('Usage:');
print (argParser.usage); print (argParser.usage);
exit(0); exit(0);
...@@ -111,7 +111,7 @@ Future<void> main(List<String> arguments) async { ...@@ -111,7 +111,7 @@ Future<void> main(List<String> arguments) async {
final List<String> dartdocBaseArgs = <String>[ final List<String> dartdocBaseArgs = <String>[
'global', 'global',
'run', 'run',
if (args['checked']) '-c', if (args['checked'] as bool) '-c',
'dartdoc', 'dartdoc',
]; ];
...@@ -130,8 +130,8 @@ Future<void> main(List<String> arguments) async { ...@@ -130,8 +130,8 @@ Future<void> main(List<String> arguments) async {
final List<String> dartdocArgs = <String>[ final List<String> dartdocArgs = <String>[
...dartdocBaseArgs, ...dartdocBaseArgs,
'--allow-tools', '--allow-tools',
if (args['json']) '--json', if (args['json'] as bool) '--json',
if (args['validate-links']) '--validate-links' else '--no-validate-links', if (args['validate-links'] as bool) '--validate-links' else '--no-validate-links',
'--link-to-source-excludes', '../../bin/cache', '--link-to-source-excludes', '../../bin/cache',
'--link-to-source-root', '../..', '--link-to-source-root', '../..',
'--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/master/%f%#L%l%', '--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/master/%f%#L%l%',
...@@ -207,14 +207,14 @@ Future<void> main(List<String> arguments) async { ...@@ -207,14 +207,14 @@ Future<void> main(List<String> arguments) async {
workingDirectory: kDocsRoot, workingDirectory: kDocsRoot,
environment: pubEnvironment, environment: pubEnvironment,
)); ));
printStream(process.stdout, prefix: args['json'] ? '' : 'dartdoc:stdout: ', printStream(process.stdout, prefix: args['json'] as bool ? '' : 'dartdoc:stdout: ',
filter: args['verbose'] ? const <Pattern>[] : <Pattern>[ filter: args['verbose'] as bool ? const <Pattern>[] : <Pattern>[
RegExp(r'^generating docs for library '), // unnecessary verbosity RegExp(r'^generating docs for library '), // unnecessary verbosity
RegExp(r'^pars'), // unnecessary verbosity RegExp(r'^pars'), // unnecessary verbosity
], ],
); );
printStream(process.stderr, prefix: args['json'] ? '' : 'dartdoc:stderr: ', printStream(process.stderr, prefix: args['json'] as bool ? '' : 'dartdoc:stderr: ',
filter: args['verbose'] ? const <Pattern>[] : <Pattern>[ filter: args['verbose'] as bool ? const <Pattern>[] : <Pattern>[
RegExp(r'^ warning: .+: \(.+/\.pub-cache/hosted/pub.dartlang.org/.+\)'), // packages outside our control RegExp(r'^ warning: .+: \(.+/\.pub-cache/hosted/pub.dartlang.org/.+\)'), // packages outside our control
], ],
); );
...@@ -252,7 +252,7 @@ String getBranchName() { ...@@ -252,7 +252,7 @@ String getBranchName() {
if (gitResult.exitCode != 0) if (gitResult.exitCode != 0)
throw 'git status exit with non-zero exit code: ${gitResult.exitCode}'; throw 'git status exit with non-zero exit code: ${gitResult.exitCode}';
final Match gitBranchMatch = gitBranchRegexp.firstMatch( final Match gitBranchMatch = gitBranchRegexp.firstMatch(
gitResult.stdout.trim().split('\n').first); (gitResult.stdout as String).trim().split('\n').first);
return gitBranchMatch == null ? '' : gitBranchMatch.group(1).split('...').first; return gitBranchMatch == null ? '' : gitBranchMatch.group(1).split('...').first;
} }
...@@ -262,7 +262,7 @@ String gitRevision() { ...@@ -262,7 +262,7 @@ String gitRevision() {
final ProcessResult gitResult = Process.runSync('git', <String>['rev-parse', 'HEAD']); final ProcessResult gitResult = Process.runSync('git', <String>['rev-parse', 'HEAD']);
if (gitResult.exitCode != 0) if (gitResult.exitCode != 0)
throw 'git rev-parse exit with non-zero exit code: ${gitResult.exitCode}'; throw 'git rev-parse exit with non-zero exit code: ${gitResult.exitCode}';
final String gitRevision = gitResult.stdout.trim(); final String gitRevision = (gitResult.stdout as String).trim();
return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision; return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision;
} }
...@@ -454,7 +454,7 @@ List<String> findPackageNames() { ...@@ -454,7 +454,7 @@ List<String> findPackageNames() {
} }
/// Finds all packages in the Flutter SDK /// Finds all packages in the Flutter SDK
List<FileSystemEntity> findPackages() { List<Directory> findPackages() {
return Directory('packages') return Directory('packages')
.listSync() .listSync()
.where((FileSystemEntity entity) { .where((FileSystemEntity entity) {
......
...@@ -132,61 +132,61 @@ Future<void> main(List<String> rawArguments) async { ...@@ -132,61 +132,61 @@ Future<void> main(List<String> rawArguments) async {
final ArgResults parsedArguments = argParser.parse(rawArguments); final ArgResults parsedArguments = argParser.parse(rawArguments);
if (parsedArguments['help']) { if (parsedArguments['help'] as bool) {
print(argParser.usage); print(argParser.usage);
exit(0); exit(0);
} }
KeyData data; KeyData data;
if (parsedArguments['collect']) { if (parsedArguments['collect'] as bool) {
String hidCodes; String hidCodes;
if (parsedArguments['chromium-hid-codes'] == null) { if (parsedArguments['chromium-hid-codes'] == null) {
hidCodes = await getChromiumConversions(); hidCodes = await getChromiumConversions();
} else { } else {
hidCodes = File(parsedArguments['chromium-hid-codes']).readAsStringSync(); hidCodes = File(parsedArguments['chromium-hid-codes'] as String).readAsStringSync();
} }
final String supplementalHidCodes = File(parsedArguments['supplemental-hid-codes']).readAsStringSync(); final String supplementalHidCodes = File(parsedArguments['supplemental-hid-codes'] as String).readAsStringSync();
hidCodes = '$hidCodes\n$supplementalHidCodes'; hidCodes = '$hidCodes\n$supplementalHidCodes';
String androidKeyCodes; String androidKeyCodes;
if (parsedArguments['android-keycodes'] == null) { if (parsedArguments['android-keycodes'] == null) {
androidKeyCodes = await getAndroidKeyCodes(); androidKeyCodes = await getAndroidKeyCodes();
} else { } else {
androidKeyCodes = File(parsedArguments['android-keycodes']).readAsStringSync(); androidKeyCodes = File(parsedArguments['android-keycodes'] as String).readAsStringSync();
} }
String androidScanCodes; String androidScanCodes;
if (parsedArguments['android-scancodes'] == null) { if (parsedArguments['android-scancodes'] == null) {
androidScanCodes = await getAndroidScanCodes(); androidScanCodes = await getAndroidScanCodes();
} else { } else {
androidScanCodes = File(parsedArguments['android-scancodes']).readAsStringSync(); androidScanCodes = File(parsedArguments['android-scancodes'] as String).readAsStringSync();
} }
String glfwKeyCodes; String glfwKeyCodes;
if (parsedArguments['glfw-keycodes'] == null) { if (parsedArguments['glfw-keycodes'] == null) {
glfwKeyCodes = await getGlfwKeyCodes(); glfwKeyCodes = await getGlfwKeyCodes();
} else { } else {
glfwKeyCodes = File(parsedArguments['glfw-keycodes']).readAsStringSync(); glfwKeyCodes = File(parsedArguments['glfw-keycodes'] as String).readAsStringSync();
} }
final String glfwToDomKey = File(parsedArguments['glfw-domkey']).readAsStringSync(); final String glfwToDomKey = File(parsedArguments['glfw-domkey'] as String).readAsStringSync();
final String androidToDomKey = File(parsedArguments['android-domkey']).readAsStringSync(); final String androidToDomKey = File(parsedArguments['android-domkey'] as String).readAsStringSync();
data = KeyData(hidCodes, androidScanCodes, androidKeyCodes, androidToDomKey, glfwKeyCodes, glfwToDomKey); data = KeyData(hidCodes, androidScanCodes, androidKeyCodes, androidToDomKey, glfwKeyCodes, glfwToDomKey);
const JsonEncoder encoder = JsonEncoder.withIndent(' '); const JsonEncoder encoder = JsonEncoder.withIndent(' ');
File(parsedArguments['data']).writeAsStringSync(encoder.convert(data.toJson())); File(parsedArguments['data'] as String).writeAsStringSync(encoder.convert(data.toJson()));
} else { } else {
data = KeyData.fromJson(json.decode(await File(parsedArguments['data']).readAsString())); data = KeyData.fromJson(json.decode(await File(parsedArguments['data'] as String).readAsString()) as Map<String, dynamic>);
} }
final File codeFile = File(parsedArguments['code']); final File codeFile = File(parsedArguments['code'] as String);
if (!codeFile.existsSync()) { if (!codeFile.existsSync()) {
codeFile.createSync(recursive: true); codeFile.createSync(recursive: true);
} }
final File mapsFile = File(parsedArguments['maps']); final File mapsFile = File(parsedArguments['maps'] as String);
if (!mapsFile.existsSync()) { if (!mapsFile.existsSync()) {
mapsFile.createSync(recursive: true); mapsFile.createSync(recursive: true);
} }
......
...@@ -87,7 +87,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK ...@@ -87,7 +87,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
// plane. // plane.
final Key entry = keyData.data.firstWhere((Key item) => item.name == Key.synonyms[name][0]); final Key entry = keyData.data.firstWhere((Key item) => item.name == Key.synonyms[name][0]);
final Set<String> unionNames = Key.synonyms[name].map<String>((dynamic name) { final Set<String> unionNames = Key.synonyms[name].map<String>((dynamic name) {
return upperCamelToLowerCamel(name); return upperCamelToLowerCamel(name as String);
}).toSet(); }).toSet();
printKey(Key.synonymPlane | entry.flutterId, entry.keyLabel, name, Key.getCommentName(name), printKey(Key.synonymPlane | entry.flutterId, entry.keyLabel, name, Key.getCommentName(name),
otherComments: wrapString('This key represents the union of the keys ' otherComments: wrapString('This key represents the union of the keys '
...@@ -100,7 +100,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK ...@@ -100,7 +100,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
String get logicalSynonyms { String get logicalSynonyms {
final StringBuffer synonyms = StringBuffer(); final StringBuffer synonyms = StringBuffer();
for (String name in Key.synonyms.keys) { for (String name in Key.synonyms.keys) {
for (String synonym in Key.synonyms[name]) { for (String synonym in Key.synonyms[name].cast<String>()) {
final String keyName = upperCamelToLowerCamel(synonym); final String keyName = upperCamelToLowerCamel(synonym);
synonyms.writeln(' $keyName: $name,'); synonyms.writeln(' $keyName: $name,');
} }
......
...@@ -38,12 +38,12 @@ class KeyData { ...@@ -38,12 +38,12 @@ class KeyData {
_nameToAndroidKeyCode = _readAndroidKeyCodes(androidKeyCodeHeader); _nameToAndroidKeyCode = _readAndroidKeyCodes(androidKeyCodeHeader);
_nameToGlfwKeyCode = _readGlfwKeyCodes(glfwKeyCodeHeader); _nameToGlfwKeyCode = _readGlfwKeyCodes(glfwKeyCodeHeader);
// Cast Android dom map // Cast Android dom map
final Map<String, List<dynamic>> dynamicAndroidNames = json.decode(androidNameMap).cast<String, List<dynamic>>(); final Map<String, List<dynamic>> dynamicAndroidNames = (json.decode(androidNameMap) as Map<String, List<dynamic>>).cast<String, List<dynamic>>();
_nameToAndroidName = dynamicAndroidNames.map<String, List<String>>((String key, List<dynamic> value) { _nameToAndroidName = dynamicAndroidNames.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>()); return MapEntry<String, List<String>>(key, value.cast<String>());
}); });
// Cast GLFW dom map // Cast GLFW dom map
final Map<String, List<dynamic>> dynamicGlfwNames = json.decode(glfwNameMap).cast<String, List<dynamic>>(); final Map<String, List<dynamic>> dynamicGlfwNames = (json.decode(glfwNameMap) as Map<String, List<dynamic>>).cast<String, List<dynamic>>();
_nameToGlfwName = dynamicGlfwNames.map<String, List<String>>((String key, List<dynamic> value) { _nameToGlfwName = dynamicGlfwNames.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>()); return MapEntry<String, List<String>>(key, value.cast<String>());
}); });
...@@ -53,7 +53,7 @@ class KeyData { ...@@ -53,7 +53,7 @@ class KeyData {
/// Parses the given JSON data and populates the data structure from it. /// Parses the given JSON data and populates the data structure from it.
KeyData.fromJson(Map<String, dynamic> contentMap) { KeyData.fromJson(Map<String, dynamic> contentMap) {
data = <Key>[ data = <Key>[
for (String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key]), for (String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map<String, List<dynamic>>),
]; ];
} }
...@@ -200,9 +200,9 @@ class KeyData { ...@@ -200,9 +200,9 @@ class KeyData {
replaced.forEach((String key, dynamic value) { replaced.forEach((String key, dynamic value) {
// Some definition values point to other definitions (e.g #define GLFW_KEY_LAST GLFW_KEY_MENU). // Some definition values point to other definitions (e.g #define GLFW_KEY_LAST GLFW_KEY_MENU).
if (value is String) { if (value is String) {
result[key] = replaced[value]; result[key] = replaced[value] as int;
} else { } else {
result[key] = value; result[key] = value as int;
} }
}); });
return result; return result;
...@@ -285,18 +285,18 @@ class Key { ...@@ -285,18 +285,18 @@ class Key {
factory Key.fromJsonMapEntry(String name, Map<String, dynamic> map) { factory Key.fromJsonMapEntry(String name, Map<String, dynamic> map) {
return Key( return Key(
enumName: name, enumName: name,
name: map['names']['domkey'], name: map['names']['domkey'] as String,
chromiumName: map['names']['chromium'], chromiumName: map['names']['chromium'] as String,
usbHidCode: map['scanCodes']['usb'], usbHidCode: map['scanCodes']['usb'] as int,
androidKeyNames: map['names']['android']?.cast<String>(), androidKeyNames: (map['names']['android'] as List<dynamic>)?.cast<String>(),
androidScanCodes: map['scanCodes']['android']?.cast<int>(), androidScanCodes: (map['scanCodes']['android'] as List<dynamic>)?.cast<int>(),
androidKeyCodes: map['keyCodes']['android']?.cast<int>(), androidKeyCodes: (map['keyCodes']['android'] as List<dynamic>)?.cast<int>(),
linuxScanCode: map['scanCodes']['linux'], linuxScanCode: map['scanCodes']['linux'] as int,
xKbScanCode: map['scanCodes']['xkb'], xKbScanCode: map['scanCodes']['xkb'] as int,
windowsScanCode: map['scanCodes']['windows'], windowsScanCode: map['scanCodes']['windows'] as int,
macOsScanCode: map['scanCodes']['macos'], macOsScanCode: map['scanCodes']['macos'] as int,
glfwKeyNames: map['names']['glfw']?.cast<String>(), glfwKeyNames: (map['names']['glfw'] as List<dynamic>)?.cast<String>(),
glfwKeyCodes: map['keyCodes']['glfw']?.cast<int>(), glfwKeyCodes: (map['keyCodes']['glfw'] as List<dynamic>)?.cast<int>(),
); );
} }
...@@ -427,7 +427,7 @@ class Key { ...@@ -427,7 +427,7 @@ class Key {
static Map<String, String> get printable { static Map<String, String> get printable {
if (_printable == null) { if (_printable == null) {
final String printableKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'printable.json',)).readAsStringSync(); final String printableKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'printable.json',)).readAsStringSync();
final Map<String, dynamic> printable = json.decode(printableKeys); final Map<String, dynamic> printable = json.decode(printableKeys) as Map<String, dynamic>;
_printable = printable.cast<String, String>(); _printable = printable.cast<String, String>();
} }
return _printable; return _printable;
...@@ -442,7 +442,7 @@ class Key { ...@@ -442,7 +442,7 @@ class Key {
static Map<String, List<dynamic>> get synonyms { static Map<String, List<dynamic>> get synonyms {
if (_synonym == null) { if (_synonym == null) {
final String synonymKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'synonyms.json',)).readAsStringSync(); final String synonymKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'synonyms.json',)).readAsStringSync();
final Map<String, dynamic> synonym = json.decode(synonymKeys); final Map<String, dynamic> synonym = json.decode(synonymKeys) as Map<String, dynamic>;
_synonym = synonym.cast<String, List<dynamic>>(); _synonym = synonym.cast<String, List<dynamic>>();
} }
return _synonym; return _synonym;
......
...@@ -60,7 +60,7 @@ Future<void> generateDocs(String url, String docName, String checkFile) async { ...@@ -60,7 +60,7 @@ Future<void> generateDocs(String url, String docName, String checkFile) async {
if (!af.name.endsWith('/')) { if (!af.name.endsWith('/')) {
final File file = File('${output.path}/${af.name}'); final File file = File('${output.path}/${af.name}');
file.createSync(recursive: true); file.createSync(recursive: true);
file.writeAsBytesSync(af.content); file.writeAsBytesSync(af.content as List<int>);
} }
} }
......
...@@ -66,12 +66,12 @@ void main(List<String> args) { ...@@ -66,12 +66,12 @@ void main(List<String> args) {
exit(1); exit(1);
} }
final String level = argResults[kIncrement]; final String level = argResults[kIncrement] as String;
final String commit = argResults[kCommit]; final String commit = argResults[kCommit] as String;
final String origin = argResults[kOrigin]; final String origin = argResults[kOrigin] as String;
final bool justPrint = argResults[kJustPrint]; final bool justPrint = argResults[kJustPrint] as bool;
final bool autoApprove = argResults[kYes]; final bool autoApprove = argResults[kYes] as bool;
final bool help = argResults[kHelp]; final bool help = argResults[kHelp] as bool;
if (help || level == null) { if (help || level == null) {
print('roll_dev.dart --increment=level --commit=hash • update the version tags and roll a new dev build.\n'); print('roll_dev.dart --increment=level --commit=hash • update the version tags and roll a new dev build.\n');
...@@ -174,8 +174,8 @@ Match parseFullTag(String version) { ...@@ -174,8 +174,8 @@ Match parseFullTag(String version) {
String getGitOutput(String command, String explanation) { String getGitOutput(String command, String explanation) {
final ProcessResult result = _runGit(command); final ProcessResult result = _runGit(command);
if (result.stderr.isEmpty && result.exitCode == 0) if ((result.stderr as String).isEmpty && result.exitCode == 0)
return result.stdout.trim(); return (result.stdout as String).trim();
_reportGitFailureAndExit(result, explanation); _reportGitFailureAndExit(result, explanation);
return null; // for the analyzer's sake return null; // for the analyzer's sake
} }
...@@ -196,9 +196,9 @@ void _reportGitFailureAndExit(ProcessResult result, String explanation) { ...@@ -196,9 +196,9 @@ void _reportGitFailureAndExit(ProcessResult result, String explanation) {
} else { } else {
print('Failed to $explanation.'); print('Failed to $explanation.');
} }
if (result.stdout.isNotEmpty) if ((result.stdout as String).isNotEmpty)
print('stdout from git:\n${result.stdout}\n'); print('stdout from git:\n${result.stdout}\n');
if (result.stderr.isNotEmpty) if ((result.stderr as String).isNotEmpty)
print('stderr from git:\n${result.stderr}\n'); print('stderr from git:\n${result.stderr}\n');
exit(1); exit(1);
} }
...@@ -32,7 +32,7 @@ import 'localizations_utils.dart'; ...@@ -32,7 +32,7 @@ import 'localizations_utils.dart';
Map<String, dynamic> loadBundle(File file) { Map<String, dynamic> loadBundle(File file) {
if (!FileSystemEntity.isFileSync(file.path)) if (!FileSystemEntity.isFileSync(file.path))
exitWithError('Unable to find input file: ${file.path}'); exitWithError('Unable to find input file: ${file.path}');
return json.decode(file.readAsStringSync()); return json.decode(file.readAsStringSync()) as Map<String, dynamic>;
} }
void encodeBundleTranslations(Map<String, dynamic> bundle) { void encodeBundleTranslations(Map<String, dynamic> bundle) {
...@@ -41,7 +41,7 @@ void encodeBundleTranslations(Map<String, dynamic> bundle) { ...@@ -41,7 +41,7 @@ void encodeBundleTranslations(Map<String, dynamic> bundle) {
// to encode them. // to encode them.
if (key.startsWith('@')) if (key.startsWith('@'))
continue; continue;
final String translation = bundle[key]; final String translation = bundle[key] as String;
// Rewrite the string as a series of unicode characters in JSON format. // Rewrite the string as a series of unicode characters in JSON format.
// Like "\u0012\u0123\u1234". // Like "\u0012\u0123\u1234".
bundle[key] = translation.runes.map((int code) { bundle[key] = translation.runes.map((int code) {
......
...@@ -108,7 +108,7 @@ Future<void> main(List<String> rawArgs) async { ...@@ -108,7 +108,7 @@ Future<void> main(List<String> rawArgs) async {
buffer.writeln('const Map<String, Map<String, String>> datePatterns = <String, Map<String, String>> {'); buffer.writeln('const Map<String, Map<String, String>> datePatterns = <String, Map<String, String>> {');
patternFiles.forEach((String locale, File data) { patternFiles.forEach((String locale, File data) {
if (_supportedLocales().contains(locale)) { if (_supportedLocales().contains(locale)) {
final Map<String, dynamic> patterns = json.decode(data.readAsStringSync()); final Map<String, dynamic> patterns = json.decode(data.readAsStringSync()) as Map<String, dynamic>;
buffer.writeln("'$locale': <String, String>{"); buffer.writeln("'$locale': <String, String>{");
patterns.forEach((String key, dynamic value) { patterns.forEach((String key, dynamic value) {
assert(value is String); assert(value is String);
...@@ -177,12 +177,13 @@ Set<String> _supportedLocales() { ...@@ -177,12 +177,13 @@ Set<String> _supportedLocales() {
Map<String, File> _listIntlData(Directory directory) { Map<String, File> _listIntlData(Directory directory) {
final Map<String, File> localeFiles = <String, File>{}; final Map<String, File> localeFiles = <String, File>{};
for (FileSystemEntity entity in directory.listSync()) { final Iterable<File> files = directory
final String filePath = entity.path; .listSync()
if (FileSystemEntity.isFileSync(filePath) && filePath.endsWith('.json')) { .whereType<File>()
final String locale = path.basenameWithoutExtension(filePath); .where((File file) => file.path.endsWith('.json'));
localeFiles[locale] = entity; for (File file in files) {
} final String locale = path.basenameWithoutExtension(file.path);
localeFiles[locale] = file;
} }
final List<String> locales = localeFiles.keys.toList(growable: false); final List<String> locales = localeFiles.keys.toList(growable: false);
......
...@@ -154,9 +154,9 @@ int sortFilesByPath (FileSystemEntity a, FileSystemEntity b) { ...@@ -154,9 +154,9 @@ int sortFilesByPath (FileSystemEntity a, FileSystemEntity b) {
} }
List<String> genMethodParameters(Map<String, dynamic> bundle, String key, String type) { List<String> genMethodParameters(Map<String, dynamic> bundle, String key, String type) {
final Map<String, dynamic> attributesMap = bundle['@$key']; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap != null && attributesMap.containsKey('placeholders')) { if (attributesMap != null && attributesMap.containsKey('placeholders')) {
final Map<String, dynamic> placeholders = attributesMap['placeholders']; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
return placeholders.keys.map((String parameter) => '$type $parameter').toList(); return placeholders.keys.map((String parameter) => '$type $parameter').toList();
} }
return <String>[]; return <String>[];
...@@ -164,14 +164,14 @@ List<String> genMethodParameters(Map<String, dynamic> bundle, String key, String ...@@ -164,14 +164,14 @@ List<String> genMethodParameters(Map<String, dynamic> bundle, String key, String
List<String> genIntlMethodArgs(Map<String, dynamic> bundle, String key) { List<String> genIntlMethodArgs(Map<String, dynamic> bundle, String key) {
final List<String> attributes = <String>['name: \'$key\'']; final List<String> attributes = <String>['name: \'$key\''];
final Map<String, dynamic> attributesMap = bundle['@$key']; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap != null) { if (attributesMap != null) {
if (attributesMap.containsKey('description')) { if (attributesMap.containsKey('description')) {
final String description = attributesMap['description']; final String description = attributesMap['description'] as String;
attributes.add('desc: ${generateString(description)}'); attributes.add('desc: ${generateString(description)}');
} }
if (attributesMap.containsKey('placeholders')) { if (attributesMap.containsKey('placeholders')) {
final Map<String, dynamic> placeholders = attributesMap['placeholders']; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
if (placeholders.isNotEmpty) { if (placeholders.isNotEmpty) {
final String args = placeholders.keys.join(', '); final String args = placeholders.keys.join(', ');
attributes.add('args: <Object>[$args]'); attributes.add('args: <Object>[$args]');
...@@ -183,15 +183,15 @@ List<String> genIntlMethodArgs(Map<String, dynamic> bundle, String key) { ...@@ -183,15 +183,15 @@ List<String> genIntlMethodArgs(Map<String, dynamic> bundle, String key) {
String genSimpleMethod(Map<String, dynamic> bundle, String key) { String genSimpleMethod(Map<String, dynamic> bundle, String key) {
String genSimpleMethodMessage(Map<String, dynamic> bundle, String key) { String genSimpleMethodMessage(Map<String, dynamic> bundle, String key) {
String message = bundle[key]; String message = bundle[key] as String;
final Map<String, dynamic> attributesMap = bundle['@$key']; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
final Map<String, dynamic> placeholders = attributesMap['placeholders']; final Map<String, dynamic> placeholders = attributesMap['placeholders'] as Map<String, dynamic>;
for (String placeholder in placeholders.keys) for (String placeholder in placeholders.keys)
message = message.replaceAll('{$placeholder}', '\$$placeholder'); message = message.replaceAll('{$placeholder}', '\$$placeholder');
return generateString(message); return generateString(message);
} }
final Map<String, dynamic> attributesMap = bundle['@$key']; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap == null) if (attributesMap == null)
exitWithError( exitWithError(
'Resource attribute "@$key" was not found. Please ensure that each ' 'Resource attribute "@$key" was not found. Please ensure that each '
...@@ -208,18 +208,18 @@ String genSimpleMethod(Map<String, dynamic> bundle, String key) { ...@@ -208,18 +208,18 @@ String genSimpleMethod(Map<String, dynamic> bundle, String key) {
return getterMethodTemplate return getterMethodTemplate
.replaceAll('@methodName', key) .replaceAll('@methodName', key)
.replaceAll('@message', '${generateString(bundle[key])}') .replaceAll('@message', '${generateString(bundle[key] as String)}')
.replaceAll('@intlMethodArgs', genIntlMethodArgs(bundle, key).join(',\n ')); .replaceAll('@intlMethodArgs', genIntlMethodArgs(bundle, key).join(',\n '));
} }
String genPluralMethod(Map<String, dynamic> bundle, String key) { String genPluralMethod(Map<String, dynamic> bundle, String key) {
final Map<String, dynamic> attributesMap = bundle['@$key']; final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
assert(attributesMap != null && attributesMap.containsKey('placeholders')); assert(attributesMap != null && attributesMap.containsKey('placeholders'));
final Iterable<String> placeholders = attributesMap['placeholders'].keys; final Iterable<String> placeholders = attributesMap['placeholders'].keys as Iterable<String>;
// To make it easier to parse the plurals message, temporarily replace each // To make it easier to parse the plurals message, temporarily replace each
// "{placeholder}" parameter with "#placeholder#". // "{placeholder}" parameter with "#placeholder#".
String message = bundle[key]; String message = bundle[key] as String;
for (String placeholder in placeholders) for (String placeholder in placeholders)
message = message.replaceAll('{$placeholder}', '#$placeholder#'); message = message.replaceAll('{$placeholder}', '#$placeholder#');
...@@ -354,13 +354,13 @@ Future<void> main(List<String> arguments) async { ...@@ -354,13 +354,13 @@ Future<void> main(List<String> arguments) async {
exit(0); exit(0);
} }
final String arbPathString = results['arb-dir']; final String arbPathString = results['arb-dir'] as String;
final String outputFileString = results['output-localization-file']; final String outputFileString = results['output-localization-file'] as String;
final Directory l10nDirectory = Directory(arbPathString); final Directory l10nDirectory = Directory(arbPathString);
final File templateArbFile = File(path.join(l10nDirectory.path, results['template-arb-file'])); final File templateArbFile = File(path.join(l10nDirectory.path, results['template-arb-file'] as String));
final File outputFile = File(path.join(l10nDirectory.path, outputFileString)); final File outputFile = File(path.join(l10nDirectory.path, outputFileString));
final String stringsClassName = results['output-class']; final String stringsClassName = results['output-class'] as String;
if (!l10nDirectory.existsSync()) if (!l10nDirectory.existsSync())
exitWithError( exitWithError(
...@@ -395,8 +395,8 @@ Future<void> main(List<String> arguments) async { ...@@ -395,8 +395,8 @@ Future<void> main(List<String> arguments) async {
final RegExp arbFilenameRE = RegExp(r'(\w+)\.arb$'); final RegExp arbFilenameRE = RegExp(r'(\w+)\.arb$');
if (arbFilenameRE.hasMatch(entityPath)) { if (arbFilenameRE.hasMatch(entityPath)) {
final File arbFile = File(entityPath); final File arbFile = File(entityPath);
final Map<String, dynamic> arbContents = json.decode(arbFile.readAsStringSync()); final Map<String, dynamic> arbContents = json.decode(arbFile.readAsStringSync()) as Map<String, dynamic>;
String localeString = arbContents['@@locale']; String localeString = arbContents['@@locale'] as String;
if (localeString == null) { if (localeString == null) {
final RegExp arbFilenameLocaleRE = RegExp(r'^[^_]*_(\w+)\.arb$'); final RegExp arbFilenameLocaleRE = RegExp(r'^[^_]*_(\w+)\.arb$');
...@@ -430,7 +430,7 @@ Future<void> main(List<String> arguments) async { ...@@ -430,7 +430,7 @@ Future<void> main(List<String> arguments) async {
Map<String, dynamic> bundle; Map<String, dynamic> bundle;
try { try {
bundle = json.decode(templateArbFile.readAsStringSync()); bundle = json.decode(templateArbFile.readAsStringSync()) as Map<String, dynamic>;
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
exitWithError('Unable to read input arb file: $e'); exitWithError('Unable to read input arb file: $e');
} on FormatException catch (e) { } on FormatException catch (e) {
...@@ -447,7 +447,7 @@ Future<void> main(List<String> arguments) async { ...@@ -447,7 +447,7 @@ Future<void> main(List<String> arguments) async {
'Invalid key format: $key \n It has to be in camel case, cannot start ' 'Invalid key format: $key \n It has to be in camel case, cannot start '
'with a number, and cannot contain non-alphanumeric characters.' 'with a number, and cannot contain non-alphanumeric characters.'
); );
if (pluralValueRE.hasMatch(bundle[key])) if (pluralValueRE.hasMatch(bundle[key] as String))
classMethods.add(genPluralMethod(bundle, key)); classMethods.add(genPluralMethod(bundle, key));
else else
classMethods.add(genSimpleMethod(bundle, key)); classMethods.add(genSimpleMethod(bundle, key));
......
...@@ -136,7 +136,7 @@ String generateArbBasedLocalizationSubclasses({ ...@@ -136,7 +136,7 @@ String generateArbBasedLocalizationSubclasses({
final Map<String, String> languageResources = localeToResources[languageLocale]; final Map<String, String> languageResources = localeToResources[languageLocale];
for (String key in allKeys) { for (String key in allKeys) {
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key]; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale)); output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale));
} }
output.writeln('}'); output.writeln('}');
...@@ -158,7 +158,7 @@ String generateArbBasedLocalizationSubclasses({ ...@@ -158,7 +158,7 @@ String generateArbBasedLocalizationSubclasses({
for (String key in scriptResources.keys.toList()..sort()) { for (String key in scriptResources.keys.toList()..sort()) {
if (languageResources[key] == scriptResources[key]) if (languageResources[key] == scriptResources[key])
continue; continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key]; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale)); output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale));
} }
output.writeln('}'); output.writeln('}');
...@@ -183,7 +183,7 @@ String generateArbBasedLocalizationSubclasses({ ...@@ -183,7 +183,7 @@ String generateArbBasedLocalizationSubclasses({
// When script fallback contains the key, we compare to it instead of language fallback. // When script fallback contains the key, we compare to it instead of language fallback.
if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key]) if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key])
continue; continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key]; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale)); output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
} }
output.writeln('}'); output.writeln('}');
...@@ -207,7 +207,7 @@ String generateArbBasedLocalizationSubclasses({ ...@@ -207,7 +207,7 @@ String generateArbBasedLocalizationSubclasses({
for (String key in localeResources.keys) { for (String key in localeResources.keys) {
if (languageResources[key] == localeResources[key]) if (languageResources[key] == localeResources[key])
continue; continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key]; final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale)); output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
} }
output.writeln('}'); output.writeln('}');
...@@ -380,7 +380,7 @@ $factoryDeclaration ...@@ -380,7 +380,7 @@ $factoryDeclaration
/// Used by [generateGetter] below. /// Used by [generateGetter] below.
String generateType(Map<String, dynamic> attributes) { String generateType(Map<String, dynamic> attributes) {
if (attributes != null) { if (attributes != null) {
switch (attributes['x-flutter-type']) { switch (attributes['x-flutter-type'] as String) {
case 'icuShortTimePattern': case 'icuShortTimePattern':
return 'TimeOfDayFormat'; return 'TimeOfDayFormat';
case 'scriptCategory': case 'scriptCategory':
...@@ -401,7 +401,7 @@ String generateKey(String key, Map<String, dynamic> attributes) { ...@@ -401,7 +401,7 @@ String generateKey(String key, Map<String, dynamic> attributes) {
if (attributes != null) { if (attributes != null) {
if (attributes.containsKey('parameters')) if (attributes.containsKey('parameters'))
return '${key}Raw'; return '${key}Raw';
switch (attributes['x-flutter-type']) { switch (attributes['x-flutter-type'] as String) {
case 'icuShortTimePattern': case 'icuShortTimePattern':
return '${key}Raw'; return '${key}Raw';
} }
...@@ -443,7 +443,7 @@ String generateValue(String value, Map<String, dynamic> attributes, LocaleInfo l ...@@ -443,7 +443,7 @@ String generateValue(String value, Map<String, dynamic> attributes, LocaleInfo l
return null; return null;
// cupertino_en.arb doesn't use x-flutter-type. // cupertino_en.arb doesn't use x-flutter-type.
if (attributes != null) { if (attributes != null) {
switch (attributes['x-flutter-type']) { switch (attributes['x-flutter-type'] as String) {
case 'icuShortTimePattern': case 'icuShortTimePattern':
if (!_icuTimeOfDayToEnum.containsKey(value)) { if (!_icuTimeOfDayToEnum.containsKey(value)) {
throw Exception( throw Exception(
......
...@@ -114,10 +114,8 @@ class LocaleInfo implements Comparable<LocaleInfo> { ...@@ -114,10 +114,8 @@ class LocaleInfo implements Comparable<LocaleInfo> {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
if (!(other is LocaleInfo)) return other is LocaleInfo
return false; && other.originalString == originalString;
final LocaleInfo otherLocale = other;
return originalString == otherLocale.originalString;
} }
@override @override
...@@ -167,13 +165,13 @@ void loadMatchingArbsIntoBundleMaps({ ...@@ -167,13 +165,13 @@ void loadMatchingArbsIntoBundleMaps({
void populateResources(LocaleInfo locale, File file) { void populateResources(LocaleInfo locale, File file) {
final Map<String, String> resources = localeToResources[locale]; final Map<String, String> resources = localeToResources[locale];
final Map<String, dynamic> attributes = localeToResourceAttributes[locale]; final Map<String, dynamic> attributes = localeToResourceAttributes[locale];
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()); final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (String key in bundle.keys) { for (String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo. // The ARB file resource "attributes" for foo are called @foo.
if (key.startsWith('@')) if (key.startsWith('@'))
attributes[key.substring(1)] = bundle[key]; attributes[key.substring(1)] = bundle[key];
else else
resources[key] = bundle[key]; resources[key] = bundle[key] as String;
} }
} }
// Only pre-assume scriptCode if there is a country or script code to assume off of. // Only pre-assume scriptCode if there is a country or script code to assume off of.
...@@ -247,9 +245,9 @@ GeneratorOptions parseArgs(List<String> rawArgs) { ...@@ -247,9 +245,9 @@ GeneratorOptions parseArgs(List<String> rawArgs) {
defaultsTo: false, defaultsTo: false,
); );
final argslib.ArgResults args = argParser.parse(rawArgs); final argslib.ArgResults args = argParser.parse(rawArgs);
final bool writeToFile = args['overwrite']; final bool writeToFile = args['overwrite'] as bool;
final bool materialOnly = args['material']; final bool materialOnly = args['material'] as bool;
final bool cupertinoOnly = args['cupertino']; final bool cupertinoOnly = args['cupertino'] as bool;
return GeneratorOptions(writeToFile: writeToFile, materialOnly: materialOnly, cupertinoOnly: cupertinoOnly); return GeneratorOptions(writeToFile: writeToFile, materialOnly: materialOnly, cupertinoOnly: cupertinoOnly);
} }
......
...@@ -36,7 +36,7 @@ void validateEnglishLocalizations(File file) { ...@@ -36,7 +36,7 @@ void validateEnglishLocalizations(File file) {
throw ValidationError(errorMessages.toString()); throw ValidationError(errorMessages.toString());
} }
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()); final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (String resourceId in bundle.keys) { for (String resourceId in bundle.keys) {
if (resourceId.startsWith('@')) if (resourceId.startsWith('@'))
...@@ -67,11 +67,11 @@ void validateEnglishLocalizations(File file) { ...@@ -67,11 +67,11 @@ void validateEnglishLocalizations(File file) {
continue; continue;
} }
final String description = atResource['description']; final String description = atResource['description'] as String;
if (description == null) if (description == null)
errorMessages.writeln('No description specified for $atResourceId'); errorMessages.writeln('No description specified for $atResourceId');
final String plural = atResource['plural']; final String plural = atResource['plural'] as String;
final String resourceId = atResourceId.substring(1); final String resourceId = atResourceId.substring(1);
if (plural != null) { if (plural != null) {
final String resourceIdOther = '${resourceId}Other'; final String resourceIdOther = '${resourceId}Other';
......
...@@ -25,7 +25,7 @@ void main(List<String> args) { ...@@ -25,7 +25,7 @@ void main(List<String> args) {
final ArgResults results = argParser.parse(args); final ArgResults results = argParser.parse(args);
if (results['help']) { if (results['help'] as bool) {
print('Generate n copies of flutter_gallery.\n'); print('Generate n copies of flutter_gallery.\n');
print('usage: dart mega_gallery.dart <options>'); print('usage: dart mega_gallery.dart <options>');
print(argParser.usage); print(argParser.usage);
...@@ -33,9 +33,9 @@ void main(List<String> args) { ...@@ -33,9 +33,9 @@ void main(List<String> args) {
} }
final Directory source = Directory(_normalize('examples/flutter_gallery')); final Directory source = Directory(_normalize('examples/flutter_gallery'));
final Directory out = Directory(_normalize(results['out'])); final Directory out = Directory(_normalize(results['out'] as String));
if (results['delete']) { if (results['delete'] as bool) {
if (out.existsSync()) { if (out.existsSync()) {
print('Deleting ${out.path}'); print('Deleting ${out.path}');
out.deleteSync(recursive: true); out.deleteSync(recursive: true);
...@@ -55,7 +55,7 @@ void main(List<String> args) { ...@@ -55,7 +55,7 @@ void main(List<String> args) {
final SourceStats stats = getStatsFor(_dir(source, 'lib')); final SourceStats stats = getStatsFor(_dir(source, 'lib'));
copies = (kTargetLineCount / stats.lines).round(); copies = (kTargetLineCount / stats.lines).round();
} else { } else {
copies = int.parse(results['copies']); copies = int.parse(results['copies'] as String);
} }
print('Making $copies copies of flutter_gallery.'); print('Making $copies copies of flutter_gallery.');
...@@ -89,7 +89,7 @@ void main(List<String> args) { ...@@ -89,7 +89,7 @@ void main(List<String> args) {
_file(out, '.dartignore').writeAsStringSync(''); _file(out, '.dartignore').writeAsStringSync('');
// Count source lines and number of files; tell how to run it. // Count source lines and number of files; tell how to run it.
print(' ${path.relative(results["out"])} : ${getStatsFor(out)}'); print(' ${path.relative(results["out"] as String)} : ${getStatsFor(out)}');
} }
// TODO(devoncarew): Create an entry-point that builds a UI with all `n` copies. // TODO(devoncarew): Create an entry-point that builds a UI with all `n` copies.
......
...@@ -158,12 +158,12 @@ void main(List<String> args) { ...@@ -158,12 +158,12 @@ void main(List<String> args) {
argParser.addFlag(kOptionDryRun, defaultsTo: false); argParser.addFlag(kOptionDryRun, defaultsTo: false);
final ArgResults argResults = argParser.parse(args); final ArgResults argResults = argParser.parse(args);
final File iconFile = File(path.absolute(argResults[kOptionIconsPath])); final File iconFile = File(path.absolute(argResults[kOptionIconsPath] as String));
if (!iconFile.existsSync()) { if (!iconFile.existsSync()) {
stderr.writeln('Icons file not found: ${iconFile.path}'); stderr.writeln('Icons file not found: ${iconFile.path}');
exit(1); exit(1);
} }
final File codepointsFile = File(path.absolute(argResults[kOptionCodepointsPath])); final File codepointsFile = File(path.absolute(argResults[kOptionCodepointsPath] as String));
if (!codepointsFile.existsSync()) { if (!codepointsFile.existsSync()) {
stderr.writeln('Codepoints file not found: ${codepointsFile.path}'); stderr.writeln('Codepoints file not found: ${codepointsFile.path}');
exit(1); exit(1);
...@@ -173,7 +173,7 @@ void main(List<String> args) { ...@@ -173,7 +173,7 @@ void main(List<String> args) {
final String codepointData = codepointsFile.readAsStringSync(); final String codepointData = codepointsFile.readAsStringSync();
final String newIconData = regenerateIconsFile(iconData, codepointData); final String newIconData = regenerateIconsFile(iconData, codepointData);
if (argResults[kOptionDryRun]) if (argResults[kOptionDryRun] as bool)
stdout.writeln(newIconData); stdout.writeln(newIconData);
else else
iconFile.writeAsStringSync(newIconData); iconFile.writeAsStringSync(newIconData);
......
...@@ -56,7 +56,7 @@ void main(List<String> args) { ...@@ -56,7 +56,7 @@ void main(List<String> args) {
final ArgResults argResults = parser.parse(args); final ArgResults argResults = parser.parse(args);
if (argResults['help'] || if (argResults['help'] as bool ||
!argResults.wasParsed('output') || !argResults.wasParsed('output') ||
!argResults.wasParsed('asset-name') || !argResults.wasParsed('asset-name') ||
argResults.rest.isEmpty) { argResults.rest.isEmpty) {
...@@ -71,20 +71,20 @@ void main(List<String> args) { ...@@ -71,20 +71,20 @@ void main(List<String> args) {
final StringBuffer generatedSb = StringBuffer(); final StringBuffer generatedSb = StringBuffer();
if (argResults.wasParsed('header')) { if (argResults.wasParsed('header')) {
generatedSb.write(File(argResults['header']).readAsStringSync()); generatedSb.write(File(argResults['header'] as String).readAsStringSync());
generatedSb.write('\n'); generatedSb.write('\n');
} }
if (argResults['codegen_comment']) if (argResults['codegen_comment'] as bool)
generatedSb.write(kCodegenComment); generatedSb.write(kCodegenComment);
if (argResults.wasParsed('part-of')) if (argResults.wasParsed('part-of'))
generatedSb.write('part of ${argResults['part-of']};\n'); generatedSb.write('part of ${argResults['part-of']};\n');
final Animation animation = Animation.fromFrameData(frames); final Animation animation = Animation.fromFrameData(frames);
generatedSb.write(animation.toDart('_AnimatedIconData', argResults['asset-name'])); generatedSb.write(animation.toDart('_AnimatedIconData', argResults['asset-name'] as String));
final File outFile = File(argResults['output']); final File outFile = File(argResults['output'] as String);
outFile.writeAsStringSync(generatedSb.toString()); outFile.writeAsStringSync(generatedSb.toString());
} }
......
...@@ -204,7 +204,7 @@ List<SvgPath> _interpretSvgGroup(List<XmlNode> children, _Transform transform) { ...@@ -204,7 +204,7 @@ List<SvgPath> _interpretSvgGroup(List<XmlNode> children, _Transform transform) {
for (XmlNode node in children) { for (XmlNode node in children) {
if (node.nodeType != XmlNodeType.ELEMENT) if (node.nodeType != XmlNodeType.ELEMENT)
continue; continue;
final XmlElement element = node; final XmlElement element = node as XmlElement;
if (element.name.local == 'path') { if (element.name.local == 'path') {
paths.add(SvgPath.fromElement(element).applyTransform(transform)); paths.add(SvgPath.fromElement(element).applyTransform(transform));
...@@ -270,9 +270,9 @@ class FrameData { ...@@ -270,9 +270,9 @@ class FrameData {
bool operator ==(Object other) { bool operator ==(Object other) {
if (runtimeType != other.runtimeType) if (runtimeType != other.runtimeType)
return false; return false;
final FrameData typedOther = other; return other is FrameData
return size == typedOther.size && other.size == size
&& const ListEquality<SvgPath>().equals(paths, typedOther.paths); && const ListEquality<SvgPath>().equals(other.paths, paths);
} }
@override @override
...@@ -322,10 +322,10 @@ class SvgPath { ...@@ -322,10 +322,10 @@ class SvgPath {
bool operator ==(Object other) { bool operator ==(Object other) {
if (runtimeType != other.runtimeType) if (runtimeType != other.runtimeType)
return false; return false;
final SvgPath typedOther = other; return other is SvgPath
return id == typedOther.id && other.id == id
&& opacity == typedOther.opacity && other.opacity == opacity
&& const ListEquality<SvgPathCommand>().equals(commands, typedOther.commands); && const ListEquality<SvgPathCommand>().equals(other.commands, commands);
} }
@override @override
...@@ -371,9 +371,9 @@ class SvgPathCommand { ...@@ -371,9 +371,9 @@ class SvgPathCommand {
bool operator ==(Object other) { bool operator ==(Object other) {
if (runtimeType != other.runtimeType) if (runtimeType != other.runtimeType)
return false; return false;
final SvgPathCommand typedOther = other; return other is SvgPathCommand
return type == typedOther.type && other.type == type
&& const ListEquality<Point<double>>().equals(points, typedOther.points); && const ListEquality<Point<double>>().equals(other.points, points);
} }
@override @override
...@@ -554,7 +554,7 @@ XmlElement _extractSvgElement(XmlDocument document) { ...@@ -554,7 +554,7 @@ XmlElement _extractSvgElement(XmlDocument document) {
return document.children.singleWhere( return document.children.singleWhere(
(XmlNode node) => node.nodeType == XmlNodeType.ELEMENT && (XmlNode node) => node.nodeType == XmlNodeType.ELEMENT &&
_asElement(node).name.local == 'svg' _asElement(node).name.local == 'svg'
); ) as XmlElement;
} }
XmlElement _asElement(XmlNode node) => node; XmlElement _asElement(XmlNode node) => node as XmlElement;
...@@ -622,7 +622,7 @@ class PathMatcher extends Matcher { ...@@ -622,7 +622,7 @@ class PathMatcher extends Matcher {
if (item.runtimeType != actual.runtimeType) if (item.runtimeType != actual.runtimeType)
return false; return false;
final SvgPath other = item; final SvgPath other = item as SvgPath;
if (other.id != actual.id || other.opacity != actual.opacity) if (other.id != actual.id || other.opacity != actual.opacity)
return false; return false;
...@@ -666,7 +666,7 @@ class PathAnimationMatcher extends Matcher { ...@@ -666,7 +666,7 @@ class PathAnimationMatcher extends Matcher {
if (item.runtimeType != expected.runtimeType) if (item.runtimeType != expected.runtimeType)
return false; return false;
final PathAnimation other = item; final PathAnimation other = item as PathAnimation;
if (!const ListEquality<double>().equals(other.opacities, expected.opacities)) if (!const ListEquality<double>().equals(other.opacities, expected.opacities))
return false; return false;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment