Sub topic 7
Talking to Native Code with Platform Channels
Prerequisites and the message model
This chapter assumes you know basic Dart and Flutter widgets, and that you can read Kotlin or Swift in an existing native app. You should already have a Flutter module embedded in the host app and a way to obtain its FlutterEngine.
A platform channel is a named communication path between Dart and native code. Dart sends a method call or message through the channel. The Android or iOS host receives it and sends back a result. The channel crosses an asynchronous boundary, so Dart must wait for the response.
Use the channel type that matches the communication pattern:
| Channel | Best for | Example |
|---|---|---|
| `MethodChannel` | Request and response | Read the signed-in user's name |
| `EventChannel` | A stream of native events | Location or sensor updates |
| `BasicMessageChannel` | Repeated messages with a custom codec | Shared status messages |
For a single request, MethodChannel is usually the simplest choice.
Define the Dart side
The channel name is part of the interface. Both sides must use exactly the same string. Keep names stable and specific to the feature.
The following module displays a loading value, asks the host for a name, and handles common failures:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MaterialApp(home: GreetingPage()));
}
class GreetingPage extends StatefulWidget {
const GreetingPage({super.key});
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
static const _channel = MethodChannel('com.example.host/session');
String _name = 'Loading...';
String? _error;
@override
void initState() {
super.initState();
_loadUserName();
}
Future<void> _loadUserName() async {
try {
final name =
await _channel.invokeMethod<String>('getUserName');
if (!mounted) return;
setState(() {
_name = name ?? 'Guest';
});
} on PlatformException catch (error) {
if (!mounted) return;
setState(() {
_error = error.message ?? 'The host could not provide a name.';
});
} on MissingPluginException {
if (!mounted) return;
setState(() {
_error = 'This host does not implement the session channel.';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(_error ?? 'Hello, $_name'),
),
);
}
}invokeMethod<String> asks the codec to decode the result as a string. Standard values such as strings, numbers, lists, maps, and null can cross the default channel codec. For complex models, send a map with documented keys or use Pigeon to generate a typed interface.
Register the Android handler
Register the handler on the engine that will display the Flutter screen. The handler must complete the result exactly once:
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
fun registerSessionChannel(engine: FlutterEngine) {
MethodChannel(
engine.dartExecutor.binaryMessenger,
"com.example.host/session"
).setMethodCallHandler { call, result ->
when (call.method) {
"getUserName" -> result.success("Ada")
else -> result.notImplemented()
}
}
}Call registerSessionChannel(engine) after creating or retrieving the engine and before Dart makes the request. For a cached engine, register the handler against that cached engine's messenger. Registering it on a different engine does not connect the channel.
On iOS, use the same channel name with FlutterMethodChannel, provide a method call handler, and return through the supplied result closure. The protocol is the same: return a value, FlutterError, or FlutterMethodNotImplemented.
Avoid common channel failures
- A spelling or capitalization difference in the channel name prevents communication.
- A method name that the host does not recognize should return
notImplemented. - Native code must not call the result callback twice.
- Long-running native work should run off the UI thread, then return the result safely.
- Dart widgets can be disposed while a request is running. Check
mountedbefore callingsetState. - Define argument and result shapes in one place. Version the contract when changing them.
For larger interfaces, Pigeon generates Dart and native APIs from a shared definition. It reduces string-based method names and manual type conversions, but adds a code-generation step. Use it when the channel has several methods, structured models, or multiple host implementations.
Exercise
What must you change if Dart calls com.example.host/session but the native handler listens on com.example.host/user?
Show answer
Make both sides use exactly the same channel name, then rebuild or reload the host so the handler is registered on the active FlutterEngine.