Flutter 与原生交互

原生与Flutter数据交互,主要就是构建好通道机制 

  • Flutter 与原生交互使用Platform Channel。Flutter定义了三种不同类型的Channel,它们分别是:

BasicMessageChannel:用于传递字符串和半结构化的信息(双向有返回值)。
MethodChannel:用于传递方法调用(method invocation)(双向有返回值)。
EventChannel: 用于数据流(event streams)的通信(仅支持数据单向传递,无返回值)。

  • 三种Channel之间互相独立,各有用途,但它们在设计上却非常相近。每种Channel均有三个重要成员变量:

name:  String类型,代表Channel的名字,也是其唯一标识符。
messager:BinaryMessenger类型,代表消息信使,是消息的发送与接收的工具。
codec: MessageCodec类型或MethodCodec类型,代表消息的编解码器。

效果图

所需知识

构建通道机制Channel

实现代码

BasicMessageChannel

  • Flutter 端
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(getFlutterView(), BASIC_MESSAGE_CHANNEL, StandardMessageCodec.INSTANCE);
    // 接收消息监听
    _basicMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler() {
        @Override
        public void onMessage(Object o, BasicMessageChannel.Reply reply) {
            // 接收flutter数据  并返回数据
            System.out.println("activity-onMessage--flutter传来得数据: " + o);
            reply.reply("已开启免打扰模式" + (count++));
        }
    }); 
  

MethodChannel

  • Flutter 端
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();
                }
            }
        }
    );

EventChannel

  • Flutter 端
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) {
            }
        }
    );

完整代码

查看完整代码

你可能感兴趣的:(Flutter扩展)