Sub topic 1
How platform channels work
Flutter draws its own UI and runs your Dart code inside the Flutter engine. Features of the host operating system are outside that world: battery state, a vendor SDK, a Bluetooth stack, a system picker. Platform channels are how Dart code reaches them. This chapter explains the mechanism: who talks to whom, what travels between them, and which rules apply to every channel type. Later chapters build on it with concrete MethodChannel and EventChannel code.
Prerequisites
This chapter assumes you can:
- Read Dart, including
async/await,Future, andStream. - Build and run a basic Flutter app on an emulator or device.
- Read simple Kotlin and Swift.
- Find the
android/andios/folders of a Flutter project and know that they hold the host apps.
You do not need to have written any native code yet.
The problem platform channels solve
A Flutter app is a normal Android or iOS app that hosts a Flutter engine. The engine runs your Dart code and renders the UI. Dart cannot call Android's BatteryManager or iOS's UIDevice directly, because those APIs are Kotlin/Java and Swift/Objective-C.
Flutter's answer is message passing, not direct calls. Dart sends a message to the host. The host does the work and sends a message back. Neither side holds a reference to objects on the other side. Everything that crosses the boundary is data.
The moving parts
A platform channel has four parts.
- A channel name. A string that identifies the conversation, for example
com.example.app/battery. - A binary messenger. The object that carries raw bytes between Dart and the host through the engine.
- A codec. The rule for turning Dart values into bytes and back, and the same on the host side.
- A handler. Code on the receiving side that is registered under a channel name and answers messages.
The binary messenger does not understand your data. It moves a block of bytes tagged with a channel name. The channel classes (MethodChannel, EventChannel, BasicMessageChannel) add meaning on top of that.
Dart execution is not blocked while this happens. invokeMethod returns a Future, and your Dart code continues to run (the UI keeps drawing) until the reply arrives.
Channel types
Flutter provides three channel classes. All three use a name, a messenger, and a codec.
| Channel | Pattern | Typical use |
|---|---|---|
| `MethodChannel` | Request, then one reply | Ask for the battery level, open a native screen, start a native SDK |
| `EventChannel` | Native side pushes a stream of events | Sensor readings, location updates, connectivity changes |
| `BasicMessageChannel` | Plain messages with a reply, no method names | Simple custom protocols, rarely used directly |
This tutorial focuses on the first two. MethodChannel is the default choice. EventChannel is for data that arrives over time. The chapter on choosing between them covers the decision in detail.
Channel names
The channel name is the only link between the two sides. Nothing checks at compile time that the Dart name matches the Kotlin or Swift name. A typo on either side produces a runtime failure, not a build error.
Follow these conventions:
- Use a reverse-domain prefix to avoid collisions with other plugins, for example
com.example.app/battery. - Use one name per feature, not one global channel for everything.
- Define the name once per platform as a constant, and keep a comment pointing to the matching constants on the other platforms.
Names are global to the engine. If two handlers register under the same name on one messenger, the later registration replaces the earlier one. This is a common source of confusing bugs when two plugins pick short, generic names such as battery.
A first look at the Dart side
Here is the smallest useful Dart-side channel, using the names that the later chapters use:
import 'package:flutter/services.dart';
const MethodChannel batteryChannel =
MethodChannel('com.example.app/battery');
Future<void> printBattery() async {
try {
final int? level =
await batteryChannel.invokeMethod<int>('getBatteryLevel');
print('Battery: $level%');
} on MissingPluginException {
print('No native handler is registered for this channel.');
}
}The MissingPluginException branch matters for this chapter. It means the message reached the engine, but no handler was registered under that channel name on the host side. That happens when the name is misspelled, when the platform has no implementation (running on web or desktop, for example), or when the handler is registered too late. The exception does not mean your native code threw anything. The native code never ran.
What actually crosses the boundary
On the wire, a method call is a byte buffer containing the method name and the arguments, encoded by a codec. You can see this without any native code. This test encodes a call, decodes it again, and shows that the round trip preserves the data:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('a method call survives encoding and decoding', () {
const codec = StandardMethodCodec();
final ByteData bytes = codec.encodeMethodCall(
const MethodCall('getBatteryLevel', {'unit': 'percent'}),
);
final MethodCall decoded = codec.decodeMethodCall(bytes);
expect(decoded.method, 'getBatteryLevel');
expect(decoded.arguments, {'unit': 'percent'});
print('Encoded size: ${bytes.lengthInBytes} bytes');
});
}Save it as test/codec_test.dart and run flutter test. The host side performs the mirror-image decode before your handler runs, which is why a handler receives a method name and arguments, not raw bytes.
The default codec for a MethodChannel is StandardMethodCodec, which supports numbers, booleans, strings, byte and number arrays, lists, and maps. Anything else, such as a custom class, must be converted to one of those first. The next chapter covers the exact type mapping to Kotlin and Swift.
Properties that hold for every channel
Messages are asynchronous
A message is sent and a reply arrives later. There is no synchronous call from Dart into native code through a channel. Design your Dart API around Future and Stream, and expect that the native side may take time to answer.
Messages are copies
The codec serializes values, so each side works on its own copy. Changing a list in Kotlin does not change the list in Dart. This also means large payloads cost time and memory: a multi-megabyte image sent through a channel is encoded, copied across the engine, and decoded. For bulk data, prefer approaches that avoid per-frame copies, such as a texture or a platform view.
Either side can start the conversation
The usual direction is Dart to host, but a handler can also be registered in Dart with setMethodCallHandler, and native code can then call Dart through the same channel name. This is how a native SDK can report a callback, such as a push-notification tap, to your Dart code. Each side that wants to receive registers a handler.
Handlers belong to the engine
A handler is registered on a messenger that belongs to one Flutter engine. The Android example in the next chapters registers it in configureFlutterEngine, and the iOS example uses the FlutterViewController's messenger. If an app runs more than one engine, each engine needs its own registration.
Hot restart resets Dart, not the host
Hot restart restarts your Dart code, but the host app and its native handlers stay alive. Native state, such as a running timer or an open connection, survives a hot restart. A native change, such as editing Kotlin or Swift code, needs a full rebuild, not a hot reload.
Threads and isolates
By default, handlers run on the platform's main thread (the Android main thread, the iOS main thread). Replies must also be sent from that thread unless you use the task queue features of the messenger. Slow native work inside a handler therefore freezes the host UI, even though the Dart UI thread is not affected. The threading chapter covers how to move work off the main thread safely.
On the Dart side, channels work from the root isolate by default. Calling a channel from a background isolate needs extra setup: since Flutter 3.7 you can call BackgroundIsolateBinaryMessenger.ensureInitialized with a RootIsolateToken obtained from the root isolate. Without that, the call fails because the background isolate has no binary messenger.
Failure modes at the architecture level
| Symptom | Likely cause |
|---|---|
| `MissingPluginException` | No handler under that name: typo, wrong platform, or handler registered after the first call |
| Handler never called after a rename | Dart and native names no longer match |
| Works after full restart, fails after hot reload | Native code changed, but a hot reload does not rebuild it |
| Value arrives as the wrong type | The codec mapped it differently than you assumed |
| Host UI stutters during a call | Slow work in the handler on the main thread |
Summary of the model
A platform channel is a named route through the Flutter engine. Dart and the host each register handlers by name. The codec turns values into bytes at one end and back into values at the other. Everything is asynchronous, copied, and checked only at runtime. With this model in place, the remaining chapters add the specifics: which types the codec supports, how to write the Dart, Kotlin, and Swift code for a MethodChannel and an EventChannel, and how to handle errors and threads.
Exercise
You call invokeMethod<int>('getBatteryLevel') on MethodChannel('com.example.app/battery') and get a MissingPluginException. Your Kotlin handler is registered under com.example.app/Battery, and the Kotlin code itself is correct. What is wrong, and did your Kotlin code run?
Show answer
The channel names differ in case (battery versus Battery), so the engine finds no handler for the Dart name and the Dart side reports MissingPluginException. The Kotlin handler never ran, because the message was never delivered to it. Fix it by making both names identical, ideally from one shared constant per platform.
Exercise
A teammate says a native method can return a custom Battery object to Dart through a MethodChannel using the standard codec. Why is that wrong, and what can you do instead?
Show answer
A channel sends serialized bytes, not object references, and the standard codec supports only a fixed set of types: null, booleans, numbers, strings, byte and number arrays, lists, and maps. A custom class is not among them. Convert the object to a map (for example {"level": 80, "charging": true}) on the native side, then build the Dart object from that map on the Dart side.