Sub topic 4
Message Codecs and Values That Cross the Boundary
Assume you know intermediate Dart, Future, Stream, and basic Kotlin or Swift. A platform channel transfers messages between Dart and native code. A message codec is the serializer that converts an in-memory value into bytes and reconstructs it on the other side.
MethodChannel and EventChannel use StandardMethodCodec by default. This codec uses StandardMessageCodec for values, then adds the structure needed for method calls, results, and errors.
Values Supported by the Standard Codec
The standard codec supports these common values:
| Dart value | Typical Android value | Typical iOS value |
|---|---|---|
| `null` | `null` | `nil` |
| `bool` | `Boolean` | `NSNumber` |
| `int` and `double` | `Integer`, `Long`, `Double` | `NSNumber` |
| `String` | `String` | `NSString` |
| `List` | `List` | `NSArray` |
| `Map` | `Map` | `NSDictionary` |
| `Uint8List` | `byte[]` | `FlutterStandardTypedData` |
Nested lists and maps are supported when every nested value is supported. Use string keys in maps for predictable behavior across Android and iOS.
import 'package:flutter/services.dart';
class ProfileApi {
static const _channel = MethodChannel('com.example.app/profile');
Future<void> saveProfile({
required String name,
required int age,
required List<String> tags,
}) {
return _channel.invokeMethod<void>('saveProfile', {
'name': name,
'age': age,
'tags': tags,
});
}
}Dart's int can be larger than some native integer types. Keep values within the range supported by both platforms, or send a large number as a string. Also remember that a native numeric value may arrive as int or double, so use num when both forms are valid.
What the Codec Does Not Support
The standard codec does not automatically serialize arbitrary Dart objects, DateTime, enums, or custom classes. Convert them into supported values before sending them.
For example, send a DateTime as an ISO 8601 string:
final payload = {
'createdAt': DateTime.now().toUtc().toIso8601String(),
};Reconstruct the DateTime on the receiving side. This makes the wire format explicit and avoids depending on platform-specific object representations.
Visualizing Serialization
When the built-in value set is insufficient, define a custom codec only when necessary. A simpler alternative is usually to encode the data as strings, lists, or maps and keep the channel contract easy to inspect.
Exercise
How should a Dart DateTime be sent through a standard platform channel?
Show answer
Convert it to a supported representation, such as a UTC ISO 8601 string, and parse that string on the native side.