
Platform Channels Are Async Messages, Not Function Calls
- كاتب موثّق
- Flutter 3.x
محتويات المقال
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
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.
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
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.
Only codec values can cross
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."
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
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
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
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')));}const channel = MethodChannel('app/reminders');Future<void> onSetReminder(BuildContext context, Reminder r) async { final messenger = ScaffoldMessenger.of(context); try { await channel.invokeMethod<void>('schedule', { 'id': r.id, 'at': r.at.millisecondsSinceEpoch, // an int crosses the channel }); messenger.showSnackBar(const SnackBar(content: Text('Reminder set'))); } on PlatformException catch (e) { messenger.showSnackBar(SnackBar(content: Text('Failed: ${e.message}'))); }}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.
Future | ||
Map<Object?, Object?> or List<Object?>, cast by you | ||
// 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);}How to apply it in your project
Await every invokeMethod Search for invokeMethodcalls that aren't awaited or returned. HandlePlatformExceptionand, where a platform may lack the method,MissingPluginException.Convert at the boundary Turn DateTimeinto milliseconds or an ISO string, enums into names, and objects into maps before sending. Never pass domain objects through a channel.Cast what comes back Use invokeMapMethodorinvokeListMethod, or cast the result right away, and validate the fields you read.Keep slow native work off the main thread Move heavy handlers to a Task Queue. If you call a channel from a background isolate, register it with BackgroundIsolateBinaryMessengerfirst.Test the channel and consider Pigeon Write flutter testcases withsetMockMethodCallHandlerthat send real arguments, and move hand-written string protocols to Pigeon as they grow.
Key takeaways
invokeMethodsends an encoded message and returns aFuture; code after it runs before the reply.Only codec values cross: DateTime,Setand your own classes fail with anArgumentErrorbefore leaving Dart.That error arrives through the Future, so an unawaited call fails silently.Results decode as Map<Object?, Object?>andList<Object?>; useinvokeMapMethodor cast.Native handlers run on the platform's main thread by default; use a Task Queue for slow work, and Pigeon for types.
التعليقات (0)