[flutter_tools] Fix _CastError in HotRunner._resetDirtyAssets (#108771)

This commit is contained in:
Christopher Fujino
2022-08-24 16:40:19 -07:00
committed by GitHub
parent 965912d886
commit 6e95067273
9 changed files with 390 additions and 360 deletions

View File

@@ -12,6 +12,7 @@ import 'context.dart';
import 'io.dart' as io;
import 'logger.dart';
// TODO(fujino): This should be direct injected, rather than mutable global state.
@visibleForTesting
Future<dds.DartDevelopmentService> Function(
Uri remoteVmServiceUri, {

View File

@@ -123,7 +123,7 @@ class _DaemonServer {
// We have to listen to socket.done. Otherwise when the connection is
// reset, we will receive an uncatchable exception.
// https://github.com/dart-lang/sdk/issues/25518
final Future<void> socketDone = socket.done.catchError((dynamic error, StackTrace stackTrace) {
final Future<void> socketDone = socket.done.catchError((Object error, StackTrace stackTrace) {
logger!.printError('Socket error: $error');
logger!.printTrace('$stackTrace');
});
@@ -145,8 +145,8 @@ class _DaemonServer {
}
}
typedef CommandHandler = Future<dynamic>? Function(Map<String, dynamic> args);
typedef CommandHandlerWithBinary = Future<dynamic> Function(Map<String, dynamic> args, Stream<List<int>>? binary);
typedef CommandHandler = Future<Object?>? Function(Map<String, Object?> args);
typedef CommandHandlerWithBinary = Future<Object?> Function(Map<String, Object?> args, Stream<List<int>>? binary);
class Daemon {
Daemon(
@@ -221,7 +221,7 @@ class Daemon {
throw DaemonException('no domain for method: $method');
}
_domainMap[prefix]!.handleCommand(name, id, castStringKeyedMap(request.data['params']) ?? const <String, dynamic>{}, request.binary);
_domainMap[prefix]!.handleCommand(name, id, castStringKeyedMap(request.data['params']) ?? const <String, Object?>{}, request.binary);
} on Exception catch (error, trace) {
connection.sendErrorResponse(id, _toJsonable(error), trace);
}
@@ -268,52 +268,53 @@ abstract class Domain {
@override
String toString() => name;
void handleCommand(String command, Object id, Map<String, dynamic> args, Stream<List<int>>? binary) {
Future<dynamic>.sync(() {
void handleCommand(String command, Object id, Map<String, Object?> args, Stream<List<int>>? binary) {
Future<Object?>.sync(() {
if (_handlers.containsKey(command)) {
return _handlers[command]!(args);
} else if (_handlersWithBinary.containsKey(command)) {
return _handlersWithBinary[command]!(args, binary);
}
throw DaemonException('command not understood: $name.$command');
}).then<dynamic>((dynamic result) {
}).then<Object?>((Object? result) {
daemon.connection.sendResponse(id, _toJsonable(result));
return null;
}).catchError((Object error, StackTrace stackTrace) {
daemon.connection.sendErrorResponse(id, _toJsonable(error), stackTrace);
});
}
void sendEvent(String name, [ dynamic args, List<int>? binary ]) {
void sendEvent(String name, [ Object? args, List<int>? binary ]) {
daemon.connection.sendEvent(name, _toJsonable(args), binary);
}
String? _getStringArg(Map<String, dynamic> args, String name, { bool required = false }) {
String? _getStringArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! String) {
throw DaemonException('$name is not a String');
}
return val as String?;
}
bool? _getBoolArg(Map<String, dynamic> args, String name, { bool required = false }) {
bool? _getBoolArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! bool) {
throw DaemonException('$name is not a bool');
}
return val as bool?;
}
int? _getIntArg(Map<String, dynamic> args, String name, { bool required = false }) {
int? _getIntArg(Map<String, Object?> args, String name, { bool required = false }) {
if (required && !args.containsKey(name)) {
throw DaemonException('$name is required');
}
final dynamic val = args[name];
final Object? val = args[name];
if (val != null && val is! int) {
throw DaemonException('$name is not an int');
}
@@ -334,7 +335,7 @@ class DaemonDomain extends Domain {
sendEvent(
'daemon.connected',
<String, dynamic>{
<String, Object?>{
'version': protocolVersion,
'pid': pid,
},
@@ -357,13 +358,13 @@ class DaemonDomain extends Domain {
}
} else {
if (message.stackTrace != null) {
sendEvent('daemon.logMessage', <String, dynamic>{
sendEvent('daemon.logMessage', <String, Object?>{
'level': message.level,
'message': message.message,
'stackTrace': message.stackTrace.toString(),
});
} else {
sendEvent('daemon.logMessage', <String, dynamic>{
sendEvent('daemon.logMessage', <String, Object?>{
'level': message.level,
'message': message.message,
});
@@ -374,7 +375,7 @@ class DaemonDomain extends Domain {
StreamSubscription<LogMessage>? _subscription;
Future<String> version(Map<String, dynamic> args) {
Future<String> version(Map<String, Object?> args) {
return Future<String>.value(protocolVersion);
}
@@ -384,16 +385,16 @@ class DaemonDomain extends Domain {
/// --web-allow-expose-url switch. The client may return the same URL back if
/// tunnelling is not required for a given URL.
Future<String> exposeUrl(String url) async {
final dynamic res = await daemon.connection.sendRequest('app.exposeUrl', <String, String>{'url': url});
if (res is Map<String, dynamic> && res['url'] is String) {
return res['url'] as String;
final Object? res = await daemon.connection.sendRequest('app.exposeUrl', <String, String>{'url': url});
if (res is Map<String, Object?> && res['url'] is String) {
return res['url']! as String;
} else {
globals.printError('Invalid response to exposeUrl - params should include a String url field');
return url;
}
}
Future<void> shutdown(Map<String, dynamic> args) {
Future<void> shutdown(Map<String, Object?> args) {
Timer.run(daemon.shutdown);
return Future<void>.value();
}
@@ -408,7 +409,7 @@ class DaemonDomain extends Domain {
/// This does not filter based on the current workflow restrictions, such
/// as whether command line tools are installed or whether the host platform
/// is correct.
Future<Map<String, Object>> getSupportedPlatforms(Map<String, dynamic> args) async {
Future<Map<String, Object>> getSupportedPlatforms(Map<String, Object?> args) async {
final String? projectRoot = _getStringArg(args, 'projectRoot', required: true);
final List<String> result = <String>[];
try {
@@ -442,7 +443,7 @@ class DaemonDomain extends Domain {
'platforms': result,
};
} on Exception catch (err, stackTrace) {
sendEvent('log', <String, dynamic>{
sendEvent('log', <String, Object?>{
'log': 'Failed to parse project metadata',
'stackTrace': stackTrace.toString(),
'error': true,
@@ -604,7 +605,7 @@ class AppDomain extends Domain {
logger.domain = this;
logger.app = app;
_sendAppEvent(app, 'start', <String, dynamic>{
_sendAppEvent(app, 'start', <String, Object?>{
'deviceId': device.id,
'directory': projectDirectory,
'supportsRestart': isRestartSupported(enableHotReload, device),
@@ -619,7 +620,7 @@ class AppDomain extends Domain {
// As it just writes to stdout.
unawaited(connectionInfoCompleter.future.then<void>(
(DebugConnectionInfo info) {
final Map<String, dynamic> params = <String, dynamic>{
final Map<String, Object?> params = <String, Object?>{
// The web vmservice proxy does not have an http address.
'port': info.httpUri?.port ?? info.wsUri!.port,
'wsUri': info.wsUri.toString(),
@@ -646,7 +647,7 @@ class AppDomain extends Domain {
);
_sendAppEvent(app, 'stop');
} on Exception catch (error, trace) {
_sendAppEvent(app, 'stop', <String, dynamic>{
_sendAppEvent(app, 'stop', <String, Object?>{
'error': _toJsonable(error),
'trace': '$trace',
});
@@ -665,7 +666,7 @@ class AppDomain extends Domain {
final int _hotReloadDebounceDurationMs = 50;
Future<OperationResult>? restart(Map<String, dynamic> args) async {
Future<OperationResult>? restart(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false;
final bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false;
@@ -727,18 +728,18 @@ class AppDomain extends Domain {
/// "type":"_extensionType",
/// "method":"ext.flutter.platformOverride"
/// }
Future<Map<String, dynamic>> callServiceExtension(Map<String, dynamic> args) async {
Future<Map<String, Object?>> callServiceExtension(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final String methodName = _getStringArg(args, 'methodName')!;
final Map<String, dynamic>? params = args['params'] == null ? <String, dynamic>{} : castStringKeyedMap(args['params']);
final Map<String, Object?>? params = args['params'] == null ? <String, Object?>{} : castStringKeyedMap(args['params']);
final AppInstance? app = _getApp(appId);
if (app == null) {
throw DaemonException("app '$appId' not found");
}
final FlutterDevice device = app.runner!.flutterDevices.first!;
final FlutterDevice device = app.runner!.flutterDevices.first;
final List<FlutterView> views = await device.vmService!.getFlutterViews();
final Map<String, dynamic>? result = await device
final Map<String, Object?>? result = await device
.vmService!
.invokeFlutterExtensionRpcRaw(
methodName,
@@ -752,13 +753,13 @@ class AppDomain extends Domain {
if (result.containsKey('error')) {
// ignore: only_throw_errors
throw result['error']! as Object;
throw result['error']!;
}
return result;
}
Future<bool> stop(Map<String, dynamic> args) async {
Future<bool> stop(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final AppInstance? app = _getApp(appId);
@@ -768,8 +769,8 @@ class AppDomain extends Domain {
return app.stop().then<bool>(
(void value) => true,
onError: (dynamic error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, dynamic>{'log': '$error', 'error': true});
onError: (Object? error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true});
app.closeLogger();
_apps.remove(app);
return false;
@@ -777,7 +778,7 @@ class AppDomain extends Domain {
);
}
Future<bool> detach(Map<String, dynamic> args) async {
Future<bool> detach(Map<String, Object?> args) async {
final String? appId = _getStringArg(args, 'appId', required: true);
final AppInstance? app = _getApp(appId);
@@ -787,8 +788,8 @@ class AppDomain extends Domain {
return app.detach().then<bool>(
(void value) => true,
onError: (dynamic error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, dynamic>{'log': '$error', 'error': true});
onError: (Object? error, StackTrace stack) {
_sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true});
app.closeLogger();
_apps.remove(app);
return false;
@@ -805,8 +806,8 @@ class AppDomain extends Domain {
return null;
}
void _sendAppEvent(AppInstance app, String name, [ Map<String, dynamic>? args ]) {
sendEvent('app.$name', <String, dynamic>{
void _sendAppEvent(AppInstance app, String name, [ Map<String, Object?>? args ]) {
sendEvent('app.$name', <String, Object?>{
'appId': app.id,
...?args,
});
@@ -876,8 +877,8 @@ class DeviceDomain extends Domain {
/// Return a list of the current devices, with each device represented as a map
/// of properties (id, name, platform, ...).
Future<List<Map<String, dynamic>>> getDevices([ Map<String, dynamic>? args ]) async {
return <Map<String, dynamic>>[
Future<List<Map<String, Object?>>> getDevices([ Map<String, Object?>? args ]) async {
return <Map<String, Object?>>[
for (final PollingDeviceDiscovery discoverer in _discoverers)
for (final Device device in await discoverer.devices)
await _deviceToMap(device),
@@ -885,8 +886,8 @@ class DeviceDomain extends Domain {
}
/// Return a list of the current devices, discarding existing cache of devices.
Future<List<Map<String, dynamic>>> discoverDevices([ Map<String, dynamic>? args ]) async {
return <Map<String, dynamic>>[
Future<List<Map<String, Object?>>> discoverDevices([ Map<String, Object?>? args ]) async {
return <Map<String, Object?>>[
for (final PollingDeviceDiscovery discoverer in _discoverers)
for (final Device device in await discoverer.discoverDevices())
await _deviceToMap(device),
@@ -894,21 +895,21 @@ class DeviceDomain extends Domain {
}
/// Enable device events.
Future<void> enable(Map<String, dynamic> args) async {
Future<void> enable(Map<String, Object?> args) async {
for (final PollingDeviceDiscovery discoverer in _discoverers) {
discoverer.startPolling();
}
}
/// Disable device events.
Future<void> disable(Map<String, dynamic> args) async {
Future<void> disable(Map<String, Object?> args) async {
for (final PollingDeviceDiscovery discoverer in _discoverers) {
discoverer.stopPolling();
}
}
/// Forward a host port to a device port.
Future<Map<String, dynamic>> forward(Map<String, dynamic> args) async {
Future<Map<String, Object?>> forward(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true)!;
int? hostPort = _getIntArg(args, 'hostPort');
@@ -920,11 +921,11 @@ class DeviceDomain extends Domain {
hostPort = await device.portForwarder!.forward(devicePort, hostPort: hostPort);
return <String, dynamic>{'hostPort': hostPort};
return <String, Object?>{'hostPort': hostPort};
}
/// Removes a forwarded port.
Future<void> unforward(Map<String, dynamic> args) async {
Future<void> unforward(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final int devicePort = _getIntArg(args, 'devicePort', required: true)!;
final int hostPort = _getIntArg(args, 'hostPort', required: true)!;
@@ -938,7 +939,7 @@ class DeviceDomain extends Domain {
}
/// Returns whether a device supports runtime mode.
Future<bool> supportsRuntimeMode(Map<String, dynamic> args) async {
Future<bool> supportsRuntimeMode(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
@@ -949,7 +950,7 @@ class DeviceDomain extends Domain {
}
/// Creates an application package from a file in the temp directory.
Future<String> uploadApplicationPackage(Map<String, dynamic> args) async {
Future<String> uploadApplicationPackage(Map<String, Object?> args) async {
final TargetPlatform targetPlatform = getTargetPlatformForName(_getStringArg(args, 'targetPlatform', required: true)!);
final File applicationBinary = daemon.proxyDomain.tempDirectory.childFile(_getStringArg(args, 'applicationBinary', required: true)!);
final ApplicationPackage? applicationPackage = await ApplicationPackageFactory.instance!.getPackageForPlatform(
@@ -962,7 +963,7 @@ class DeviceDomain extends Domain {
}
/// Starts the log reader on the device.
Future<String> startLogReader(Map<String, dynamic> args) async {
Future<String> startLogReader(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
@@ -981,13 +982,13 @@ class DeviceDomain extends Domain {
}
/// Stops a log reader that was previously started.
Future<void> stopLogReader(Map<String, dynamic> args) async {
Future<void> stopLogReader(Map<String, Object?> args) async {
final String? id = _getStringArg(args, 'id', required: true);
_logReaders.remove(id)?.dispose();
}
/// Starts an app on a device.
Future<Map<String, dynamic>> startApp(Map<String, dynamic> args) async {
Future<Map<String, Object?>> startApp(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
@@ -1010,14 +1011,14 @@ class DeviceDomain extends Domain {
ipv6: _getBoolArg(args, 'ipv6') ?? false,
userIdentifier: _getStringArg(args, 'userIdentifier'),
);
return <String, dynamic>{
return <String, Object?>{
'started': result.started,
'observatoryUri': result.observatoryUri?.toString(),
};
}
/// Stops an app.
Future<bool> stopApp(Map<String, dynamic> args) async {
Future<bool> stopApp(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
@@ -1032,7 +1033,7 @@ class DeviceDomain extends Domain {
}
/// Takes a screenshot.
Future<String?> takeScreenshot(Map<String, dynamic> args) async {
Future<String?> takeScreenshot(Map<String, Object?> args) async {
final String? deviceId = _getStringArg(args, 'deviceId', required: true);
final Device? device = await daemon.deviceDomain._getDevice(deviceId);
if (device == null) {
@@ -1082,10 +1083,10 @@ class DevToolsDomain extends Domain {
DevtoolsLauncher? _devtoolsLauncher;
Future<Map<String, dynamic>> serve([ Map<String, dynamic>? args ]) async {
Future<Map<String, Object?>> serve([ Map<String, Object?>? args ]) async {
_devtoolsLauncher ??= DevtoolsLauncher.instance;
final DevToolsServerAddress? server = await _devtoolsLauncher?.serve();
return<String, dynamic>{
return<String, Object?>{
'host': server?.host,
'port': server?.port,
};
@@ -1097,8 +1098,8 @@ class DevToolsDomain extends Domain {
}
}
Future<Map<String, dynamic>> _deviceToMap(Device device) async {
return <String, dynamic>{
Future<Map<String, Object?>> _deviceToMap(Device device) async {
return <String, Object?>{
'id': device.id,
'name': device.name,
'platform': getNameForTargetPlatform(await device.targetPlatform),
@@ -1120,8 +1121,8 @@ Future<Map<String, dynamic>> _deviceToMap(Device device) async {
};
}
Map<String, dynamic> _emulatorToMap(Emulator emulator) {
return <String, dynamic>{
Map<String, Object?> _emulatorToMap(Emulator emulator) {
return <String, Object?>{
'id': emulator.id,
'name': emulator.name,
'category': emulator.category.toString(),
@@ -1129,15 +1130,15 @@ Map<String, dynamic> _emulatorToMap(Emulator emulator) {
};
}
Map<String, dynamic> _operationResultToMap(OperationResult result) {
return <String, dynamic>{
Map<String, Object?> _operationResultToMap(OperationResult result) {
return <String, Object?>{
'code': result.code,
'message': result.message,
};
}
Object? _toJsonable(dynamic obj) {
if (obj is String || obj is int || obj is bool || obj is Map<dynamic, dynamic> || obj is List<dynamic> || obj == null) {
Object? _toJsonable(Object? obj) {
if (obj is String || obj is int || obj is bool || obj is Map<Object?, Object?> || obj is List<Object?> || obj == null) {
return obj;
}
if (obj is OperationResult) {
@@ -1250,7 +1251,7 @@ class NotifyingLogger extends DelegatingLogger {
}
@override
void sendEvent(String name, [Map<String, dynamic>? args]) { }
void sendEvent(String name, [Map<String, Object?>? args]) { }
@override
bool get supportsColor => throw UnimplementedError();
@@ -1305,12 +1306,12 @@ class EmulatorDomain extends Domain {
androidWorkflow: androidWorkflow!,
);
Future<List<Map<String, dynamic>>> getEmulators([ Map<String, dynamic>? args ]) async {
Future<List<Map<String, Object?>>> getEmulators([ Map<String, Object?>? args ]) async {
final List<Emulator> list = await emulators.getAllAvailableEmulators();
return list.map<Map<String, dynamic>>(_emulatorToMap).toList();
return list.map<Map<String, Object?>>(_emulatorToMap).toList();
}
Future<void> launch(Map<String, dynamic> args) async {
Future<void> launch(Map<String, Object?> args) async {
final String emulatorId = _getStringArg(args, 'emulatorId', required: true)!;
final bool coldBoot = _getBoolArg(args, 'coldBoot') ?? false;
final List<Emulator> matches =
@@ -1324,10 +1325,10 @@ class EmulatorDomain extends Domain {
}
}
Future<Map<String, dynamic>> create(Map<String, dynamic> args) async {
Future<Map<String, Object?>> create(Map<String, Object?> args) async {
final String? name = _getStringArg(args, 'name');
final CreateEmulatorResult res = await emulators.createEmulator(name: name);
return <String, dynamic>{
return <String, Object?>{
'success': res.success,
'emulatorName': res.emulatorName,
'error': res.error,
@@ -1349,7 +1350,7 @@ class ProxyDomain extends Domain {
int _id = 0;
/// Writes to a file in a local temporary directory.
Future<void> writeTempFile(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<void> writeTempFile(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
await file.parent.create(recursive: true);
@@ -1357,7 +1358,7 @@ class ProxyDomain extends Domain {
}
/// Calculate rolling hashes for a file in the local temporary directory.
Future<Map<String, dynamic>?> calculateFileHashes(Map<String, dynamic> args) async {
Future<Map<String, Object?>?> calculateFileHashes(Map<String, Object?> args) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
if (!await file.exists()) {
@@ -1367,20 +1368,20 @@ class ProxyDomain extends Domain {
return result.toJson();
}
Future<bool?> updateFile(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<bool?> updateFile(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String path = _getStringArg(args, 'path', required: true)!;
final File file = tempDirectory.childFile(path);
if (!await file.exists()) {
return null;
}
final List<Map<String, dynamic>> deltaJson = (args['delta'] as List<dynamic>).cast<Map<String, dynamic>>();
final List<Map<String, Object?>> deltaJson = (args['delta']! as List<Object?>).cast<Map<String, Object?>>();
final List<FileDeltaBlock> delta = FileDeltaBlock.fromJsonList(deltaJson);
final bool result = await FileTransfer().rebuildFile(file, delta, binary!);
return result;
}
/// Opens a connection to a local port, and returns the connection id.
Future<String> connect(Map<String, dynamic> args) async {
Future<String> connect(Map<String, Object?> args) async {
final int targetPort = _getIntArg(args, 'port', required: true)!;
final String id = 'portForwarder_${targetPort}_${_id++}';
@@ -1406,22 +1407,22 @@ class ProxyDomain extends Domain {
_forwardedConnections[id] = socket;
socket.listen((List<int> data) {
sendEvent('proxy.data.$id', null, data);
}, onError: (dynamic error, StackTrace stackTrace) {
}, onError: (Object error, StackTrace stackTrace) {
// Socket error, probably disconnected.
globals.logger.printTrace('Socket error: $error, $stackTrace');
});
unawaited(socket.done.catchError((dynamic error, StackTrace stackTrace) {
unawaited(socket.done.catchError((Object error, StackTrace stackTrace) {
// Socket error, probably disconnected.
globals.logger.printTrace('Socket error: $error, $stackTrace');
}).then((dynamic _) {
}).then((Object? _) {
sendEvent('proxy.disconnected.$id');
}));
return id;
}
/// Disconnects from a previously established connection.
Future<bool> disconnect(Map<String, dynamic> args) async {
Future<bool> disconnect(Map<String, Object?> args) async {
final String? id = _getStringArg(args, 'id', required: true);
if (_forwardedConnections.containsKey(id)) {
await _forwardedConnections.remove(id)?.close();
@@ -1431,7 +1432,7 @@ class ProxyDomain extends Domain {
}
/// Writes to a previously established connection.
Future<bool> write(Map<String, dynamic> args, Stream<List<int>>? binary) async {
Future<bool> write(Map<String, Object?> args, Stream<List<int>>? binary) async {
final String? id = _getStringArg(args, 'id', required: true);
if (_forwardedConnections.containsKey(id)) {
final StreamSubscription<List<int>> subscription = binary!.listen(_forwardedConnections[id!]!.add);
@@ -1519,7 +1520,7 @@ class AppRunLogger extends DelegatingLogger {
printStatus(message);
}
} else {
final Map<String, dynamic> event = <String, dynamic>{
final Map<String, Object?> event = <String, Object?>{
'id': eventId,
'progressId': eventType,
if (message != null) 'message': message,
@@ -1531,7 +1532,7 @@ class AppRunLogger extends DelegatingLogger {
}
@override
void sendEvent(String name, [Map<String, dynamic>? args, List<int>? binary]) {
void sendEvent(String name, [Map<String, Object?>? args, List<int>? binary]) {
if (domain == null) {
printStatus('event sent after app closed: $name');
} else {

View File

@@ -81,14 +81,14 @@ const String kExitMessage = 'Failed to establish connection with the application
class ResidentWebRunner extends ResidentRunner {
ResidentWebRunner(
FlutterDevice? device, {
FlutterDevice device, {
String? target,
bool stayResident = true,
bool machine = false,
required this.flutterProject,
required bool? ipv6,
required DebuggingOptions debuggingOptions,
required FileSystem? fileSystem,
required FileSystem fileSystem,
required Logger? logger,
required SystemClock systemClock,
required Usage usage,
@@ -100,8 +100,8 @@ class ResidentWebRunner extends ResidentRunner {
_usage = usage,
_urlTunneller = urlTunneller,
super(
<FlutterDevice?>[device],
target: target ?? fileSystem!.path.join('lib', 'main.dart'),
<FlutterDevice>[device],
target: target ?? fileSystem.path.join('lib', 'main.dart'),
debuggingOptions: debuggingOptions,
ipv6: ipv6,
stayResident: stayResident,
@@ -109,7 +109,7 @@ class ResidentWebRunner extends ResidentRunner {
devtoolsHandler: devtoolsHandler,
);
final FileSystem? _fileSystem;
final FileSystem _fileSystem;
final Logger? _logger;
final SystemClock _systemClock;
final Usage _usage;
@@ -119,7 +119,7 @@ class ResidentWebRunner extends ResidentRunner {
Logger? get logger => _logger;
@override
FileSystem? get fileSystem => _fileSystem;
FileSystem get fileSystem => _fileSystem;
FlutterDevice? get device => flutterDevices.first;
final FlutterProject flutterProject;
@@ -245,7 +245,7 @@ class ResidentWebRunner extends ResidentRunner {
}
final String modeName = debuggingOptions.buildInfo.friendlyModeName;
_logger!.printStatus(
'Launching ${getDisplayPath(target, _fileSystem!)} '
'Launching ${getDisplayPath(target, _fileSystem)} '
'on ${device!.device!.name} in $modeName mode...',
);
if (device!.device is ChromiumDevice) {
@@ -271,7 +271,7 @@ class ResidentWebRunner extends ResidentRunner {
buildInfo: debuggingOptions.buildInfo,
enableDwds: _enableDwds,
enableDds: debuggingOptions.enableDds,
entrypoint: _fileSystem!.file(target).uri,
entrypoint: _fileSystem.file(target).uri,
expressionCompiler: expressionCompiler,
chromiumLauncher: _chromiumLauncher,
nullAssertions: debuggingOptions.nullAssertions,
@@ -425,7 +425,7 @@ class ResidentWebRunner extends ResidentRunner {
Future<Uri> _generateEntrypoint(Uri mainUri, PackageConfig? packageConfig) async {
File? result = _generatedEntrypointDirectory?.childFile('web_entrypoint.dart');
if (_generatedEntrypointDirectory == null) {
_generatedEntrypointDirectory ??= _fileSystem!.systemTempDirectory.createTempSync('flutter_tools.')
_generatedEntrypointDirectory ??= _fileSystem.systemTempDirectory.createTempSync('flutter_tools.')
..createSync();
result = _generatedEntrypointDirectory!.childFile('web_entrypoint.dart');
@@ -438,16 +438,17 @@ class ResidentWebRunner extends ResidentRunner {
Uri? importedEntrypoint = packageConfig!.toPackageUri(mainUri);
// Special handling for entrypoints that are not under lib, such as test scripts.
if (importedEntrypoint == null) {
final String parent = _fileSystem!.file(mainUri).parent.path;
flutterDevices.first!.generator!.addFileSystemRoot(parent);
flutterDevices.first!.generator!.addFileSystemRoot(_fileSystem!.directory('test').absolute.path);
final String parent = _fileSystem.file(mainUri).parent.path;
flutterDevices.first.generator!
..addFileSystemRoot(parent)
..addFileSystemRoot(_fileSystem.directory('test').absolute.path);
importedEntrypoint = Uri(
scheme: 'org-dartlang-app',
path: '/${mainUri.pathSegments.last}',
);
}
final LanguageVersion languageVersion = determineLanguageVersion(
_fileSystem!.file(mainUri),
_fileSystem.file(mainUri),
packageConfig[flutterProject.manifest.appName],
Cache.flutterRoot!,
);
@@ -487,7 +488,7 @@ class ResidentWebRunner extends ResidentRunner {
);
final UpdateFSReport report = await device!.devFS!.update(
mainUri: await _generateEntrypoint(
_fileSystem!.file(mainPath).absolute.uri,
_fileSystem.file(mainPath).absolute.uri,
invalidationResult.packageConfig,
),
target: target,
@@ -603,7 +604,7 @@ class ResidentWebRunner extends ResidentRunner {
}
if (websocketUri != null) {
if (debuggingOptions.vmserviceOutFile != null) {
_fileSystem!.file(debuggingOptions.vmserviceOutFile)
_fileSystem.file(debuggingOptions.vmserviceOutFile)
..createSync(recursive: true)
..writeAsStringSync(websocketUri.toString());
}

View File

@@ -240,7 +240,7 @@ class FlutterDevice {
bool cacheStartupProfile = false,
bool enableDds = true,
required bool allowExistingDdsInstance,
bool? ipv6 = false,
bool ipv6 = false,
}) {
final Completer<void> completer = Completer<void>();
late StreamSubscription<void> subscription;
@@ -927,14 +927,14 @@ abstract class ResidentHandlers {
if (!supportsWriteSkSL) {
throw Exception('writeSkSL is not supported by this runner.');
}
final List<FlutterView> views = await flutterDevices
.first!
.vmService!.getFlutterViews();
final Map<String, Object> data = await (flutterDevices.first!.vmService!.getSkSLs(
final FlutterDevice flutterDevice = flutterDevices.first!;
final FlutterVmService vmService = flutterDevice.vmService!;
final List<FlutterView> views = await vmService.getFlutterViews();
final Map<String, Object?>? data = await vmService.getSkSLs(
viewId: views.first.id,
) as FutureOr<Map<String, Object>>);
final Device device = flutterDevices.first!.device!;
return sharedSkSlWriter(device, data);
);
final Device device = flutterDevice.device!;
return sharedSkSlWriter(device, data!);
}
/// Take a screenshot on the provided [device].
@@ -1091,10 +1091,10 @@ abstract class ResidentRunner extends ResidentHandlers {
Logger? get logger => globals.logger;
@override
FileSystem? get fileSystem => globals.fs;
FileSystem get fileSystem => globals.fs;
@override
final List<FlutterDevice?> flutterDevices;
final List<FlutterDevice> flutterDevices;
final String target;
final DebuggingOptions debuggingOptions;
@@ -1171,7 +1171,7 @@ abstract class ResidentRunner extends ResidentHandlers {
//
// Would be null if there is no device connected or
// there is no devFS associated with the first device.
Uri? get uri => flutterDevices.first?.devFS?.baseUri;
Uri? get uri => flutterDevices.first.devFS?.baseUri;
/// Returns [true] if the resident runner exited after invoking [exit()].
bool get exited => _exited;
@@ -1257,7 +1257,7 @@ abstract class ResidentRunner extends ResidentHandlers {
void writeVmServiceFile() {
if (debuggingOptions.vmserviceOutFile != null) {
try {
final String address = flutterDevices.first!.vmService!.wsAddress.toString();
final String address = flutterDevices.first.vmService!.wsAddress.toString();
final File vmserviceOutFile = globals.fs.file(debuggingOptions.vmserviceOutFile);
vmserviceOutFile.createSync(recursive: true);
vmserviceOutFile.writeAsStringSync(address);
@@ -1359,7 +1359,7 @@ abstract class ResidentRunner extends ResidentHandlers {
hostVmServicePort: debuggingOptions.hostVmServicePort,
getSkSLMethod: getSkSLMethod,
printStructuredErrorLogMethod: printStructuredErrorLog,
ipv6: ipv6,
ipv6: ipv6 ?? false,
disableServiceAuthCodes: debuggingOptions.disableServiceAuthCodes,
cacheStartupProfile: debuggingOptions.cacheStartupProfile,
);

View File

@@ -88,11 +88,11 @@ class ColdRunner extends ResidentRunner {
));
}
if (flutterDevices.first!.observatoryUris != null) {
if (flutterDevices.first.observatoryUris != null) {
// For now, only support one debugger connection.
connectionInfoCompleter?.complete(DebugConnectionInfo(
httpUri: flutterDevices.first!.vmService!.httpAddress,
wsUri: flutterDevices.first!.vmService!.wsAddress,
httpUri: flutterDevices.first.vmService!.httpAddress,
wsUri: flutterDevices.first.vmService!.wsAddress,
));
}
@@ -108,7 +108,7 @@ class ColdRunner extends ResidentRunner {
if (traceStartup) {
// Only trace startup for the first device.
final FlutterDevice device = flutterDevices.first!;
final FlutterDevice device = flutterDevices.first;
if (device.vmService != null) {
globals.printStatus('Tracing startup on ${device.device!.name}.');
final String outputPath = globals.platform.environment[kFlutterTestOutputsDirEnvName] ?? getBuildDirectory();

View File

@@ -141,7 +141,7 @@ class HotRunner extends ResidentRunner {
}
if (flutterDevices.length == 1) {
final Device device = flutterDevices.first!.device!;
final Device device = flutterDevices.first.device!;
_targetPlatform = getNameForTargetPlatform(await device.targetPlatform);
_sdkName = await device.sdkNameAndVersion;
_emulator = await device.isLocalEmulator;
@@ -257,8 +257,8 @@ class HotRunner extends ResidentRunner {
// Only handle one debugger connection.
connectionInfoCompleter.complete(
DebugConnectionInfo(
httpUri: flutterDevices.first!.vmService!.httpAddress,
wsUri: flutterDevices.first!.vmService!.wsAddress,
httpUri: flutterDevices.first.vmService!.httpAddress,
wsUri: flutterDevices.first.vmService!.wsAddress,
baseUri: baseUris.first.toString(),
),
);
@@ -454,12 +454,13 @@ class HotRunner extends ResidentRunner {
}
final Stopwatch findInvalidationTimer = _stopwatchFactory.createStopwatch('updateDevFS')..start();
final DevFS devFS = flutterDevices[0].devFS!;
final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated(
lastCompiled: flutterDevices[0]!.devFS!.lastCompiled,
urisToMonitor: flutterDevices[0]!.devFS!.sources,
lastCompiled: devFS.lastCompiled,
urisToMonitor: devFS.sources,
packagesPath: packagesFilePath,
asyncScanning: hotRunnerConfig!.asyncScanning,
packageConfig: flutterDevices[0]!.devFS!.lastPackageConfig
packageConfig: devFS.lastPackageConfig
?? debuggingOptions.buildInfo.packageConfig,
);
findInvalidationTimer.stop();
@@ -474,7 +475,7 @@ class HotRunner extends ResidentRunner {
}
final UpdateFSReport results = UpdateFSReport(
success: true,
scannedSourcesCount: flutterDevices[0]!.devFS!.sources.length,
scannedSourcesCount: devFS.sources.length,
findInvalidatedDuration: findInvalidationTimer.elapsed,
);
for (final FlutterDevice? device in flutterDevices) {
@@ -497,21 +498,27 @@ class HotRunner extends ResidentRunner {
}
void _resetDirtyAssets() {
for (final FlutterDevice? device in flutterDevices) {
device!.devFS!.assetPathsToEvict.clear();
device.devFS!.shaderPathsToEvict.clear();
for (final FlutterDevice device in flutterDevices) {
final DevFS? devFS = device.devFS;
if (devFS == null) {
// This is sometimes null, however we don't know why and have not been
// able to reproduce, https://github.com/flutter/flutter/issues/108653
continue;
}
devFS.assetPathsToEvict.clear();
devFS.shaderPathsToEvict.clear();
}
}
Future<void> _cleanupDevFS() async {
final List<Future<void>> futures = <Future<void>>[];
for (final FlutterDevice? device in flutterDevices) {
if (device!.devFS != null) {
for (final FlutterDevice device in flutterDevices) {
if (device.devFS != null) {
// Cleanup the devFS, but don't wait indefinitely.
// We ignore any errors, because it's not clear what we would do anyway.
futures.add(device.devFS!.destroy()
.timeout(const Duration(milliseconds: 250))
.catchError((dynamic error) {
.catchError((Object? error) {
globals.printTrace('Ignored error while cleaning up DevFS: $error');
}));
}
@@ -756,7 +763,7 @@ class HotRunner extends ResidentRunner {
String? restartEvent;
try {
final Stopwatch restartTimer = _stopwatchFactory.createStopwatch('fullRestartHelper')..start();
if (!(await (hotRunnerConfig!.setupHotRestart() as FutureOr<bool>))) {
if ((await hotRunnerConfig!.setupHotRestart()) != true) {
return OperationResult(1, 'setupHotRestart failed');
}
result = await _restartFromSources(reason: reason);
@@ -885,7 +892,7 @@ class HotRunner extends ResidentRunner {
}
final Stopwatch reloadTimer = _stopwatchFactory.createStopwatch('reloadSources:reload')..start();
if (!(await (hotRunnerConfig!.setupHotReload() as FutureOr<bool>))) {
if ((await hotRunnerConfig!.setupHotReload()) != true) {
return OperationResult(1, 'setupHotReload failed');
}
final Stopwatch devFSTimer = Stopwatch()..start();

View File

@@ -13,7 +13,7 @@ import 'convert.dart';
import 'device.dart';
import 'globals.dart' as globals;
Future<String?> sharedSkSlWriter(Device device, Map<String, Object> data, {
Future<String?> sharedSkSlWriter(Device device, Map<String, Object?> data, {
File? outputFile,
Logger? logger,
}) async {

View File

@@ -493,7 +493,7 @@ class FlutterVmService {
///
/// This method will only return data if `--cache-sksl` was provided as a
/// flutter run argument, and only then on physical devices.
Future<Map<String, Object>?> getSkSLs({
Future<Map<String, Object?>?> getSkSLs({
required String viewId,
}) async {
final vm_service.Response? response = await callMethodWrapper(
@@ -505,7 +505,7 @@ class FlutterVmService {
if (response == null) {
return null;
}
return response.json?['SkSLs'] as Map<String, Object>?;
return response.json?['SkSLs'] as Map<String, Object?>?;
}
/// Flush all tasks on the UI thread for an attached Flutter view.