الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 7 دقائق للقراءة

Platform Channels Are Async Messages, Not Function Calls

invokeMethod encodes your arguments, sends them to the platform's main thread and hands you a Future. Only codec values cross, and failures arrive later.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

A Flutter app schedules reminders through a MethodChannel. The button handler calls invokeMethod('schedule', ...) with a map holding the reminder's ID and its DateTime, then shows a "Reminder set" snackbar. Users report reminders that never fire. The Kotlin and Swift code is fine; it was never called. The DateTime couldn't be encoded, the error went into a Future nobody awaited, and the snackbar had already promised success.

The common misconception

The belief: calling native code through a MethodChannel is a direct function call into Kotlin or Swift. It runs right away, and you can pass it any Dart object, the same way you'd pass one to another Dart function.

The API invites that reading. The class is called MethodChannel, the method is invokeMethod, and the native side receives a call with a method and arguments, just like a dispatcher. The arguments parameter is dynamic, so the compiler accepts anything. Most plugins hide the channel behind a typed Dart method, and on a fast phone the reply feels instant. The half-truth: it is a call in spirit, a request with a reply. But it travels as a message, across threads and a serialization step, and each of those has its own rules and failure modes.

What actually happens

Your call becomes a message

The API docs describe it plainly: method calls "are encoded into binary before being sent, and binary results received are decoded into Dart values." Flutter's guide adds that messages and responses are passed "asynchronously through channels to ensure the user interface remains responsive." So invokeMethod always returns a Future, and the code after it runs before the reply exists. In a test with a mocked native handler, a log written around a call came out as before call, after call, result: true.

On the other side, a handler runs on the platform's main thread by default. The guide says handlers "can execute on the platform's main thread or they can execute on a background thread if using a Task Queue." From Dart, calls must come from the root isolate or an registered as a background isolate. One comfort: channels provided by the framework "guarantee FIFO ordering", so calls on the same channel arrive in the order you sent them.

Only codec values can cross

A carries what its can encode. The default, StandardMessageCodec, supports null, bools, numbers, strings, typed data lists such as Uint8List, and lists and maps of those. The MethodChannel docs are clear about the rest: "The use of unsupported values should be considered programming errors, and will result in exceptions being thrown."

We passed a range of values through a channel in flutter test. A DateTime, a Duration, a Uri, a Set, a BigInt and a custom User class each failed with an ArgumentError such as Invalid argument: Instance of 'DateTime'. A map with a DateTime inside failed the same way. In every failing case, the mocked native handler never ran: the call died during encoding, still in Dart. And invokeMethod itself didn't throw. It returned a Future, and the error appeared only when that Future was awaited.

What comes back is loosely typed

The codec decodes into List<Object?> and Map<Object?, Object?> "irrespective of content." Asking for invokeMethod<Map<String, Object?>> in our test threw a TypeError: '_Map<Object?, Object?>' is not a subtype of type 'Map<String, Object?>?'. The docs warn that the type argument "cannot be a class with generics other than dynamic." invokeMapMethod<String, Object?> worked, because it casts the map for you.

Failures are part of the contract

The returned Future completes with a result, a PlatformException when native code reports an error, or a MissingPluginException when nothing handles the method. Method and channel names are strings matched at runtime, so a typo isn't a compile error; in our test it surfaced as No implementation found for method ping on channel app/missing. ReadIn's article on why a network call is not a method call makes the same point for servers, and most of it applies here too.

Making the reminder call honest

Dart reminder_button.dart
const channel = MethodChannel('app/reminders');void onSetReminder(BuildContext context, Reminder r) {  // Not awaited, and DateTime isn't a codec type:  // the ArgumentError lands in a Future nobody listens to  channel.invokeMethod('schedule', {'id': r.id, 'at': r.at});  ScaffoldMessenger.of(context)      .showSnackBar(const SnackBar(content: Text('Reminder set')));}

We ran the wrong version in a guarded zone: the snackbar line ran, the zone caught Invalid argument: Instance of 'DateTime', and the native handler was called zero times. With millisecondsSinceEpoch, it was called once. The right version also grabs the ScaffoldMessenger before the await, for the reasons in the article on BuildContext after await. A MissingPluginException isn't a PlatformException, so catch it too if the method may be missing on a platform.

Dart function callMethodChannel call
When the result existsWhen the function returnsLater, through a Future
What you can passAny Dart objectCodec values: null, bool, num, String, typed data, List, Map
What comes backThe declared typeMap<Object?, Object?> or List<Object?>, cast by you
How names are checkedBy the compilerAs strings at runtime
Where the code runsThe calling isolateThe platform's main thread, unless a Task Queue is used
Dart pigeons/reminders.dart
// Input for Pigeon's code generator, not app codeclass ReminderMessage {  ReminderMessage({required this.id, required this.atMillis});  final String id;  final int atMillis;}@HostApi()abstract class ReminderApi {  @async  bool schedule(ReminderMessage reminder);}

Pigeon's platform channel mode is still asynchronous messaging, just typed. Its README also describes an experimental native interop mode built on Dart FFI and JNI that supports synchronous host calls, on Android, iOS and macOS only.

How to apply it in your project

  1. Await every invokeMethodSearch for invokeMethod calls that aren't awaited or returned. Handle PlatformException and, where a platform may lack the method, MissingPluginException.
  2. Convert at the boundaryTurn DateTime into milliseconds or an ISO string, enums into names, and objects into maps before sending. Never pass domain objects through a channel.
  3. Cast what comes backUse invokeMapMethod or invokeListMethod, or cast the result right away, and validate the fields you read.
  4. Keep slow native work off the main threadMove heavy handlers to a Task Queue. If you call a channel from a background isolate, register it with BackgroundIsolateBinaryMessenger first.
  5. Test the channel and consider PigeonWrite flutter test cases with setMockMethodCallHandler that send real arguments, and move hand-written string protocols to Pigeon as they grow.

Key takeaways

  • invokeMethod sends an encoded message and returns a Future; code after it runs before the reply.
  • Only codec values cross: DateTime, Set and your own classes fail with an ArgumentError before leaving Dart.
  • That error arrives through the Future, so an unawaited call fails silently.
  • Results decode as Map<Object?, Object?> and List<Object?>; use invokeMapMethod or cast.
  • Native handlers run on the platform's main thread by default; use a Task Queue for slow work, and Pigeon for types.

📚 المصادر

  1. Writing custom platform-specific code — Flutter docs
  2. MethodChannel class — Flutter API
  3. MethodChannel.invokeMethod — Flutter API
  4. StandardMessageCodec class — Flutter API
  5. pigeon — pub.dev

التعليقات (0)