Sub topic 8
Async methods and threading
This chapter assumes you have declared a HostApi, generated the code, and implemented it in Kotlin and Swift, as in the earlier chapters. It covers three things: which thread your native code runs on, how to write methods that finish later, and how to move heavy work off the UI thread.
Dart is always async, native is not
Every HostApi method returns a Future on the Dart side. The call crosses a message channel, so the answer can never arrive immediately. This is true even when the native implementation is synchronous.
The native side is different. By default Pigeon generates a synchronous native method. It returns a value, or throws, and Pigeon sends that result back before the handler returns.
| Schema declaration | Dart signature | Kotlin signature | Swift signature |
|---|---|---|---|
| `int quickCount();` | `Future<int> quickCount()` | `fun quickCount(): Long` | `func quickCount() throws -> Int64` |
| `@async String buildReport(String name);` | `Future<String> buildReport(String name)` | `fun buildReport(name: String, callback: (Result<String>) -> Unit)` | `func buildReport(name: String, completion: @escaping (Result<String, Error>) -> Void)` |
The Kotlin and Swift signatures for @async methods are those generated by recent Pigeon releases. Older releases used different callback types, so compare with your generated file after you run the generator.
Where your native code runs
Flutter runs Dart and native code on separate threads, and each platform has a "platform thread".
- On Android, the platform thread is the main (UI) thread.
- On iOS, it is the main thread.
When a message arrives from Dart, the engine delivers it to your handler on that platform thread. This has two consequences:
- A slow synchronous handler freezes the native UI. Flutter's own rendering runs on other threads, but the platform thread also handles lifecycle events, platform views, and input forwarding on the native side. A blocked handler makes the whole app feel stuck.
- Replies must also be sent from the platform thread. Calling the Pigeon callback from a background thread can crash or drop the message, depending on platform and engine version.
The second point is the most common mistake with async methods.
Declaring an async method
Add the @async annotation to a method in the HostApi. The following schema mixes a fast synchronous method with a slow asynchronous one.
// pigeons/messages.dart
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Messages.g.swift',
))
@HostApi()
abstract class ReportApi {
/// Cheap lookup. A synchronous native handler is fine.
int quickCount();
/// Slow work. The native side replies through a callback.
@async
String buildReport(String name);
}Use @async when the native work needs time or calls an API that reports its result later. Examples are file I/O, network requests, database queries, and system APIs that take a completion handler, such as permission prompts or Bluetooth scans.
Use a plain synchronous method for quick, in-memory work such as reading a stored property.
Implementing an async method on Android
The generated Kotlin interface gives you a callback parameter. You call it exactly once, with Result.success(value) or Result.failure(error).
This implementation does the slow work on a single-thread executor and posts the result back to the main looper.
import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executors
class ReportApiImpl : ReportApi {
private val executor = Executors.newSingleThreadExecutor()
private val mainHandler = Handler(Looper.getMainLooper())
override fun quickCount(): Long = 3L
override fun buildReport(name: String, callback: (Result<String>) -> Unit) {
executor.execute {
val result = runCatching {
Thread.sleep(500) // stands in for real work
"Report for $name"
}
mainHandler.post { callback(result) }
}
}
}
// In MainActivity.configureFlutterEngine:
// ReportApi.setUp(flutterEngine.dartExecutor.binaryMessenger, ReportApiImpl())Three details matter here:
runCatchingturns any thrown exception intoResult.failure, so Dart gets an error instead of a Future that never completes.mainHandler.postmoves the callback back to the platform thread.- The executor is a field, not created per call, so the app does not create a new thread for every request.
If you use Kotlin coroutines, the same rule applies. Do the work in Dispatchers.IO and call the callback from Dispatchers.Main.
Implementing an async method on iOS
The generated Swift protocol uses a completion closure. The same rule holds: call it once, on the main thread.
import Flutter
import UIKit
class ReportApiImpl: ReportApi {
func quickCount() throws -> Int64 {
return 3
}
func buildReport(name: String, completion: @escaping (Result<String, Error>) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
Thread.sleep(forTimeInterval: 0.5) // stands in for real work
let report = "Report for \(name)"
DispatchQueue.main.async {
completion(.success(report))
}
}
}
}
// In AppDelegate, after the Flutter view controller is available:
// let controller = window?.rootViewController as! FlutterViewController
// ReportApiSetup.setUp(binaryMessenger: controller.binaryMessenger, api: ReportApiImpl())If an iOS API already delivers its result on the main queue, you can call completion directly from its handler. When you are unsure, hop to the main queue explicitly. The extra hop costs very little.
Calling it from Dart
Nothing in the Dart code reveals whether the native method is @async. You always await the call.
import 'src/messages.g.dart';
Future<void> loadReports() async {
final api = ReportApi();
// Both calls are in flight at the same time.
final results = await Future.wait([
api.buildReport('Q1'),
api.buildReport('Q2'),
]);
print(results);
// Guard against a native side that never replies.
try {
final report = await api.buildReport('Q3').timeout(
const Duration(seconds: 5),
);
print(report);
} on Exception catch (e) {
print('Report failed: $e');
}
}Calls to the same API are independent. The Dart side does not queue them, so Future.wait really does start both before either finishes. Whether they run in parallel on the native side depends on your implementation. In the Android example above, the single-thread executor runs them one after the other. Use a larger thread pool if you want parallelism.
The timeout call protects against a handler that forgets to invoke its callback. Dart has no other way to know the native side has stopped responding.
Moving synchronous handlers off the platform thread
Sometimes the native API is synchronous and slow, and you do not want to write executor code in every method. Pigeon can run handlers on a background thread for you with the @TaskQueue annotation.
@HostApi()
abstract class ImageApi {
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
Uint8List compress(Uint8List input, int quality);
}With serialBackgroundThread, Pigeon asks the engine for a background task queue and registers the handler on it. Messages for that handler run one at a time, off the platform thread, and Pigeon sends the reply for you.
Check these points before relying on it:
- Task queues need a recent Flutter engine. Check the Pigeon changelog and the generated code for your version.
- Code in a background handler cannot touch UI APIs directly. On Android you cannot show a
Toast. On iOS you cannot useUIKitobjects. serialBackgroundThreadruns calls to the annotated handlers one at a time. If you need real parallelism, write your own thread pool and use@async.
You can combine @TaskQueue with @async, but then your handler also must not block the task queue thread for long. For most apps, @async with your own executor is the more flexible choice, and @TaskQueue is the shortcut for simple cases.
FlutterApi and threads
The same rule applies in the other direction. When native code calls a FlutterApi, the call must come from the platform thread. If a sensor or network callback fires on a background thread, hop to the main thread first.
mainHandler.post {
batteryEvents.onBatteryChanged(info) { /* reply ignored */ }
}Here batteryEvents is the generated native client for the FlutterApi from the earlier chapter. Every call to it takes a completion callback, even for void methods. That callback tells you whether Dart handled the message.
Platform channels from background isolates
Dart code running in a background isolate can call a Pigeon API too, since Flutter 3.7. The isolate must register itself first, and the generated constructor must receive the messenger that results.
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
Future<String> reportInBackground(String name) async {
final token = RootIsolateToken.instance!;
return Isolate.run(() async {
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
final api = ReportApi(
binaryMessenger: BackgroundIsolateBinaryMessenger.instance,
);
return api.buildReport(name);
});
}This moves Dart-side work, such as parsing the reply, off the main isolate. It does not change the native threading. The native handler still runs on the platform thread unless you use @async or @TaskQueue.
Common mistakes
- Never calling the callback. The Dart
Futurestays pending forever. Handle every code path, including early returns andcatchblocks. - Calling the callback twice. The second reply is ignored or logged as an error. Watch for code that calls it in both a success handler and a
finallyblock. - Replying from a background thread. This can crash on Android or fail silently. Post to the main thread first.
- Blocking the platform thread in a synchronous handler. Dart sees a slow
Future, but the whole native UI also suffers. Make the method@asyncor use@TaskQueue. - Capturing an
Activityin a long-lived executor task. If the user leaves the screen, the callback may run against a destroyed object. Check for cancellation, or hold only the applicationContext.
Exercise
A Kotlin @async handler starts a Thread, finishes its work, and calls callback(Result.success(value)) directly from that thread. What can go wrong, and how do you fix it?
Show answer
The reply is sent from a thread other than the platform thread, which can crash the app or lose the message. Post the call to the main looper, for example Handler(Looper.getMainLooper()).post { callback(Result.success(value)) }.
Exercise
You have a synchronous HostApi method that reads a large file and takes 300 ms. Name two ways to stop it from blocking the platform thread, and say when you would choose each.
Show answer
Mark the method @async and do the read on your own executor, replying on the main thread. This suits cases where you want control over the thread pool or cancellation. Or add @TaskQueue(type: TaskQueueType.serialBackgroundThread) so Pigeon runs the handler on a background thread. This suits simple handlers that do not need parallelism or UI access.
Exercise
Why should Dart code calling an @async method often add .timeout(...)?
Show answer
Dart cannot tell whether the native side is still working or has forgotten to call its callback. Without a timeout, the Future stays pending forever and the UI may wait indefinitely.