runNativeApp function

void runNativeApp(
  1. void main()
)

Runs a desktop app from a plain Dart program (dart run), without Flutter.

Import this helper through package:nativeapi/standalone.dart. It requires experimental VM APIs available in Dart 3.13 and is not supported on Dart 3.14. The ordinary nativeapi and Flutter entrypoints do not import it.

main builds the app: it creates windows and views and registers listeners. It runs in a new isolate that lives on the platform's UI thread, where every call into nativeapi and every event callback then happens, while that isolate's timers, futures and streams keep working as usual. Pass a top-level or static function: it crosses into the new isolate, so it must not capture state.

The process ends when the app quits: through Application.instance.quit(), with its exit code, or when the user quits it from the Dock or with Cmd+Q. Listeners registered in main still get ApplicationExitingEvent first. The process then ends at once, without the teardown exit() from dart:io would run (the Dart VM's threads are still busy): windows and tray icons go with it. An uncaught error in the app prints and exits with status 255, as it would in the main isolate.

Call it at most once, from main(), before anything else in nativeapi: the objects nativeapi hands out belong to the thread that created them.

On macOS AppKit only works on the process's first thread, which the Dart VM keeps parked while main() runs elsewhere; the app takes that thread over. On Windows and Linux it gets a thread of its own. Not for Flutter, whose engine already runs the loop, nor for Android or iOS: throws a StateError there.

Implementation

void runNativeApp(void Function() main) {
  // Only final locals can be captured by a callback bound to the group.
  final appMain = main;
  final entry = ffi.NativeCallable<ffi.Void Function()>.isolateGroupBound(() {
    // Isolate.create, runSync and runEventLoopSync were Dart 3.13's
    // experimental VM APIs; Dart 3.14 removed them. Kept until the runner is
    // ported or removed, so analysis of this package stays clean meanwhile.
    // ignore: undefined_method
    final app = Isolate.create(debugName: 'nativeapi');
    app.runSync(() => _start(appMain));
    // Returns once the app isolate has nothing left to run for.
    app.runEventLoopSync();
  });
  if (!c.cnativeapi_run_ui_thread(entry.nativeFunction)) {
    entry.close();
    throw StateError(
      'runNativeApp: no UI thread to run on. It runs once per process, from a '
      'plain Dart program on macOS, Windows or Linux.',
    );
  }
  // The app isolate ends the process; until then this isolate stays up, and
  // with it `entry`, which the UI thread is still inside.
  RawReceivePort(null, 'runNativeApp');
}