launchApp method

Future<({Process process, Uri uri})> launchApp({
  1. required String projectDir,
  2. required String deviceId,
  3. Uri? attachTo,
  4. Duration timeout = const Duration(seconds: 180),
  5. Duration poll = const Duration(seconds: 2),
  6. Duration progressEvery = const Duration(seconds: 15),
  7. void onProgress(
    1. int elapsedSec,
    2. String? phase
    )?,
  8. Map<String, String>? environment,
  9. Future<void> whileWaiting()?,
})

flutter run projectDir on deviceId, or with attachTo flutter attach to the app already serving that VM URI; returns the tool's VM URI + live process, throws LaunchError on failure/timeout.

Implementation

Future<({Uri uri, Process process})> launchApp({
  required String projectDir,
  required String deviceId,
  Uri? attachTo,
  Duration timeout = const Duration(seconds: 180),
  Duration poll = const Duration(seconds: 2),
  Duration progressEvery = const Duration(seconds: 15),
  void Function(int elapsedSec, String? phase)? onProgress,
  Map<String, String>? environment,
  Future<void> Function()? whileWaiting,
}) async {
  final verb = attachTo == null ? 'run' : 'attach';
  final Process proc;
  try {
    proc = await startHelper(
      'flutter-run',
      flutterPath,
      [
        verb,
        '-d',
        deviceId,
        if (attachTo != null) ...['--debug-url', '$attachTo']
      ],
      device: deviceId,
      owner: projectDir,
      label: 'flutter $verb',
      workingDirectory: projectDir,
      environment: environment,
    );
  } on Object catch (e) {
    throw LaunchError('could not start `$flutterPath $verb`: $e');
  }
  var exited = false;
  unawaited(proc.exitCode.then((_) => exited = true));

  // Bounded — the listeners keep draining for the app's whole life (the
  // process outlives this call for kill_app), so accumulate only the tail.
  final out = _BoundedLog();
  proc.stdout.transform(utf8.decoder).listen(out.add);
  proc.stderr.transform(utf8.decoder).listen(out.add);

  return CallProgress.during(
    attachTo == null ? 'flutter run: building and launching the app' : 'flutter attach: connecting to the app',
    key: 'launch',
    () async {
      final start = DateTime.now();
      final deadline = start.add(timeout);
      var nextUpdate = start.add(progressEvery);
      while (DateTime.now().isBefore(deadline)) {
        await Future<void>.delayed(poll);
        CallProgress.checkAlive();
        final text = out.text;
        final uri = vmUriPattern.firstMatch(text)?.group(0);
        if (uri != null) {
          final parsed = Uri.tryParse(uri);
          if (parsed != null) return (uri: parsed, process: proc);
        }
        if (exited || _looksFailed(text)) {
          await killProcessTree(proc);
          throw LaunchError(
              'flutter $verb failed: ${failureLine(text) ?? 'see the log tail for what flutter reported'}',
              logTail: _tail(text),
              signing: _signingFailed(text));
        }
        if (whileWaiting != null && text.contains('Installing and launching')) await whileWaiting();
        final now = DateTime.now();
        if (onProgress != null && now.isAfter(nextUpdate)) {
          onProgress(now.difference(start).inSeconds, _phase(text));
          nextUpdate = now.add(progressEvery);
        }
      }
      await killProcessTree(proc);
      final phase = _phase(out.text);
      final reported = failureLine(out.text);
      throw LaunchError(
        'timed out after ${timeout.inSeconds}s waiting for the VM service'
        '${phase == null ? "" : " (last: $phase)"}'
        '${reported == null ? "" : "; flutter reported: $reported"}',
        logTail: _tail(out.text),
      );
    },
  );
}