Sub topic 2
Codecs and the types you can send
This chapter assumes you can write basic Dart, Kotlin and Swift, and that you have already seen a MethodChannel call from the previous chapter, "How platform channels work". Here you will learn how a value becomes bytes and back, which types survive the trip, and what happens to the ones that don't.
What a codec does
Dart and the host platform run in different runtimes with different object models. A Dart Map cannot be handed to Kotlin as a pointer. Every message that crosses a channel is flattened into bytes by a codec, sent through the binary messenger, and rebuilt on the other side by the matching codec.
Both sides must use the same codec. If they disagree, decoding fails or produces garbage. A codec also defines the set of types you can send. This is the most common source of channel bugs.
The codecs Flutter provides
Flutter ships two layers of codecs. A message codec converts a single value to bytes and back. A method codec wraps a message codec and also encodes a method name, arguments, and the success or error envelope of a reply.
| Codec | Layer | Use |
|---|---|---|
| `StandardMessageCodec` | Message | Default. Binary format for the types in the table below. |
| `JSONMessageCodec` | Message | Values that are valid JSON, encoded as UTF-8 text. |
| `StringCodec` | Message | Plain strings. |
| `BinaryCodec` | Message | Raw bytes, with no interpretation. |
| `StandardMethodCodec` | Method | Default for `MethodChannel` and `EventChannel`. |
| `JSONMethodCodec` | Method | Method calls whose payloads are JSON. |
MethodChannel and EventChannel use StandardMethodCodec unless you pass another one as the second constructor argument:
import 'package:flutter/services.dart';
const jsonChannel = MethodChannel('com.example.app/json', JSONMethodCodec());The native channel must be constructed with the same codec. On Android that is MethodChannel(messenger, name, JSONMethodCodec.INSTANCE). On iOS it is FlutterMethodChannel(name:binaryMessenger:codec:) with FlutterJSONMethodCodec.sharedInstance().
Message codecs are used directly by BasicMessageChannel, which sends plain messages with no method name. You will rarely need it. Stay with the standard codec unless you have a concrete reason to change.
Types the standard codec supports
The standard codec handles a fixed set of types. The table shows the Dart type you send and what the handler receives, and the same mapping in reverse for replies.
| Dart | Kotlin (Android) | Swift (iOS) |
|---|---|---|
| `null` | `null` | `nil`, or `NSNull` inside a collection |
| `bool` | `Boolean` | `NSNumber` holding a bool (cast with `as? Bool`) |
| `int` | `Int` if it fits in 32 bits, otherwise `Long` | `NSNumber` (cast with `as? Int`) |
| `double` | `Double` | `NSNumber` (cast with `as? Double`) |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` (bytes) |
| `Int32List` | `IntArray` | `FlutterStandardTypedData` (int32) |
| `Int64List` | `LongArray` | `FlutterStandardTypedData` (int64) |
| `Float32List` | `FloatArray` | `FlutterStandardTypedData` (float32) |
| `Float64List` | `DoubleArray` | `FlutterStandardTypedData` (float64) |
| `List` | `List` (an `ArrayList`) | `Array` |
| `Map` | `Map` (a `HashMap`) | `Dictionary` |
List and Map can nest, and their elements can be any supported type, including more lists and maps. Map keys can be any supported type, but strings are the practical choice.
Seeing the mapping in code
The following example sends one map containing most of the types, and the handler reads each one. The Dart side uses invokeMapMethod, which returns a typed Map instead of Map<dynamic, dynamic>.
import 'dart:typed_data';
import 'package:flutter/services.dart';
const _channel = MethodChannel('com.example.app/codec_demo');
Future<void> runDemo() async {
final result = await _channel.invokeMapMethod<String, Object?>('describe', {
'name': 'sensor-1',
'count': 3,
'ratio': 0.5,
'enabled': true,
'samples': Int32List.fromList([10, 20, 30]),
'tags': ['a', 'b'],
'nested': {'x': 1},
'missing': null,
});
print(result);
}The Kotlin handler reads the arguments with call.argument<T>(), which looks up a key in the arguments map and casts the value.
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
fun registerCodecDemo(messenger: BinaryMessenger) {
MethodChannel(messenger, "com.example.app/codec_demo")
.setMethodCallHandler { call, result ->
when (call.method) {
"describe" -> {
val name = call.argument<String>("name")
val count = call.argument<Int>("count")
val ratio = call.argument<Double>("ratio")
val samples = call.argument<IntArray>("samples")
val tags = call.argument<List<String>>("tags")
val nested = call.argument<Map<String, Any?>>("nested")
val nestedX = (nested?.get("x") as? Number)?.toLong()
result.success(
mapOf(
"name" to name,
"count" to count,
"ratio" to ratio,
"sampleCount" to samples?.size,
"tagCount" to tags?.size,
"nestedX" to nestedX
)
)
}
else -> result.notImplemented()
}
}
}The Swift handler receives call.arguments as Any?. It casts to a dictionary first, then casts each value.
import Flutter
func registerCodecDemo(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(
name: "com.example.app/codec_demo",
binaryMessenger: messenger)
channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
guard call.method == "describe" else {
result(FlutterMethodNotImplemented)
return
}
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let count = args["count"] as? Int,
let samples = args["samples"] as? FlutterStandardTypedData else {
result(FlutterError(code: "BAD_ARGS",
message: "Missing or mistyped argument.",
details: nil))
return
}
result([
"name": name,
"count": count,
"sampleCount": samples.elementCount
])
}
}Edge cases that cause bugs
Integers arrive as Int or Long
Dart has one int type, which is 64 bits wide on the VM. Kotlin has Int and Long, and the codec picks the smaller one when the value fits. A timestamp in milliseconds arrives as Long, while the value 3 arrives as Int. A cast such as call.argument<Long>("count") throws a ClassCastException when the Dart side sent 3.
When the width is not fixed, cast to Number and convert:
val count = (call.argument<Any>("count") as? Number)?.toLong()The reverse direction is simpler. Kotlin Int and Long both arrive in Dart as int.
Null inside collections
A top-level null becomes null or nil. On iOS, a null stored under a key in a map arrives as NSNull, because Swift dictionaries cannot hold nil for Any. The cast args["missing"] as? String returns nil for NSNull, so it behaves as you expect. A check like args["missing"] == nil is false when the key exists with a null value.
Typed lists keep their type
A Dart List<int> is sent as a generic list. Each element is encoded one by one, and Kotlin receives a List<Int>. An Int32List is sent as one compact block and arrives as an IntArray. For large numeric data such as audio samples or image bytes, use a typed list. It is much smaller and faster to encode.
On iOS, typed lists arrive wrapped in FlutterStandardTypedData. You read its data (a Data value), its type, and its elementCount.
Generics are erased
Whatever you ask for, the channel returns what the codec decoded. invokeMethod<List<String>> can fail at runtime, because the decoded value is a List<dynamic>. Use invokeListMethod<String> and invokeMapMethod<String, int>, which cast the elements for you. On the native side, call.argument<List<String>> is an unchecked cast. A wrong element type fails later, when you use the element.
Custom classes are not supported
If you pass an object the codec doesn't know, encoding fails. On the Dart side you get an error when the message is written. When native code returns an unsupported object, the result is a failed call, and on iOS the failure may be a crash. Convert your own types to maps before sending.
class Reading {
const Reading({required this.sensor, required this.value, required this.at});
final String sensor;
final double value;
final DateTime at;
Map<String, Object?> toMap() => {
'sensor': sensor,
'value': value,
'at': at.millisecondsSinceEpoch,
};
factory Reading.fromMap(Map<Object?, Object?> map) => Reading(
sensor: map['sensor'] as String,
value: (map['value'] as num).toDouble(),
at: DateTime.fromMillisecondsSinceEpoch(map['at'] as int),
);
}The same rule applies to other common types:
DateTime: send milliseconds since the epoch as anint, or an ISO 8601 string.- Enums: send the
namestring or an integer index. Strings survive reordering of the enum, so prefer them. Duration: send microseconds or milliseconds as anint.Floatin Dart: it does not exist. Dartdoubleis always 64-bit, so sendDoublefrom native code.
Integer range
A Dart int on the VM is a signed 64-bit value, and the standard codec encodes it as such. If you need larger numbers, send them as a decimal String and parse them on each side.
Large messages are copied
The codec copies the data at least once in each direction. Passing a 20 MB image as a Uint8List works but is slow and uses a lot of memory. For big payloads, send a file path, a texture ID, or a URI instead, and let the receiver read the data itself.
Writing your own codec
You can subclass StandardMessageCodec and override writeValue and readValue to add your own type tags. You must implement the same format in Kotlin (StandardMessageCodec subclass) and in Swift (FlutterStandardReaderWriter), and keep them in sync. For anything beyond one or two types, this is better handled by generating the code. The final chapter covers Pigeon, which does that for you.
Choosing a codec
- Use
StandardMethodCodec, the default, for almost everything. - Use
JSONMethodCodeconly when you are bridging to a native library that already speaks JSON and you want to pass its text through unchanged. - Use
BinaryCodecwith aBasicMessageChannelwhen the payload is an opaque byte block that you encode yourself.
Each of the other choices means writing extra code on both platforms, so make sure the benefit is real.
Exercise
A Dart caller sends {'id': 7, 'created': DateTime.now()} through a MethodChannel with the standard codec. The call fails. Explain why, and show how to fix the map. Then explain why a Kotlin handler that does call.argument<Long>("id") fails for the corrected map.
Show answer
The standard codec cannot encode DateTime, so the message cannot be written. Replace the value with a supported type, for example {'id': 7, 'created': DateTime.now().millisecondsSinceEpoch}. The value 7 fits in 32 bits, so Kotlin receives it as Int, and casting it to Long throws a ClassCastException. Read it with (call.argument<Any>("id") as? Number)?.toLong(), or ask for Int if the value is always small.
Exercise
You need to send 1 million 32-bit sensor readings from Dart to Kotlin and Swift. Which Dart type should you use, and what do the handlers receive?
Show answer
Use an Int32List. It is encoded as one compact block instead of a million separate list elements. Kotlin receives an IntArray. Swift receives a FlutterStandardTypedData whose type is int32, with the values in its data property and a count in elementCount.