一均芽、Flutter交互初始化
1丘逸、初始化Method Channel,定義交互名:message Method Channel
static const methodChannel = MethodChannel('messageMethodChannel');
2掀宋、flutter發(fā)起原生調(diào)用
methodChannel.invokeMethod(method, arguments);
其中method為調(diào)用原生函數(shù)對應(yīng)key,arguments為傳遞數(shù)據(jù)深纲,可多個任意類型值仲锄;同時返回值為Future<T>,則可通過await或者then進行回調(diào)監(jiān)聽:
HiChannel.invokeMethod(HiChannel.PERMISSION, {
'permissions': [HiPremissionKey.ACCESS_FINE_LOCATION]
}).then((value) {
if (value) {
homeIsLocation(() {
eventBus.fire(UpdateDataEvent());
yesCallback();
}, noCallback);
}
});
3湃鹊、flutter監(jiān)聽原生調(diào)用
methodChannel.setMethodCallHandler((call) {
if (call.method == TOAST) {
toast(call.arguments);
} else if (call.method == SHOW_LOADING) {
showLoading();
} else if (call.method == HIDE_LOADING) {
hideLoading();
}
return Future(() => "接受成功");
});
通過調(diào)用setMethodCallHandler監(jiān)聽原生調(diào)用儒喊,其中call.method為調(diào)用函數(shù)對應(yīng)的key,call.arguments為傳遞數(shù)據(jù)币呵,可為任意類型值怀愧。并原生可監(jiān)聽flutter的回調(diào);
其中flutter回調(diào)通知原生余赢,通過return Future(() => "接受成功");實現(xiàn)芯义。
二、Android原生相關(guān)
1没佑、Main Activity繼承FlutterActivity類毕贼,并實現(xiàn)configureFlutterEngine函數(shù):如下:
其中優(yōu)先初始化調(diào)用監(jiān)聽:
methodChannel = MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"messageMethodChannel"
)
其中messageMethodChannel為flutter初始化時定義的交互名。
2蛤奢、調(diào)用監(jiān)聽函數(shù)setMethodCallHandler鬼癣,如下:
通過call.method判斷調(diào)用方法。call.argument<String>("error")獲取flutter傳遞數(shù)值啤贩。調(diào)用完畢后待秃,可通過result.success(value)進行回調(diào)flutter,其中value為任意類型值痹屹。
3章郁、Android原生調(diào)用Flutter函數(shù)代碼
調(diào)用invokeMethod函數(shù)實現(xiàn)。其中method為調(diào)用函數(shù)key志衍,arguments為傳遞參數(shù)暖庄。并監(jiān)聽Result回調(diào)。通過success獲取楼肪。
三培廓、IOS原生相關(guān)
1、在application中初始化iOS通信
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(name: "messageMethodChannel", binaryMessenger: controller.binaryMessenger)
2春叫、調(diào)用監(jiān)聽函數(shù)setMethodCallHandler
channel.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
if (call.method == "sendData") {
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
result(["name":"hello,\(name)","age":age])
}
}
}
其中call.method為調(diào)用函數(shù)key肩钠,call.arguments為傳遞參數(shù)值。并且通過result(value)進行回調(diào)暂殖,value為任意類型參數(shù)价匠。
3、IOS原生主動向Flutter發(fā)送數(shù)據(jù)
channel.invokeMethod(method, arguments:args)