一、flutter和安卓原生交互(flutter调用安卓方法)
flutter中定义的代码
1 在widget中,定义MethodChannel变量
static const MethodChannel methodChannel = MethodChannel("sample.flutter.io/test");
//samples 实际使用可以替换为包名。要跟原生对应即可。
2 通过异步方法调用methodChannel中的invokeMethod方法,指定要调用的activity中的方法
Future<void> _getActivityResult() async {
int result;
try {
final int level = await methodChannel.invokeMethod('getCount'); //通过getCount传递方法名称,类似于广播中的action
result =level;
} on PlatformException {
result = 'Failed to get battery level.';
}
setState(() {
// _result = result;
});
}
android中定义的代码
1 定义channel,与flutter对应
public static String CHANNEL = "sample.flutter.io/test";
2 创建 MethodChannel 并通过 setMethodCallHandler 方法来区分 Flutter 的不同调用方法名和返回对应的
new MethodChannel((FlutterView)flutterView,CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if(methodCall.equals("getCount")){
//to do something
result.success("success");//回调给flutter的参数
}
}
});
总结:flutter和安卓都需要创建MethodChannel,并传入唯一的标识。如demo中的 sample.flutter.io/test 字符串。
调用方methodChannel.invokeMethod('getCount'),被调用方会匹配getCount方法,做相关操作。
被调用方会设置setMethodCallHandler监听,其中就会匹配调用方的调用的getCount方法。
一、flutter和安卓原生交互(安卓调用flutter方法,传值给flutter)
fluuter 端
static const platform = const MethodChannel("sample.flutter.io/test");
//定义MethodChannel,传入唯一标识
@override
void initState() {
super.initState();
platform.setMethodCallHandler(platformCallHandler);//设置监听
}
//实现监听
Future<dynamic> platformCallHandler(MethodCall call) async {
switch (call.method) {
case "RETURN":
int relest = call.arguments;//获取安卓穿过来的值
break;
}
}
android端
MethodChannel methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor(), "sample.flutter.io/test");
methodChannel.invokeMethod("RETURN", 666);
总结: 安卓端调用 methodChannel.invokeMethod("RETURN", 666);
flutter注册监听 platform.setMethodCallHandler(platformCallHandler);//设置监听
匹配 RETURN,从而获得到安卓端传给flutter的值。