Sub topic 8
Async Methods and Threading
This chapter assumes basic Dart and Flutter structure, async/await, and that you can read Kotlin or Swift. You should also know that a Flutter app and native code communicate through platform channels.
A platform call can take time. Reading a file, querying a database, or asking a device service for data should not stop Flutter from drawing frames. Pigeon represents this work with asynchronous methods.
Declare an asynchronous API
In a Pigeon schema, return Future<T> when native work does not finish immediately. The generated Dart method also returns a Future<T>. The generated native method receives a completion callback instead of returning the value directly.
// 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',
))
class BatteryInfo {
BatteryInfo({required this.level});
int level;
}
@HostApi()
abstract class BatteryApi {
Future<BatteryInfo> getBatteryInfo();
}Dart code awaits the generated method like any other asynchronous Dart function:
import 'src/messages.g.dart';
Future<int> readBatteryLevel() async {
final info = await BatteryApi().getBatteryInfo();
return info.level;
}The await pauses this function, not the Flutter user interface. Flutter can continue processing input and drawing frames while the native side works.
Move expensive work off the platform thread
Pigeon does not automatically make native work run in the background. An API call may initially reach the Android or iOS platform thread. Short operations are usually fine there. Network requests, database queries, and expensive computation should use a background queue.
On Android, an implementation can use an executor. The completion callback reports the result after the work finishes.
import android.content.Context
import android.os.BatteryManager
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class BatteryApiImpl(
private val context: Context
) : BatteryApi {
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
override fun getBatteryInfo(callback: (Result<BatteryInfo>) -> Unit) {
executor.execute {
try {
val manager =
context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager
.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
.toLong()
callback(Result.success(BatteryInfo(level = level)))
} catch (error: Throwable) {
callback(Result.failure(error))
}
}
}
fun close() {
executor.shutdown()
}
}The exact generated callback signature can vary with the Pigeon version and language options. Always inspect the generated interface when implementing an API.
On iOS, use a background queue for slow work. Call the completion handler when the result is ready.
import Foundation
import UIKit
final class BatteryApiImpl: BatteryApi {
func getBatteryInfo(
completion: @escaping (Result<BatteryInfo, Error>) -> Void
) {
DispatchQueue.global(qos: .userInitiated).async {
UIDevice.current.isBatteryMonitoringEnabled = true
let rawLevel = UIDevice.current.batteryLevel
let level = Int64(max(rawLevel, 0) * 100)
completion(.success(BatteryInfo(level: level)))
}
}
}Keep UI work on the main thread
Background code must not update UI objects directly. On Android, post UI work to the main looper. On iOS, use DispatchQueue.main.async. The completion callback can usually be delivered from the worker queue because Dart receives a platform message, but native UI updates still belong on the platform’s main thread.
Follow the call sequence
A completion callback must be called exactly once on every path. Call it with success when the operation completes, or with failure when it cannot complete. Forgetting the callback leaves the Dart Future pending forever.
Exercise
Why should a native implementation use a background queue for a slow database query?
Show answer
The platform thread can continue handling Flutter messages and UI work instead of being blocked until the query finishes.