-
Notifications
You must be signed in to change notification settings - Fork 35
Platform Communication
Use the PlatformComm
class in the platform_comm
directory when you need to access platform-specific code quickly without writing a plugin.
More info on how platform communication is executed in Flutter can be found at the official documentation.
Also, if you need a specific feature that needs to communicate with platform-specific native code consider writing a flutter plugin. Here's a blog post on writing a good flutter plugin.
The PlatformComm
class is a helper for executing platform-specific methods which adds typed arguments and typed response. It's a wrapper around MethodChannel
and provides invokeMethod
and listenMethod
helper functions.
For invoking methods a converter is required if the arguments are not serialized automatically by MethodChannel#invokeMethod
.
For listening to calls from the native side you need to register a method listener that will parse the incoming method arguments. Internally, for listening to methods, the PlatformComm uses a converter map with closures to parse the params of an incoming method.
A current shortcoming is that you can only register one listener per platform method without overriding the previous one. To overcome this you need to wrap your method listener and allow multiple subscriptions or open a pull request to add this functionality to PlatformComm.
The PlatformComm
class is already configured on the flutter, Android, and iOS side, and is ready to be used. See platform_comm/AppPlatformMethods
for preset platform methods used for testing.
Alternatively, you can use Pigeon for this, but we opted to write our own helper.
The following code sends a String
message to the native side and receives the same echo message back.
serviceLocator
.get<PlatformComm>()
.echoMessage('echo')
.catchError((error) => 'Test platform method error: $error')
.then((backEcho) => Log.d("Test message 'echo' - '$backEcho'"));
The echo message calls the invokeMethod
function in PlatformComm
:
Future<String> echoMessage(String echoMessage) =>
this.invokeMethod(method: platformTestMethod, param: echoMessage);
For more complicated parameter types see echoObject
which takes a typed Object as a parameter and echoes it back.
Future<TaskGroup> echoObject(TaskGroup echoObject) =>
this.invokeMethod<TaskGroup, TaskGroup>(
method: platformTestMethod2,
param: echoObject,
serializeParam: (object) => jsonEncode(object.toJson()),
deserializeResult: (data) => TaskGroup.fromJson(jsonDecode(data)),
);
In the process the object is:
- on the flutter side, serialized to JSON and sent to the native side
- on the native side, deserialized to Object and being read
- on the native side, serialized to JSON and sent back as a result to the calling flutter side
- on the flutter side, deserialized to Object and returned as a result to the caller
For method definitions see platform_comm/AppPlatformMethods.dart