Sub topic 11
Keeping native work off the main thread
This chapter assumes you have finished the earlier chapters on the Android and iOS implementations. You should be comfortable with a MethodChannel handler in Kotlin and in Swift. You should also know how result.success and result.error reply to Dart.
Why the main thread matters
Each platform has one main thread, also called the platform thread or UI thread. It draws native views, handles touch input, and runs system callbacks. By default, Flutter delivers every MethodChannel call to your plugin on this thread.
Dart does not freeze while your native code runs, because await suspends only the Dart caller. The native side is the problem. A handler that spends 300 ms reading a file blocks the platform thread for 300 ms. The consequences are:
- On Android, animations in platform views stutter, and long blocks can trigger an "Application Not Responding" dialog.
- On iOS, gestures and platform views become unresponsive, and the watchdog can terminate an app whose main thread stays blocked too long.
- Network calls on the Android main thread throw
NetworkOnMainThreadException.
The rule is to do slow work on a background thread and reply on the main thread. "Slow" includes disk and network I/O, image decoding, hashing, database queries, and anything with an unbounded loop. Short reads such as the battery level can stay on the main thread.
The Dart side does not change
Moving work to a worker thread is invisible to callers. The method stays asynchronous and returns a Future. This example adds a method that computes a checksum of a file:
Future<int> fileChecksum(String path) async {
try {
final int? sum = await _channel.invokeMethod<int>(
'fileChecksum',
<String, Object?>{'path': path},
);
return sum!;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}Android: an executor and a main-thread handler
Create a single-thread Executor when the plugin attaches. Submit the work to it. When the work finishes, post the reply to the main looper. Two details matter here:
- Reply exactly once, on every path, including failures.
- Shut the executor down in
onDetachedFromEngine, or the thread leaks.
package com.example.battery_info
import android.os.Handler
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class BatteryInfoPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var executor: ExecutorService
private val mainHandler = Handler(Looper.getMainLooper())
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
executor = Executors.newSingleThreadExecutor()
channel = MethodChannel(binding.binaryMessenger, "battery_info")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"fileChecksum" -> {
val path = call.argument<String>("path")
if (path == null) {
result.error("INVALID_ARGUMENT", "path is required.", null)
return
}
executor.execute {
try {
var sum = 0L
for (b in File(path).readBytes()) {
sum += (b.toInt() and 0xFF)
}
val checksum = sum and 0xFFFFFFFFL
mainHandler.post { result.success(checksum) }
} catch (e: Exception) {
mainHandler.post { result.error("IO_ERROR", e.message, null) }
}
}
}
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
executor.shutdown()
}
}The Long value arrives in Dart as an int. The argument check runs on the main thread because it is cheap. Only the file read is moved.
iOS: Grand Central Dispatch
On iOS, DispatchQueue.global supplies the worker thread. Use DispatchQueue.main.async to reply.
import Flutter
import UIKit
public class BatteryInfoPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "battery_info", binaryMessenger: registrar.messenger())
let instance = BatteryInfoPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "fileChecksum":
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String else {
result(FlutterError(code: "INVALID_ARGUMENT", message: "path is required.", details: nil))
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let sum = data.reduce(UInt32(0)) { $0 &+ UInt32($1) }
DispatchQueue.main.async { result(Int(sum)) }
} catch {
DispatchQueue.main.async {
result(FlutterError(code: "IO_ERROR", message: error.localizedDescription, details: nil))
}
}
}
default:
result(FlutterMethodNotImplemented)
}
}
}The FlutterResult closure is marked @escaping because it is called after handle returns. Both platforms compute the same checksum, so the Dart tests can use one expected value.
Task queues: let the channel pick the thread
Recent Flutter versions can run a channel's handler on a background thread without any manual dispatching. You ask the messenger for a task queue and pass it when you create the channel.
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
val taskQueue = binding.binaryMessenger.makeBackgroundTaskQueue()
channel = MethodChannel(
binding.binaryMessenger,
"battery_info",
StandardMethodCodec.INSTANCE,
taskQueue
)
channel.setMethodCallHandler(this)
}The iOS equivalent looks like this. The call is optional-chained because makeBackgroundTaskQueue is an optional method on the messenger protocol.
let taskQueue = registrar.messenger().makeBackgroundTaskQueue?()
let channel = FlutterMethodChannel(
name: "battery_info",
binaryMessenger: registrar.messenger(),
codec: FlutterStandardMethodCodec.sharedInstance(),
taskQueue: taskQueue
)Every method on that channel now runs on the queue's background thread, so you do not post results back to the main thread. The trade-off is that a task queue applies to the whole channel. A channel that mixes cheap and expensive methods puts all of them on the background thread. A handler that touches UI APIs, such as UIDevice or an Activity, must hop to the main thread itself.
| Approach | Where handler runs | Reply from | Best for |
|---|---|---|---|
| Default | Main thread | Main thread | Fast, UI-bound calls |
| Executor or GCD | Main, then worker | Main (you post) | Mixed channels, one slow method |
| Task queue | Background thread | Background thread | Channels where every method is slow |
Common errors
- Replying from the worker thread. With the default channel setup, calling
result.successoff the main thread can crash or silently drop the message. Always post back. - Never replying. An early
returnin anifbranch or an uncaught exception leaves the DartFuturepending forever. Wrap worker bodies intry/catchand reply in both branches. - Replying twice. Calling
resulta second time throws on Android and is ignored or logged on iOS. - Unbounded threads. Creating a
Threadper call wastes memory. Reuse one executor or a queue. - Updating UI from the worker. Views,
UIDevice, andActivitycalls belong on the main thread.
Testing
The mock channel test from the testing chapter still works, because it replaces the native side entirely. It cannot show whether your native code blocks the main thread. To check that, run the example app and profile it. Android Studio's Profiler and Xcode's Time Profiler both show main-thread activity. Call your slow method while a scrolling list or animation is on screen. Dropped frames during the call point to work that is still on the main thread.
Exercise
Your Android handler for fileChecksum reads the file on a worker thread. It calls result.success(checksum) directly from that worker, without posting to the main looper, and the plugin uses a plain MethodChannel with no task queue. What is wrong, and what are two ways to fix it?
Show answer
With the default setup the reply must be sent on the main thread, so calling result.success from the worker can crash or lose the message. Fix 1: wrap the reply in Handler(Looper.getMainLooper()).post { ... }, for both the success and the error path. Fix 2: create the channel with a background task queue from makeBackgroundTaskQueue(), so the handler and its reply run on the queue's thread.