说到两者的通讯,也有好几种,但我只学习了最常用的一种,MethodChannel 方式。
(1)flutter向native通讯
先定义好 channel_name.两端都一样。通常定义两个比如
private static final String CHANNEL_NATIVE ="com.example.flutter/native";
(Android 端)
MethodChannel methodChannel =new MethodChannel(mFlutterEngine.getDartExecutor(),CHANNEL_NATIVE);
methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
switch (call.method) {
//这里操作从flutter获取到的数据,就可以愉快的玩耍了。
}
});
这里的mFlutterEngine 就是上篇文章里创建FlutterFragment所需要的对象。
(flutter端)
先定义渠道:static const nativeChannel =const MethodChannel('com.example.flutter/native');
然后在需要通讯的地方调用nativeChannel.invokeMethod("jumpToNative",result);
这样就能被android 端接收
(2)native向flutter通讯
一样先定义。 private static final StringCHANNEL_FLUTTER ="com.example.flutter/flutter";
flutter定义接收
static const flutterChannel =const MethodChannel('com.example.flutter/flutter');
@override
void initState() {
// TODO: implement initState
super.initState();
Future handler(MethodCall call)async{
switch(call.method) {
//接收native传过来的数据
case "onActivityResult":
print(call.arguments["message"]);
break;
}
}
flutterChannel.setMethodCallHandler(handler);
}
然后android调用
Map result =new HashMap<>();
result.put("message", msg);
MethodChannel methodChannel =new MethodChannel(mFlutterEngine.getDartExecutor(),CHANNEL_FLUTTER);
methodChannel.invokeMethod("onActivityResult",result);//发送数据,一般都是用map传送数据
这样就实现两端通讯的效果