原生与Flutter数据交互,主要就是构建好通道机制
BasicMessageChannel:用于传递字符串和半结构化的信息(双向有返回值)。
MethodChannel:用于传递方法调用(method invocation)(双向有返回值)。
EventChannel: 用于数据流(event streams)的通信(仅支持数据单向传递,无返回值)。
name: String类型,代表Channel的名字,也是其唯一标识符。
messager:BinaryMessenger类型,代表消息信使,是消息的发送与接收的工具。
codec: MessageCodec类型或MethodCodec类型,代表消息的编解码器。
构建通道机制Channel
static const BasicMessageChannel _basicMessageChannel = const BasicMessageChannel('flutter_demo_jiaohu.flutter.io/basic_message_channel', StandardMessageCodec());
// 向原生发送 数据 并接收返回数据
String reply = await _basicMessageChannel.send(userController.text.trim());
private static final String BASIC_MESSAGE_CHANNEL = "flutter_demo_jiaohu.flutter.io/basic_message_channel";
_basicMessageChannel = new BasicMessageChannel
static const MethodChannel _methodChannel = const MethodChannel('flutter_demo_jiaohu.flutter.io/method_channel');
final int result = await _methodChannel.invokeMethod('getBatteryLevel');
private static final String METHOD_CHANNEL = "flutter_demo_jiaohu.flutter.io/method_channel";
new MethodChannel(getFlutterView(), METHOD_CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
// TODO 接收数据 并返回
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
}
);
static const EventChannel _eventChannel = const EventChannel('flutter_demo_jiaohu.flutter.io/event_channel');
void initState() {
super.initState();
// 监听开始 原生发来数据
_eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
}
void _onEvent(Object event) {
print('Flutter - 返回的内容: $event');
setState(() {
obj = event;
});
}
void _onError(Object error) {
print('Flutter - 返回的错误');
setState(() {
obj = error;
});
}
private static final String EVENT_CHANNEL = "flutter_demo_jiaohu.flutter.io/event_channel";
new EventChannel(getFlutterView(), EVENT_CHANNEL).setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
eventSink.success("主动发送消息给flutter" + (count++));
}
@Override
public void onCancel(Object o) {
}
}
);
查看完整代码