Sub topic 11
Keeping Native Work off the Main Thread
This chapter assumes you understand Dart futures, Flutter platform channels, and the basic Android and iOS plugin lifecycle. You should also know basic Kotlin and Swift concurrency APIs.
Why the main thread matters
The main thread, also called the UI thread, draws the application and handles user input. Long-running native work on this thread can make the Flutter interface freeze.
Examples of work that may need a background thread include:
- Reading a large file.
- Running a database query.
- Encrypting or decoding data.
- Calling a slow native SDK.
- Processing a large image.
A platform-channel method call usually begins on the platform thread. The native implementation should start expensive work elsewhere, then send the result back through the channel.
The result callback must be called exactly once. It should also report both success and failure.
Android: use a worker and return safely
Android plugin handlers commonly begin on the main thread. An ExecutorService provides a simple worker pool without adding another dependency.
private val executor = Executors.newSingleThreadExecutor()
private val mainHandler = Handler(Looper.getMainLooper())
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method != "readData") {
result.notImplemented()
return
}
executor.execute {
try {
val value = readDataFromDisk()
mainHandler.post {
result.success(value)
}
} catch (error: Exception) {
mainHandler.post {
result.error("READ_FAILED", error.message, null)
}
}
}
}
private fun readDataFromDisk(): String {
Thread.sleep(500)
return "finished"
}The example uses Thread.sleep only to represent slow work. Real code should perform the actual operation there. Keep UI-dependent Android APIs on the main thread. For example, an Activity or a view should not be accessed from the executor.
Shut down the executor when the plugin detaches from the engine:
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
executor.shutdown()
channel.setMethodCallHandler(null)
}If the plugin can attach again, create a new executor during attachment instead of reusing one that has been shut down.
iOS: dispatch work with GCD
On iOS, Grand Central Dispatch (GCD) schedules work on queues. Use a background queue for expensive work and the main queue for UI-related work and the final channel response.
public func handle(
_ call: FlutterMethodCall,
result: @escaping FlutterResult
) {
guard call.method == "readData" else {
result(FlutterMethodNotImplemented)
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
let value = try self.readDataFromDisk()
DispatchQueue.main.async {
result(value)
}
} catch {
DispatchQueue.main.async {
result(FlutterError(
code: "READ_FAILED",
message: error.localizedDescription,
details: nil
))
}
}
}
}Use DispatchQueue.main for UIKit and other main-thread-only APIs. Avoid capturing mutable plugin state without synchronization. A background operation can finish after the plugin or its associated resource has been released.
> callout note > Moving work to a background thread prevents UI stalls, but it does not automatically make code safe. Protect shared state, handle cancellation where possible, and ensure every channel call receives one response.
Common errors
| Error | Consequence | Better approach |
|---|---|---|
| Doing file or database work in the handler | Frozen interface | Dispatch to a worker |
| Calling a UI API from a worker | Crash or undefined behavior | Hop to the main thread |
| Returning twice | Channel protocol error | Use one success or error path |
| Forgetting executor cleanup | Threads remain alive | Shut down during detachment |
Exercise
Where should an Android plugin perform a slow database query, and where should it update a user interface element?
Show answer
Perform the query on a background executor. Update the user interface on the main thread, then return the channel result exactly once.