一、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传递方法名称,类似于广播中的actionresult =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() {@Overridepublic void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {if(methodCall.equals("getCount")){//to do somethingresult.success("success");//回调给flutter的参数}}});
总结:flutter和安卓都需要创建MethodChannel,并传入唯一的标识。如demo中的 sample.flutter.io/test 字符串。
调用方methodChannel.invokeMethod('getCount'),被调用方会匹配getCount方法,做相关操作。
被调用方会设置setMethodCallHandler监听,其中就会匹配调用方的调用的getCount方法。