Sub topic 3
Calling native code from Dart with MethodChannel
This chapter covers the Dart side of a MethodChannel: how to call native code, pass arguments, read typed results, and handle failures. It assumes you know async/await and Future, can run a basic Flutter app, and have seen the android/ and ios/ folders. The previous chapters introduced the channel architecture and the standard codec. The next two chapters write the Kotlin and Swift handlers.
What a MethodChannel call is
A MethodChannel is a named pipe between Dart and the host platform. Dart sends a method name and optional arguments. The native side runs some code and sends back one reply. That reply is a success value, an error, or "not implemented". This is a request/response pattern, like a function call that happens to cross a language boundary.
Three properties follow from this design:
- Every call is asynchronous.
invokeMethodalways returns aFuture, even if the native work is instant. - Each call gets exactly one reply. If you need many values over time, use an
EventChannelinstead (a later chapter). - Arguments and results go through a codec. The default is
StandardMethodCodec, so only the types it supports can cross.
The sequence for one call looks like this:
Creating the channel
You create a channel by giving it a name. The native side must register a handler under exactly the same string, or calls will not arrive.
static const MethodChannel _channel =
MethodChannel('com.example.app/battery');Use a reverse-domain prefix plus a feature name. A prefix such as com.example.app/ avoids collisions with channels from plugins in your app. A common convention is one channel per feature area (battery, bluetooth, auth) rather than one big channel for everything. Each channel then has its own handler on the native side.
The constructor takes an optional second argument, a MethodCodec. Leave it at the default unless you have a reason to switch to JSONMethodCodec. The standard codec supports more types and is what plugins use.
The channel object is cheap and holds no native resources. Making it static const inside a service class is idiomatic.
Calling invokeMethod
The signature is:
Future<T?> invokeMethod<T>(String method, [dynamic arguments])Note that the result is always nullable. The native side can reply null, and you also get null if a handler returns without a value. Declare your own return type to match.
Here is a complete service class and a small page that uses it:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class BatteryService {
static const MethodChannel _channel =
MethodChannel('com.example.app/battery');
Future<int?> getBatteryLevel() async {
try {
return await _channel.invokeMethod<int>('getBatteryLevel');
} on PlatformException catch (e) {
throw StateError('Battery unavailable: ${e.code} ${e.message}');
}
}
}
void main() => runApp(const MaterialApp(home: BatteryPage()));
class BatteryPage extends StatefulWidget {
const BatteryPage({super.key});
@override
State<BatteryPage> createState() => _BatteryPageState();
}
class _BatteryPageState extends State<BatteryPage> {
final BatteryService _service = BatteryService();
late Future<int?> _level;
@override
void initState() {
super.initState();
_level = _service.getBatteryLevel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<int?>(
future: _level,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Battery: ${snapshot.data ?? 'unknown'}%');
},
),
),
);
}
}This page needs the native handlers from the next two chapters. Without them the call throws MissingPluginException, which the page shows as an error. That failure is itself useful for seeing the error path.
Why wrap the channel in a class
Calling invokeMethod with a raw string from a widget spreads magic strings across your UI. A service class gives you three things:
- One place that owns the channel name and method names.
- A typed, documented Dart API that hides the channel.
- A single seam to replace in tests, either by faking the service or by mocking the channel (covered in the testing chapter).
Passing arguments
The optional second parameter to invokeMethod is a single value. To send several values, pack them into a Map. On Android the handler reads them with call.argument<T>("key"), and on iOS with call.arguments as? [String: Any].
import 'package:flutter/services.dart';
class ThermostatService {
static const MethodChannel _channel =
MethodChannel('com.example.app/thermostat');
Future<void> setTarget({required double celsius, required bool eco}) {
return _channel.invokeMethod<void>('setTarget', <String, Object?>{
'celsius': celsius,
'eco': eco,
});
}
Future<Map<String, Object?>> readStatus() async {
final status =
await _channel.invokeMapMethod<String, Object?>('readStatus');
return status ?? const <String, Object?>{};
}
Future<List<String>> listZones() async {
final zones = await _channel.invokeListMethod<String>('listZones');
return zones ?? const <String>[];
}
}Some details in this example:
invokeMethod<void>is the right form for calls where you only care that the call finished.invokeMapMethod<K, V>andinvokeListMethod<T>exist because of how generics work with the codec. The platform returns a plainMap<Object?, Object?>orList<Object?>. If you callinvokeMethod<Map<String, int>>, the cast can fail at runtime. The two helper methods convert the collection to the type you ask for.- Both helpers return
nullwhen the native side replies withnull, so handle that case as shown. - Pass only codec-supported values:
null,bool,int,double,String,Uint8List,Int32List,Int64List,Float64List,List, andMap. A custom class throws an error when the call is encoded. Convert such objects to aMapfirst.
The type of the result
Dart's int maps to a 64-bit or 32-bit native integer depending on its value. Dart's double maps to a native double. With invokeMethod<int>, the reply must really be an integer. If the Android handler sends level.toDouble(), the call fails with a type error in Dart. Check that the native value matches what you declared.
Handling failures
A call can fail in three ways, and each shows up differently in Dart.
| Native behavior | What Dart sees | Typical cause |
|---|---|---|
| `result.error(code, message, details)` | `PlatformException` with `code`, `message`, `details` | The native operation failed, such as a missing sensor |
| `result.notImplemented()` | `MissingPluginException` | The handler does not know the method name |
| No handler registered on the channel | `MissingPluginException` | Wrong channel name, platform without an implementation, or a plugin not registered |
PlatformException carries data from native code. MissingPluginException signals a wiring problem, so catching it is usually about graceful degradation:
import 'package:flutter/services.dart';
Future<int?> safeBatteryLevel(MethodChannel channel) async {
try {
return await channel.invokeMethod<int>('getBatteryLevel');
} on PlatformException catch (e) {
// The native side understood the call but could not do the work.
print('Native error ${e.code}: ${e.message} (${e.details})');
return null;
} on MissingPluginException {
// No native handler: for example running on desktop or in a test.
return null;
}
}Swallowing MissingPluginException everywhere can hide real bugs such as a misspelled channel name. Catch it where you have a sensible fallback, such as an optional feature on one platform. Otherwise let it propagate.
Error codes as an API
The code field is a string you define. Treat the codes as part of the contract between Dart and native code. For example, both sides agree on "UNAVAILABLE" and "PERMISSION_DENIED". In Dart, map them to your own exceptions so the UI does not depend on channel details:
sealed class BatteryFailure implements Exception {
const BatteryFailure(this.message);
final String message;
}
class BatteryUnavailable extends BatteryFailure {
const BatteryUnavailable(super.message);
}
class BatteryUnknown extends BatteryFailure {
const BatteryUnknown(super.message);
}
BatteryFailure toFailure(PlatformException e) {
switch (e.code) {
case 'UNAVAILABLE':
return BatteryUnavailable(e.message ?? 'Battery not available');
default:
return BatteryUnknown('${e.code}: ${e.message}');
}
}The next chapters on the native handlers and error handling go deeper on the native side of these codes.
Rules and gotchas
- Call from the root isolate. Channels talk to the platform through the root isolate's binary messenger. To use a channel from a background isolate, you must call
BackgroundIsolateBinaryMessenger.ensureInitialized(token)with aRootIsolateTokenpassed from the main isolate, and the plugin must support it. - Initialize bindings first. If you call a channel before
runApp, for example inmain, callWidgetsFlutterBinding.ensureInitialized()first. Otherwise the binary messenger is not ready. - Hot reload and hot restart. Hot reload keeps the native handler. Changes to Kotlin or Swift code need a full rebuild, not a hot restart. A new method on the native side that appears to do nothing is usually an app that was not rebuilt.
- Native handlers must reply exactly once. A handler that never calls
resultleaves the DartFuturepending forever. A handler that replies twice triggers an error on the native side. In Dart there is no built-in timeout, so add.timeout(...)to calls that could hang. - Large payloads cost time. Encoding and copying big byte arrays through a channel is slower than it looks. For large data, prefer files, shared memory, or
dart:ffi. - Strings are the contract. Method names and argument keys are not type checked. A typo compiles on both sides and fails at runtime. This is the main motivation for Pigeon, covered in the last chapter.
Putting it together
A checklist for adding a new native call:
- Pick a channel name and a method name, and write them down once.
- Decide the argument shape (a single value or a
Map) and the result type, using only codec-supported types. - Wrap the channel in a Dart service class with a typed method.
- Catch
PlatformExceptionwhere you can translate it into a meaningful Dart error. - Decide where a
MissingPluginExceptionshould be handled. - Implement the Kotlin and Swift handlers using the same names, then test on both platforms.
Exercise
A Dart method calls _channel.invokeMethod<Map<String, int>>('readCounters'). The native side replies with a map of strings to integers, but the call throws a type error in Dart. What is the likely cause, and which API fixes it?
Show answer
The platform returns a Map<Object?, Object?>, and the cast to Map<String, int> fails at runtime. Use invokeMapMethod<String, int>('readCounters'), which converts the map to the requested key and value types. Remember that it returns null if native replies with null.
Exercise
You call invokeMethod<int>('getBatteryLevel') on a channel named com.example.app/battery, but you get a MissingPluginException. Name three possible causes.
Show answer
(1) The native channel name differs from the Dart name, such as a typo or different casing. (2) The native handler does not handle the method name and replies notImplemented(). (3) No handler is registered at all, because the code runs on a platform with no implementation, the native code was changed but the app was not rebuilt, or the call runs in a test without a mock handler.