connect method

Future<FlutterDriver> connect (
  1. {String dartVmServiceUrl,
  2. bool printCommunication: false,
  3. bool logCommunicationToFile: true,
  4. int isolateNumber,
  5. Pattern fuchsiaModuleTarget}

Connects to a Flutter application.

Resumes the application if it is currently paused (e.g. at a breakpoint).

dartVmServiceUrl is the URL to Dart observatory (a.k.a. VM service). If not specified, the URL specified by the VM_SERVICE_URL environment variable is used. One or the other must be specified.

printCommunication determines whether the command communication between the test and the app should be printed to stdout.

logCommunicationToFile determines whether the command communication between the test and the app should be logged to flutter_driver_commands.log.

isolateNumber determines the specific isolate to connect to. If this is left as null, will connect to the first isolate found running on dartVmServiceUrl.

fuchsiaModuleTarget specifies the pattern for determining which mod to control. When running on a Fuchsia device, either this or the environment variable FUCHSIA_MODULE_TARGET must be set (the environment variable is treated as a substring pattern). This field will be ignored if isolateNumber is set, as this is already enough information to connect to an isolate.

The return value is a future. This method never times out, though it may fail (completing with an error). A timeout can be applied by the caller using Future.timeout if necessary.


static Future<FlutterDriver> connect({
  String dartVmServiceUrl,
  bool printCommunication = false,
  bool logCommunicationToFile = true,
  int isolateNumber,
  Pattern fuchsiaModuleTarget,
}) async {
  // If running on a Fuchsia device, connect to the first isolate whose name
  // If the user has already supplied an isolate number/URL to the Dart VM
  // service, then this won't be run as it is unnecessary.
  if (Platform.isFuchsia && isolateNumber == null) {
    // TODO(awdavies): Use something other than print. On fuchsia
    // `stderr`/`stdout` appear to have issues working correctly.
    fuchsiaModuleTarget ??= Platform.environment['FUCHSIA_MODULE_TARGET'];
    if (fuchsiaModuleTarget == null) {
      throw DriverError(
        'No Fuchsia module target has been specified.\n'
        'Please make sure to specify the FUCHSIA_MODULE_TARGET '
        'environment variable.'
    final fuchsia.FuchsiaRemoteConnection fuchsiaConnection =
        await FuchsiaCompat.connect();
    final List<fuchsia.IsolateRef> refs =
        await fuchsiaConnection.getMainIsolatesByPattern(fuchsiaModuleTarget);
    final fuchsia.IsolateRef ref = refs.first;
    isolateNumber = ref.number;
    dartVmServiceUrl = ref.dartVm.uri.toString();
    await fuchsiaConnection.stop();

  dartVmServiceUrl ??= Platform.environment['VM_SERVICE_URL'];

  if (dartVmServiceUrl == null) {
    throw DriverError(
      'Could not determine URL to connect to application.\n'
      'Either the VM_SERVICE_URL environment variable should be set, or an explicit '
      'URL should be provided to the FlutterDriver.connect() method.'

  // Connect to Dart VM services'Connecting to Flutter application at $dartVmServiceUrl');
  final VMServiceClientConnection connection =
      await vmServiceConnectFunction(dartVmServiceUrl);
  final VMServiceClient client = connection.client;
  final VM vm = await client.getVM();
  final VMIsolateRef isolateRef = isolateNumber ==
      null ? vm.isolates.first :
                 (VMIsolateRef isolate) => isolate.number == isolateNumber);
  _log.trace('Isolate found with number: ${isolateRef.number}');

  VMIsolate isolate = await isolateRef.loadRunnable();

  // TODO(yjbanov): vm_service_client does not support "None" pause event yet.
  // It is currently reported as null, but we cannot rely on it because
  // eventually the event will be reported as a non-null object. For now,
  // list all the events we know about. Later we'll check for "None" event
  // explicitly.
  // See:
  if (isolate.pauseEvent is! VMPauseStartEvent &&
      isolate.pauseEvent is! VMPauseExitEvent &&
      isolate.pauseEvent is! VMPauseBreakpointEvent &&
      isolate.pauseEvent is! VMPauseExceptionEvent &&
      isolate.pauseEvent is! VMPauseInterruptedEvent &&
      isolate.pauseEvent is! VMResumeEvent) {
    isolate = await isolateRef.loadRunnable();

  final FlutterDriver driver = FlutterDriver.connectedTo(
    client, connection.peer, isolate,
    printCommunication: printCommunication,
    logCommunicationToFile: logCommunicationToFile,

  driver._dartVmReconnectUrl = dartVmServiceUrl;

  // Attempts to resume the isolate, but does not crash if it fails because
  // the isolate is already resumed. There could be a race with other tools,
  // such as a debugger, any of which could have resumed the isolate.
  Future<dynamic> resumeLeniently() {
    _log.trace('Attempting to resume isolate');
    return isolate.resume().catchError((dynamic e) {
      const int vmMustBePausedCode = 101;
      if (e is rpc.RpcException && e.code == vmMustBePausedCode) {
        // No biggie; something else must have resumed the isolate
          'Attempted to resume an already resumed isolate. This may happen '
          'when we lose a race with another tool (usually a debugger) that '
          'is connected to the same isolate.'
      } else {
        // Failed to resume due to another reason. Fail hard.
        throw e;

  /// Waits for a signal from the VM service that the extension is registered.
  /// Returns [_flutterExtensionMethodName]
  Future<String> waitForServiceExtension() {
    return isolate.onExtensionAdded.firstWhere((String extension) {
      return extension == _flutterExtensionMethodName;

  /// Tells the Dart VM Service to notify us about "Isolate" events.
  /// This is a workaround for an issue in package:vm_service_client, which
  /// subscribes to the "Isolate" stream lazily upon subscription, which
  /// results in lost events.
  /// Details:
  Future<void> enableIsolateStreams() async {
    await connection.peer.sendRequest('streamListen', <String, String>{
      'streamId': 'Isolate',

  // Attempt to resume isolate if it was paused
  if (isolate.pauseEvent is VMPauseStartEvent) {
    _log.trace('Isolate is paused at start.');

    // If the isolate is paused at the start, e.g. via the --start-paused
    // option, then the VM service extension is not registered yet. Wait for
    // it to be registered.
    await enableIsolateStreams();
    final Future<String> whenServiceExtensionReady = waitForServiceExtension();
    final Future<dynamic> whenResumed = resumeLeniently();
    await whenResumed;

    _log.trace('Waiting for service extension');
    // We will never receive the extension event if the user does not
    // register it. If that happens, show a message but continue waiting.
    await _warnIfSlow<String>(
      future: whenServiceExtensionReady,
      timeout: kUnusuallyLongTimeout,
      message: 'Flutter Driver extension is taking a long time to become available. '
               'Ensure your test app (often "lib/main.dart") imports '
               '"package:flutter_driver/driver_extension.dart" and '
               'calls enableFlutterDriverExtension() as the first call in main().',
  } else if (isolate.pauseEvent is VMPauseExitEvent ||
             isolate.pauseEvent is VMPauseBreakpointEvent ||
             isolate.pauseEvent is VMPauseExceptionEvent ||
             isolate.pauseEvent is VMPauseInterruptedEvent) {
    // If the isolate is paused for any other reason, assume the extension is
    // already there.
    _log.trace('Isolate is paused mid-flight.');
    await resumeLeniently();
  } else if (isolate.pauseEvent is VMResumeEvent) {
    _log.trace('Isolate is not paused. Assuming application is ready.');
  } else {
      'Unknown pause event type ${isolate.pauseEvent.runtimeType}. '
      'Assuming application is ready.'

  // Invoked checkHealth and try to fix delays in the registration of Service
  // extensions
  Future<Health> checkHealth() async {
    try {
      // At this point the service extension must be installed. Verify it.
      return await driver.checkHealth();
    } on rpc.RpcException catch (e) {
      if (e.code != error_code.METHOD_NOT_FOUND) {
        'Check Health failed, try to wait for the service extensions to be'
      await enableIsolateStreams();
      await waitForServiceExtension();
      return driver.checkHealth();

  final Health health = await checkHealth();
  if (health.status != HealthStatus.ok) {
    await client.close();
    throw DriverError('Flutter application health check failed.');
  }'Connected to Flutter application.');
  return driver;