說到兩者的通訊杀饵,也有好幾種市袖,但我只學(xué)習(xí)了最常用的一種鸠天,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獲取到的數(shù)據(jù)啥供,就可以愉快的玩耍了。
}
});
這里的mFlutterEngine 就是上篇文章里創(chuàng)建FlutterFragment所需要的對象库糠。
(flutter端)
先定義渠道:static const nativeChannel =const MethodChannel('com.example.flutter/native');
然后在需要通訊的地方調(diào)用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傳過來的數(shù)據(jù)
case "onActivityResult":
print(call.arguments["message"]);
? break;
? ? ? }
}
flutterChannel.setMethodCallHandler(handler);
}
然后android調(diào)用
Map result =new HashMap<>();
result.put("message", msg);
MethodChannel methodChannel =new MethodChannel(mFlutterEngine.getDartExecutor(),CHANNEL_FLUTTER);
methodChannel.invokeMethod("onActivityResult",result);//發(fā)送數(shù)據(jù),一般都是用map傳送數(shù)據(jù)
這樣就實現(xiàn)兩端通訊的效果