Sub topic 2
How Platform Channels Carry Messages
Assume you know intermediate Dart and Flutter, including Future, Stream, and asynchronous callbacks. You should also know the basics of Kotlin or Swift. This chapter explains how values cross the boundary between Dart code and native Android or iOS code.
The message path
A platform channel is a named communication path between Flutter and native code. Dart sends a message to a channel, and a message codec converts the Dart value into bytes. The native side decodes those bytes, handles the request, and encodes its response.
The channel name is part of the contract. Both sides must use the same name and compatible codecs. A name such as com.example.app/greeting is specific enough to avoid collisions.
Flutter's default codec is StandardMessageCodec. It supports values that have direct representations on both platforms:
| Dart value | Encoded value |
|---|---|
| `null`, `bool`, `int`, `double`, `String` | Scalar value |
| `Uint8List` | Byte array |
| `List` | Ordered collection |
| `Map` | Key-value collection |
Nested lists and maps are allowed when every nested value is supported. Use simple, stable data structures at the boundary. For example, pass a map with string keys instead of passing a custom Dart object.
Encoding a channel message
A MethodChannel message includes a method name and optional arguments. The channel does not automatically serialize arbitrary classes. Convert domain objects into supported values before invocation.
import 'package:flutter/services.dart';
class GreetingApi {
static const _channel = MethodChannel('com.example.app/greeting');
Future<String> greet(String name) async {
final result = await _channel.invokeMethod<String>('greet', {
'name': name,
});
return result ?? '';
}
}Here, greet is the method name and the map is the argument value. The codec encodes both for the native handler. The generic type on invokeMethod<String> tells Dart what result type the wrapper expects. It does not force the native side to return that type, so a mismatch can still cause a runtime error.
An EventChannel uses the same general codec idea, but it carries a sequence of messages. Each event must be a supported value. A native sensor might send a double, while a more complex event could be a map such as {'value': 21.5, 'unit': 'C'}.
What can go wrong
A codec failure occurs when a value cannot be encoded or decoded. A type-casting failure occurs when Dart expects a different type from the one returned by native code. Keep conversions at the wrapper boundary, validate native input, and document the accepted shapes.
Exercise
Why can a Dart custom class not be passed directly through a standard platform channel?
Show answer
The standard codec only knows how to encode supported primitive values and collections. Convert the object to a supported map or list first.