Sub topic 11
Threading and cleanup
This chapter assumes you have written a MethodChannel and an EventChannel handler on both platforms, as in the earlier chapters. It covers which thread each piece of code runs on, how to move slow work off the main thread, and how to release native resources when a channel stops being used.
Which thread runs what
Every channel message crosses a boundary between the Dart isolate and the host platform. Two threads matter:
- The Dart UI isolate runs your Dart code. It is the isolate that
main()starts in. Futures frominvokeMethodcomplete here. - The platform thread is the Android main (UI) thread or the iOS main thread. By default, native channel handlers run on it.
| Code | Runs on by default |
|---|---|
| `invokeMethod` call and `await` | Dart UI isolate |
| `setMethodCallHandler` callback (Kotlin or Swift) | Platform (main) thread |
| `onListen` and `onCancel` of a stream handler | Platform (main) thread |
| `result.success`, `result.error`, `events.success` | Must be called on the platform thread |
Two consequences follow:
- A handler that blocks, for example by reading a large file, freezes the native UI. Flutter drawing may stall too, because the platform thread also handles input and lifecycle events.
- Replies and event-sink calls must return to the platform thread. If you do the work elsewhere, hop back before replying.
Moving slow work off the platform thread
The usual pattern is: receive the call on the platform thread, validate the arguments there, run the slow part on a worker, and post the reply back.
Android
import android.os.Handler
import android.os.Looper
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.IOException
import java.security.MessageDigest
import java.util.concurrent.Executors
class MainActivity : FlutterActivity() {
private val worker = Executors.newSingleThreadExecutor()
private val mainHandler = Handler(Looper.getMainLooper())
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.app/hash")
.setMethodCallHandler { call, result ->
when (call.method) {
"hashFile" -> {
val path = call.argument<String>("path")
if (path == null) {
result.error("BAD_ARGS", "path is required", null)
return@setMethodCallHandler
}
worker.execute {
try {
val digest = sha256(path)
mainHandler.post { result.success(digest) }
} catch (e: IOException) {
mainHandler.post { result.error("IO_ERROR", e.message, null) }
}
}
}
else -> result.notImplemented()
}
}
}
private fun sha256(path: String): String {
val bytes = MessageDigest.getInstance("SHA-256").digest(File(path).readBytes())
return bytes.joinToString("") { "%02x".format(it) }
}
override fun onDestroy() {
worker.shutdown()
super.onDestroy()
}
}Every code path ends in exactly one reply: success, error, or notImplemented. The return@setMethodCallHandler after the argument error stops the handler from also queuing work.
iOS
import Flutter
import CryptoKit
func registerHashChannel(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: "com.example.app/hash",
binaryMessenger: messenger)
channel.setMethodCallHandler { call, result in
guard call.method == "hashFile" else {
result(FlutterMethodNotImplemented)
return
}
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String else {
result(FlutterError(code: "BAD_ARGS", message: "path is required", details: nil))
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let hex = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
DispatchQueue.main.async { result(hex) }
} catch {
DispatchQueue.main.async {
result(FlutterError(code: "IO_ERROR", message: error.localizedDescription, details: nil))
}
}
}
}
}Call registerHashChannel(messenger: controller.binaryMessenger) from didFinishLaunchingWithOptions, next to the channel code from the earlier chapter.
Task queues: running a handler off the platform thread
Both platforms let you register a handler so that Flutter itself runs it on a background thread. You create a task queue from the binary messenger and pass it when you build the channel. On Android:
val messenger = flutterEngine.dartExecutor.binaryMessenger
val taskQueue = messenger.makeBackgroundTaskQueue()
MethodChannel(messenger, "com.example.app/hash", StandardMethodCodec.INSTANCE, taskQueue)
.setMethodCallHandler { call, result -> /* runs on a background thread */ }iOS has the same idea through makeBackgroundTaskQueue and a taskQueue: parameter on the channel initializer. A task queue is serial, so calls on one queue run one at a time.
Inside a task-queue handler you are no longer on the main thread. Any UI API, and any native object that requires the main thread, still needs an explicit hop to it.
Calling channels from a background isolate
Since Flutter 3.7, a Dart background isolate can use a channel too, provided it is given a token from the root isolate:
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 channel.invokeMethod<int>('getBatteryLevel');
});
}The native handler still runs where it was registered, usually the platform thread. This only moves the Dart caller off the UI isolate. It helps when the Dart side is busy, for instance while decoding a large response, and does not make a slow native handler fast.
Replying exactly once
Each Result accepts one reply. Typical bugs:
- No reply. The Dart
Futurenever completes. This often happens when atryblock fails and thecatchforgets to callresult.error. - Two replies. A success followed by an error from a callback that fires twice. Android logs an error or throws, depending on version. Treat it as a bug on either platform.
- Reply from the wrong thread. Calling
result.successfrom a worker thread may work in a quick test and then crash or misbehave on another device or Flutter version. Always post to the main thread.
The same applies to event sinks. On Android, call sink.success(...) from the main thread, as the Handler(Looper.getMainLooper()) in the earlier TickStreamHandler does. On iOS, call the FlutterEventSink from the main queue. If a sensor callback arrives on another thread, wrap the call in DispatchQueue.main.async.
Cleanup: what must be released and when
Native resources outlive a single call, so they need an owner and a release point.
Event streams
For an EventChannel, Dart listen triggers onListen, and cancelling the last subscription triggers onCancel. Use onCancel to release everything onListen acquired: timers, Handler callbacks, sensor listeners, location updates, and the saved sink.
receiveBroadcastStream produces a broadcast stream. onListen fires for the first listener and onCancel for the last one. A second listener does not start a second native source, and the native side cannot tell the listeners apart.
On the Dart side, keep the StreamSubscription and cancel it:
import 'dart:async';
import 'package:flutter/widgets.dart';
class TickView extends StatefulWidget {
const TickView({super.key});
@override
State<TickView> createState() => _TickViewState();
}
class _TickViewState extends State<TickView> {
static const EventChannel _events = EventChannel('com.example.app/ticks');
StreamSubscription<dynamic>? _sub;
int _last = -1;
@override
void initState() {
super.initState();
_sub = _events.receiveBroadcastStream().listen((event) {
setState(() => _last = event as int);
});
}
@override
void dispose() {
_sub?.cancel(); // triggers onCancel on the native side
super.dispose();
}
@override
Widget build(BuildContext context) => Text('tick: $_last');
}Without dispose, the subscription stays alive after the widget is gone. The native timer keeps running and setState is called on a disposed widget.
Handlers and the engine
A channel handler holds a reference to your native object, and the engine holds the channel. Remove the handler when the engine goes away:
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class BatteryPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var channel: MethodChannel
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "com.example.app/battery")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
result.notImplemented()
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}The iOS counterpart is channel.setMethodCallHandler(nil) in the plugin's detachFromEngine(for:). Setting the handler to nil releases the closure and any objects it captured. After that, a Dart call on that channel name fails with MissingPluginException.
Lifecycle gotchas
- Activity versus engine. An Android
Activitycan be destroyed and recreated, for example on rotation, while a cached engine survives. Stop native work in the component whose lifetime matches the work, and do not hold anActivityreference in a long-lived stream handler. - Hot restart. The Dart side restarts and its subscriptions disappear. Do not assume
onCancelis called in that case, and makeonListensafe to call again by resetting state at its start, as the tick handlers do withcount = 0. Stop any existing timer there too. - Backgrounded apps. Streaming from sensors or location while the app is in the background drains the battery and may be blocked by the OS. If your use case needs it, pause the source in the platform lifecycle callbacks.
- Late replies. A worker may finish after the engine detached. Check for cancellation before posting, or accept that the reply is dropped.
Summary checklist
- Handlers run on the platform thread, so keep them short.
- Slow work goes to a worker or a task queue, and the reply goes back to the main thread.
- Reply once on every path.
- Release in
onCancel, indispose, and inonDetachedFromEngine.
Exercise
A Kotlin handler for "loadImage" calls worker.execute { result.success(bytes) } directly from the worker thread. It works in your emulator, but users report rare crashes and UI hiccups. What should change, and where should the Dart side release its resources if "loadImage" were an event stream instead?
Show answer
Post the reply to the main thread, for example mainHandler.post { result.success(bytes) } with Handler(Looper.getMainLooper()). Replies must be sent from the platform thread, and the emulator's timing can hide the bug. For a stream, the Dart widget should keep the StreamSubscription and call cancel() in dispose, which triggers onCancel on the native side. There, the stream handler stops its worker, removes callbacks, and sets the event sink to null.