| name | platform_handler |
| description | Use when coding with platform_handler: centralized Flutter MethodChannel registration, native-to-Flutter notification dispatch, invokeMethod wrappers, and PingPongPlatformNotification requestId response matching. |
platform_handler Agent Context
Use this package to organize Flutter MethodChannel communication. Register a channel once, subscribe notifications by native method name, and invoke native methods through a PlatformHandler.
Imports
import 'package:platform_handler/platform_handler.dart';
import 'package:platform_handler/platform_notification.dart';
Handler Setup
class AppPlatformHandler extends PlatformHandler {
@override
Future<dynamic> n2fCallDispatcher(MethodCall call) async {
print("native -> flutter: ${call.method}, ${call.arguments}");
return super.n2fCallDispatcher(call);
}
}
final handler = AppPlatformHandler();
handler.registerChannel("native.demo.com/messageChannel");
Native Callback Notification
class LogNotification extends PlatformNotification {
LogNotification() {
subscribers = {
"LogCallback": onLog,
};
}
void listen() {
docking = true;
}
void onLog(dynamic arguments) {
print(arguments);
}
}
final logNotification = LogNotification()..listen();
handler.subscribe([logNotification]);
await handler.invokeMethod("startLog");
Ping-Pong Request/Response
Use PingPongPlatformNotification when each request expects one matching 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()..listen();
handler.subscribe([ruleNotification]);
await handler.invokeMethod("luaScript", "return 1", ruleNotification);
Native must respond with { "requestId": sameRequestId, "responseData": result }. Late, duplicate, or mismatched request IDs are ignored.
Notes for Agents
- Business code should use
handler.invokeMethod, not raw MethodChannel, unless low-level control is required.
- Set
docking = true before expecting callbacks.
- Map native method names in
subscribers.
- Use
PingPongPlatformNotification for request-response flows; use PlatformNotification for push/event callbacks.