MethodChannel data flow and type marshalling
how platform channels marshal data.
Dart invokeMethod sends a StandardMessageCodec-serialized payload to native, which returns a primitive or map; complex objects must be reduced to supported types.
WHAT THIS TESTS Whether you grasp the asynchronous, serialized nature of platform channels and the constraints on what data can cross the Dart-to-native boundary.
A GOOD ANSWER COVERS From Dart you call channel.invokeMethod with a method name and an optional arguments value. The StandardMethodCodec serializes the arguments into a binary message sent over the BinaryMessenger to the host platform. On Android a MethodCallHandler in Kotlin or Java receives the MethodCall, switches on call.method, runs native work, and replies via result.success, result.error, or result.notImplemented; iOS does the same in Swift or Objective-C. The reply is decoded back into Dart and completes the Future. Everything is asynchronous. Only codec-supported types travel: null, booleans, numbers, strings, Uint8List and similar byte buffers, and Lists and Maps composed of those.
COMMON WRONG ANSWERS Thinking you can pass a custom Dart class and have it appear as a native object automatically. Treating invokeMethod as synchronous. Forgetting to handle MissingPluginException or PlatformException. Assuming the return type is strongly typed; it arrives as dynamic and must be cast.
LIKELY FOLLOW-UPS How do you pass a custom object across. Difference between MethodChannel, EventChannel and BasicMessageChannel. What thread does the handler run on. How do errors propagate back as PlatformException.
ONE CONCRETE EXAMPLE To fetch battery level you call await channel.invokeMethod('getBatteryLevel'). The native handler reads the level and calls result.success(level), returning an int that arrives in Dart as a dynamic to cast. To send a user profile, you cannot pass a Dart User object; you convert it to a Map of primitives first, pass that, and reconstruct it natively, since the codec only understands primitives and collections of them.
Read the original → docs.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.