flutter android 开发笔记(三.flutter调用android方法,并拿到返回值,展示在flutter控件或者native控件)
作者:互联网
1,创建flutter消息通道
mFlutter2MethodChannel = new MethodChannel(flutter2Engine.getDartExecutor(), "flutter2/flutter2Java");//字符串的含义跟JsBridge中的js和native互相调用的含义差不多,flutter中要是用这个消息通道时,也要设置为一样的 mFlutter2MethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call == null || result == null){ if (result!=null){ result.error("-1","MethodCall is null",new Exception("MethodCall is null")); } return; } if ("getJavaMethod".equals(call.method)){ result.success("success "); } else { result.success(" unKnow"); } } });
2,flutter调用native方法
static const platform = const MethodChannel("flutter2/flutter2Java");//跟安卓代码中设置的通道名称字符串一样 Future<Null> _getJavaMethod() async { String str; try { print("dart -_getJavaMethod"); //在通道上调用此方法 final String intValue = await platform.invokeMethod("getJavaMethod");//这个参数是跟安卓协商的,相当于一个变量名,安卓用来筛选flutter需要调用的方法用的 str = 'getJavaMethod $intValue .'; } on Exception catch (e) { str = "Failed to getJavaMethod: '${e.toString()}'."; } setState(() { print("dart -setState"); _counter = str; }); }
3,flutter调用结果
标签:控件,调用,getJavaMethod,result,android,null,flutter,MethodChannel 来源: https://www.cnblogs.com/fengchuxiaodai/p/13026440.html