工作中用到了 flutter和Android原生的交互 写个demo 方便以后用
方式1
MethodChannel 该方式是Android原生和flutter直接互相传值
首先在flutter中定义一个方法 然后在点击事件中调用这个方法 比如
这样就会调用MethodChannel的方法
然后 在Android原生代码中也就是Android目录下的MainActivity 重写configureFlutterEngine方法
其中MethodChannel 定义的值 要和flutter中定义MechodChannel的参数保持一直 这样当flutter调用_startNativeActivity的时候 就会执行setMethodCallHandler方法 然后从call.method 匹配调用的方法名称 从call.argument获取传递的参数 最后调用result.success 返回给flutter
log打印日志如下:
第二种交互方式 EventChannel 该方法flutter监听Android 原生的消息 比如 网络状态的变动 音量的大小等
首先在flutter 定义方法
class MyEventChannel { static const EventChannel _eventChannel = EventChannel("my_event_channel"); static Stream<dynamic> get eventStream { return _eventChannel.receiveBroadcastStream(); } }这样就注册了接收器 当Android原生发送消息的时候 就会自动接收到消息 我们这里使用StreamBuilder来接收
然后在Android 原生中 我们模拟 个场景 每隔1秒向flutter发送一个数字
第三种方式 通过platFormView 调用Android原生组件通信
首先 在flutter中定义一个组件 比如我这里是NativeView
定义sendMessageToNative方法 和原生通信 这里我们是用来修改Android原生TextView的内容
这里要注意的几个点 这里的viewType 要和等会在Android原生中定义的值要一样 然后在onPlatformViewCreated回调中 获取到id 这个id 然后再onPressed方法中将这个id 通过methodChanel.invokeMethod方法传递到Android原生
然后在Android原生代码中 在configureFlutterEngine方法中注册PlatformView
这里的nativeChannel 要和在flutter中androidView中的viewType一样
这里我们运行 模拟器上显示的是
我们点击图片按钮 触发sendMessageToNative方法 此时 你会发现TextView的值已经变成我们从flutter传递过来的值了
记录下