platform_handler
A small Flutter helper for organizing native MethodChannel callbacks.
platform_handler lets you register one native channel, subscribe callback handlers by method name, and invoke native methods through the same manager. For request-response style calls, PingPongPlatformNotification automatically attaches a requestId and ignores stale or duplicated responses.
Chinese documentation: README-zh.md
Features
- Register a native
MethodChannelin one place. - Route native callbacks to focused
PlatformNotificationclasses. - Invoke native methods without exposing
MethodChannelto business code. - Built-in ping-pong request id handling for one request and one terminal response.
Quick Start
final handler = AppPlatformHandler();
handler.registerChannel('native.demo.com/messageChannel');
handler.subscribe([
logNotification,
ruleNotification,
]);
Handle Native Callbacks
class AppPlatformHandler extends PlatformHandler {
@override
Future<dynamic> n2fCallDispatcher(MethodCall call) async {
print('native -> flutter: ${call.method}, ${call.arguments}');
return super.n2fCallDispatcher(call);
}
}
class LogNotification extends PlatformNotification {
LogNotification() {
subscribers = {
'LogCallback': onLog,
};
}
void listen() {
docking = true;
}
void onLog(dynamic arguments) {
print(arguments);
}
}
Invoke Native Methods
logNotification.listen();
await handler.invokeMethod('startLog');
Ping-Pong Requests
Use PingPongPlatformNotification when each request should accept only one terminal response.
class RuleNotification extends PingPongPlatformNotification {
RuleNotification() {
subscribers = {
'RuleResult': onRuleResult,
};
}
void listen() {
docking = true;
}
void onRuleResult(dynamic responseData) {
print('rule result: $responseData');
}
}
final ruleNotification = RuleNotification();
ruleNotification.listen();
await handler.invokeMethod(
'luaScript',
'return 1',
ruleNotification,
);
When the notification is ping-pong, invokeMethod sends this shape to native:
{
'requestId': 'ph-request...',
'arguments': originalArguments,
}
Native should return:
{
'requestId': sameRequestId,
'responseData': nativeResult,
}
Only the matching response is delivered to onRuleResult. Late, duplicated, or mismatched responses are ignored.
Native Side
Use the same method channel name on Android and iOS:
native.demo.com/messageChannel
Then call Flutter with the method names subscribed by your notifications, for example LogCallback or RuleResult.
Additional Information
Issues and suggestions are welcome on GitHub.