Sub topic 12
Calling plugins from a background isolate
This chapter assumes you know Isolate.run, Isolate.spawn, and ports from the earlier chapters. It also assumes you know what a Flutter plugin is: a package with Dart code that talks to Android, iOS, or desktop code through platform channels. You should be comfortable with async/await.
The problem: channels belong to the root isolate
A new isolate has its own heap and runs none of Flutter's startup code. Flutter's services layer (the code behind MethodChannel) sends messages to the platform through a binding that exists only in the root isolate, the isolate that runs main(). A background isolate has no such binding. A plugin call made there fails.
Since Flutter 3.7 you can fix this by giving the background isolate a way to reach the platform. The mechanism has two parts:
RootIsolateTokenis an identifier for the root isolate.RootIsolateToken.instancereturns it, but only when read on the root isolate. On any other isolate it isnull.BackgroundIsolateBinaryMessenger.ensureInitialized(token)registers the background isolate with the engine. After that,MethodChannel,EventChannel, andBasicMessageChannelcalls made in that isolate are routed to the platform side.
Without the second step, the first channel call throws a StateError that says BackgroundIsolateBinaryMessenger.instance is not valid until ensureInitialized has run.
The pattern with Isolate.run
Read the token before starting the isolate, capture it in the closure, and initialize the messenger first thing inside the closure.
import 'dart:io';
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
Future<int> writeReport(String contents) async {
final token = RootIsolateToken.instance;
if (token == null) {
throw StateError('writeReport must be called from the root isolate.');
}
return Isolate.run(() async {
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/report.txt');
await file.writeAsString(contents);
return await file.length();
});
}Points to notice:
- The token is a local variable, so the closure captures only it and
contents. The closure-capture rules from the earlier chapter still apply.RootIsolateTokenis a small object that can be sent between isolates. ensureInitializedis called before any plugin call. Put it on the first line so you do not forget it when you add code later.- The closure is
async.Isolate.runaccepts aFutureOrresult and waits for it before sending the value back. - The null check gives a clear error when someone calls the function from a background isolate. The spine example uses
!, which is fine if you are sure, but a named error is easier to debug.
What the plugin does in the background
The heavy part of this example is the file write. The plugin call (getApplicationDocumentsDirectory) is only a short question to the platform. This is the usual shape of plugin work in an isolate. You use plugins for the inputs and outputs of a long computation: finding a directory, reading a preference, calling a native decoder. The isolate keeps the Dart-side loop and the file or data handling off the UI isolate.
A long-lived worker that uses plugins
With Isolate.spawn you pass the token yourself, because the entry function receives only one message argument. A record bundles the token and the reply port:
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
typedef _Init = (RootIsolateToken, SendPort);
Future<void> _pathWorker(_Init init) async {
final (token, toMain) = init;
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
final commands = ReceivePort();
toMain.send(commands.sendPort);
commands.listen((message) async {
if (message == null) {
commands.close();
return;
}
final (id, _) = message as (int, String);
final dir = await getTemporaryDirectory();
toMain.send((id, dir.path));
});
}
Future<void> demo() async {
final token = RootIsolateToken.instance!;
final fromWorker = ReceivePort();
await Isolate.spawn<_Init>(_pathWorker, (token, fromWorker.sendPort));
final events = StreamIterator<dynamic>(fromWorker);
await events.moveNext();
final toWorker = events.current as SendPort;
toWorker.send((1, 'temp'));
await events.moveNext();
final (id, path) = events.current as (int, String);
print('request $id -> $path');
toWorker.send(null);
fromWorker.close();
}This follows the handshake from the long-lived worker chapter: the worker sends its own SendPort first, then answers requests, then stops on null. The only additions are the token in the start message and the ensureInitialized call before the port setup. Calling ensureInitialized once per isolate is enough. The registration lasts as long as the isolate does.
The message as (int, String) pattern is a record cast. The second field is unused here. It exists so you can see how a real request would carry parameters.
A custom channel works the same way
You do not need a published plugin. Any channel you define yourself can be used from a background isolate, as long as you create it inside that isolate or create it in a way that does not capture the root binding:
import 'dart:isolate';
import 'package:flutter/services.dart';
Future<int?> readBatteryInBackground() async {
final token = RootIsolateToken.instance!;
return Isolate.run(() async {
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
const channel = MethodChannel('com.example.app/battery');
return await channel.invokeMethod<int>('getLevel');
});
}On the native side, a handler for com.example.app/battery registered in the usual way answers this call. The native code does not need to know which isolate asked. Replies are routed back to the isolate that sent the request.
What works and what does not
Background isolates get one-way access: Dart can call the platform. The reverse direction and most of Flutter's UI layer are not available.
| Capability in a background isolate | Supported? | Notes |
|---|---|---|
| `MethodChannel.invokeMethod` to the platform | Yes | After `ensureInitialized` |
| `EventChannel` and `BasicMessageChannel` sends | Yes | Same requirement |
| Platform calling into Dart (`setMethodCallHandler`) | No | Handlers on a background isolate are not supported. Keep them on the root isolate |
| Widgets, `rootBundle`, `dart:ui` rendering | No | These need the root isolate's bindings |
| Plugins that use only FFI or pure Dart | Yes | No token needed |
| Plugins with their own native threading assumptions | Depends | Read the plugin's documentation |
Support depends on the plugin
Calling a plugin from a background isolate works only if the plugin's Dart code uses the default binary messenger and does not depend on root-isolate state. Plugins written in the usual way (a MethodChannel constructed without a custom messenger) work. A plugin that stores state in a static field on the root isolate, or that registers a callback for the platform to call, does not. Because each isolate has its own heap, a static singleton that a plugin initialized in the root isolate is not initialized in the background isolate. The plugin may need its own setup call there too.
Federated plugins (packages where each platform has its own Dart implementation package) can need one more step. Their platform implementation registers itself with the plugin's interface package through generated registration code. Flutter runs that code for the root isolate. A plugin that depends on it may not be registered in your background isolate, and calls then fail with an "unimplemented" error. Some plugins document DartPluginRegistrant.ensureInitialized() (from dart:ui) for this case. Check the plugin's README and changelog for "background isolate" before relying on it.
Common errors
- Reading the token in the wrong place.
RootIsolateToken.instanceisnulloutside the root isolate. If you read it inside theIsolate.runclosure,!throws. Read it before starting the isolate and capture the variable. - Forgetting
ensureInitialized. The first channel call throws theStateErrordescribed above. Calling it late, after another plugin call, has the same effect for that earlier call. - Calling it on the root isolate.
ensureInitializedis for background isolates. You never need it inmain(). - Expecting platform callbacks. If the native side needs to push events, use an
EventChannellistened to on the root isolate, and forward the events to the worker through a port. - Running in tests. In a plain
flutter testrun there may be no root isolate token (instanceisnull) and no platform side to answer. Wrap plugin access behind your own interface and fake it in tests, as you would for any plugin call. - Web. On Flutter web there is no background isolate to initialize.
Isolate.runis not supported there, andcomputeruns the work on the main thread. Platform-channel plugins on web work as normal, with no token. Isolate-based plugin code needs a conditional import or a platform check so it does not run on web.
Design advice
Keep the plugin calls thin and the isolate boundary clear:
- Call the plugin in the isolate only when the plugin result feeds directly into the heavy work. If the plugin returns a small value (a directory path, a setting), it is often simpler to call it on the root isolate and pass the value in as an argument. That avoids all the token handling.
- Choose one entry point per worker that calls
ensureInitialized. Do not scatter it through helper functions. - Send results back as plain data (strings, numbers, lists, records). Do not send plugin objects between isolates.
Exercise
You call RootIsolateToken.instance! inside the closure passed to Isolate.run, then call BackgroundIsolateBinaryMessenger.ensureInitialized(token). The call throws. Why, and how do you fix it?
Show answer
RootIsolateToken.instance returns a value only on the root isolate. Inside the closure, the code runs on the new isolate, so it is null and the ! throws. Read the token on the root isolate before calling Isolate.run, store it in a local variable, and let the closure capture that variable.
Exercise
A plugin you use registers a handler with setMethodCallHandler so the platform can notify Dart about changes. Can you move that plugin entirely into a background worker isolate? What would you do instead?
Show answer
No. Platform-to-Dart calls are not supported on a background isolate, so the handler must stay on the root isolate. Keep the plugin on the root isolate, and when it reports a change, forward the data to the worker through its SendPort as a plain message.
Exercise
Why can a static singleton that a plugin set up in main() appear uninitialized when the plugin is used in a background isolate, even after ensureInitialized?
Show answer
Each isolate has its own heap, so static fields are per isolate. ensureInitialized only connects the isolate to the platform channel system. It does not copy Dart state from the root isolate. The plugin must be set up again in the background isolate, if it supports that.