Sub topic 10
MethodChannel or EventChannel: choosing the right one
This chapter assumes you have already written a MethodChannel and an EventChannel with Kotlin and Swift handlers, as in the earlier chapters. You should also be comfortable with Future, Stream, and the difference between a single-subscription and a broadcast stream. Here the question is which channel to use for a given native feature, and how to combine them when one is not enough.
The core difference: one answer or many
Both channels carry asynchronous messages between Dart and the host platform, and both use the same codec machinery. They differ in the shape of the conversation.
- A
MethodChannelis request and response. Dart asks, native code answers once, and theFuturecompletes. The initiative is always on the Dart side. - An
EventChannelis subscribe and push. Dart starts listening, native code sends zero or more events whenever it wants, and Dart stops listening. After the subscription starts, the initiative is on the native side.
A useful test is to ask who decides when the next message is sent. If Dart does, use a MethodChannel. If the platform does, because a sensor reading arrived, a download progressed, or the connectivity state changed, use an EventChannel.
| Question | MethodChannel | EventChannel |
|---|---|---|
| Dart type | `Future<T?>` from `invokeMethod` | `Stream<dynamic>` from `receiveBroadcastStream` |
| Messages per use | One result or one error | Any number of events, then an optional end |
| Who initiates each message | Dart | Native, after Dart subscribes |
| Direction of data | Arguments in, result out | Events out (arguments only at subscribe time) |
| Native lifecycle hooks | One handler call per method call | `onListen` and `onCancel` |
| Typical uses | Read a value, trigger an action, run a query | Sensors, location updates, connectivity, progress |
| Error shape | `PlatformException` from the `Future` | `PlatformException` delivered as a stream error |
A decision flow
The flowchart below turns the question into steps. Follow it from the top for each native capability you want to expose.
When a MethodChannel is the right choice
Use a MethodChannel when each interaction has a clear start and finish.
- Reading a value once, such as the battery level, the device model, or an app version.
- Performing an action and reporting success or failure, such as opening a native share sheet, saving a file, or starting a payment.
- Querying with arguments, such as "does this app scheme resolve to an installed app?"
A MethodChannel also fits slow work. The Future stays pending until native code calls result.success, result.error, or result.notImplemented. The handler can start background work and answer later, as long as it replies exactly once.
When an EventChannel is the right choice
Use an EventChannel when native code is the source of a sequence and Dart only needs to observe it.
- Hardware streams: accelerometer, compass, battery state changes.
- System notifications: network reachability, screen on or off, headset plugged in.
- Long operations that report progress and then finish.
Two properties matter in practice.
- Native work is tied to the subscription. The platform's
onListenruns when Dart starts listening, andonCancelruns when the last Dart listener cancels. Start sensors, timers, and observers inonListen. Stop them inonCancel. The sensor then runs only while someone is listening. - Nothing is buffered for you. Events sent while no Dart listener exists are lost. An event channel is a live feed, not a queue.
The most common mistake: polling with a MethodChannel
When developers know MethodChannel well, they often build a stream out of repeated calls:
import 'dart:async';
import 'package:flutter/services.dart';
const MethodChannel _channel = MethodChannel('com.example.app/battery');
Stream<int?> pollBattery() {
return Stream.periodic(const Duration(seconds: 1))
.asyncMap((_) => _channel.invokeMethod<int>('getBatteryLevel'));
}This works, but it has real costs.
- Every poll crosses the channel and wakes native code, even when nothing changed.
- Changes are seen up to one interval late, and short-lived changes between polls are missed.
- Native code cannot stop or start work based on whether anyone is watching.
If the platform offers a callback or observer, wrap it in an EventChannel instead. Polling is acceptable only when the platform exposes no change notification, and then the polling loop is better placed in native code behind an EventChannel than in Dart.
The opposite mistake: forcing request and response onto an EventChannel
An EventChannel has no way to send a message to native code after the subscription starts. The only input is the arguments value passed to receiveBroadcastStream, and native code receives it once, in onListen. Do not try to encode commands in that argument or reopen the stream to "send" something. Use a MethodChannel for commands.
An event channel also gives you no per-message reply. If Dart must confirm each event, or Dart must answer a question that native code asks, use a MethodChannel. Native code can also call into Dart through invokeMethod on the platform side, though that is a less common pattern.
Combining both channels
Many real features need both. The usual split is:
- A
MethodChannelfor commands and one-off reads (start, stop, configure, get current value). - An
EventChannelfor updates.
This example exposes the current battery level through a method and later changes through an event channel. It also passes configuration at subscribe time through the stream arguments.
import 'dart:async';
import 'package:flutter/services.dart';
class BatteryService {
static const MethodChannel _method =
MethodChannel('com.example.app/battery');
static const EventChannel _events =
EventChannel('com.example.app/battery_events');
Future<int?> current() => _method.invokeMethod<int>('getBatteryLevel');
Stream<int> changes({int minDelta = 1}) {
return _events
.receiveBroadcastStream(<String, Object?>{'minDelta': minDelta})
.map((event) => event as int);
}
}Use a distinct channel name for each channel. A MethodChannel and an EventChannel that share a name would register on the same binary messenger entry, and one handler would replace the other. A suffix such as /battery and /battery_events keeps them apart.
The snapshot-then-stream pattern
A new subscriber usually wants the current value first and then updates. There are two clean ways to get this.
- Send an initial event in
onListen. Native code reads the current value and calls the sink once, right after it registers its observer. Dart sees a single stream with no gap. - Call a method, then listen. Dart awaits
current()and then subscribes tochanges(). This is simpler to write, but a change that happens between the two steps is lost.
Prefer the first option when you control the native code. Use the second when you are wrapping a native API that you cannot change.
Edge cases to know
Broadcast semantics. receiveBroadcastStream returns a broadcast stream, so several Dart listeners can attach. Native onListen runs when the first listener attaches. onCancel runs when the last one detaches. All listeners share one native subscription and see the same events. Per-listener behavior is not possible. If two parts of the app need different arguments, such as different sampling rates, use two channel names or one shared service object that owns the stream.
Errors on a stream. Native code can call events.error(code, message, details) (Android) or send a FlutterError to the sink (iOS). Dart receives a PlatformException as a stream error. An error does not end the stream by default. The listener's onError runs, and later events still arrive.
Ending a stream. Android calls events.endOfStream(). iOS calls the sink with the FlutterEndOfEventStream constant. The Dart stream then completes, and onDone runs. Use this for finite sequences, such as a progress feed that finishes.
Missing handlers. If a Dart invokeMethod call reaches a channel with no registered handler, it throws MissingPluginException. For event channels, subscribing to an unregistered name produces the same exception as a stream error. This usually means the native registration code did not run, for example because of a hot restart that cleared state or a plugin that was not registered.
Cancelling is the cleanup signal. If the Dart subscription is never cancelled, onCancel never runs, and native observers keep running. Always cancel in dispose or in the owner's teardown path.
A quick selection checklist
Work through these questions in order.
- Is the result a single value or a single success or failure? Use a
MethodChannel. - Does native code have to push data without being asked each time? Use an
EventChannel. - Does Dart also need commands or an initial value? Add a
MethodChannelnext to theEventChannel. - Do you have many methods with structured arguments, or a plugin shared across teams? Consider Pigeon, covered in a later chapter, which generates typed code for the method-call style.
- Can the platform notify you of changes? Never poll from Dart.
Exercise
A fitness app needs to (a) ask the platform whether step counting is available, (b) start and stop step counting, and (c) receive a new step total every time it changes. Which channel types would you use for each part, and why would you avoid polling for part (c)?
Show answer
Use a MethodChannel for (a) and (b). The availability check is a one-off query with a single answer, and start and stop are commands that Dart initiates and that complete with success or an error. Use an EventChannel for (c), because the platform decides when the step total changes and pushes each new value to Dart. Polling with repeated invokeMethod calls would wake native code even when nothing changed, would delay updates by up to the polling interval, and would give native code no signal for when to stop counting. An EventChannel's onListen and onCancel provide that signal.
Exercise
Two widgets both call receiveBroadcastStream on the same EventChannel, each with a different arguments map. What does the native side see, and how would you fix the design?
Show answer
Native onListen runs only once, when the first listener attaches, so it receives only the first widget's arguments. The second listener shares the same native subscription and sees the same events. To fix it, use one shared service that owns the stream and exposes it to both widgets, or register two separate channel names when the widgets need genuinely different native configuration.