美文网首页
Flutter与Native交互的方式

Flutter与Native交互的方式

作者: 我说的这句话是谎话 | 来源:发表于2019-10-12 18:19 被阅读0次

Flutter与Native交换主要是使用PlatformChannel功能

PlatformChannel

Platformchannle分为三种类型

  • BasicMessageChannel
  • MethodChannel
  • EventChannel

BasicMessageChannel

用于传递数据。Flutter与原生项目的资源是不共享的,可以通过BasicMessageChannel 来获取Native项目的图标等资源

MethodChannel

传递方法调用。Flutter主动调用Native的方法,并获取相应的返回值。比如获取系统电量,发起Toast等系统API,可以通过这个完成。

EventChannel

传递事件。Native将时间通知到Flutter。比如Flutter需要监听网络情况。EventChannel可以将Flutter的一个监听器交给Native,Native去做网络广播的监听,当收到广播之后借助 EventChannel调用Flutter注册的监听,完成对Flutter的事件通知。

具体实现

BasicMessageChannel

  • Flutter

    static const messageChannel = const BasicMessageChannel('samples.flutter.io/message', StandardMessageCodec());
    
    static const messageChannel2 = const BasicMessageChannel('smaples.flutter.io/message2', StandardMessageCodec());
    
    Future<String> sendMessage() async {
        String reply = await messageChannel.send('发送给Native的数据');
        print('reply: $reply');
        return reply;
    }
    
    void receiveMessage() {
        messageChannel2.setMessageHandler((message) async {
           print('message : $message');
            return '从Native端返回来的数据';
        });
    }
    
    @Override
    void initState() {
        super.initState();
        receiveMessage();
        sendMessage();
    }
    
  • iOS 先不动

  • Android

    BasicMessageChanngl messageChannel = new BasicMessageChannel<Object>(getFlutterView(), "samples.flutter.io/message2", StandardMessageCodes.INSTANCE);
    
    // 接收来自Flutter的消息
    messageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
        @Override
        public void onMessage(object o, BasicMessageChannel.Reply<Object> reply) {
            Log.d("jimbray", "OnMessage" + o);
            reply.reply("返回给Flutter的数据");
        }
    });
    
    // 发送数据给Flutter
    BasicMessageChannel messageChannel2 = new BasicMessageChannel<Object>(
    getFlutterView(), "samples.flutter.io/message2", StandardMessageCodec.INSTANCE);
    
    // 发送消息到Flutter
    messageChannel2.send("发送到Flutter的消息", new BasicMessageChannel.Reply<Object>() {
       @Override
        public void reply(Object o) {
            Log.d("jimbray", "onReply: " + o);
        }
    });
    

MethodChannel

  • Flutter

    static const platform = const MethodChannel('samples.flutter.io/battery');
    
    Future<Null> _getBatteryLevel() async {
        String batteryLevel;
        try {
          final int result = awai platform.invokeMethod('getBatteryLevel');
          batteryLevel = 'BatteryLevel at $result %';
        } on PlatformException catch(e) {
            batterylevel = 'Failed to get battery levet: "${e.message}".';
        }
        
        setState(() {
            _batteryLevel = batterLevel;
        });
    }
    
  • iOS先不动

  • Android

    new MethodChannel(getFlutterView(), "samples.flutter.io/battery").setMethodCallHandler(new MethodCallHandler() {
        @Override
        public void onMethodCall(MethodCall call, Result result) {
            if (call.method.equals("getBatteryLevel")) {
                int batteryLevel = _getBatteryLevel();
                
                if (batteryLevel != -1) {
                    result.success(batteryLevel);
                } else {
                    result.error("UNAVAILABLE", "Battery level is not available.", null);
                }
            } else {
                result.notImplemented();
            }
        }
    });
    
    private int getBatterylevel() {
        // 实现Android平台的 getBatteryLevel 代码即可
    }
    

EventChannel

  • Flutter

    static const EventChannel _eventChannel = const EventChannel('samples.flutter.io/test');
    
    void _onEvent(Object event) {
        print('从Native发送过来的消息内容: $event');
    }
    
    void _onError(Object error) {
        print('从Native发送过来的错误');
    }
    
    @Override
    void initState() {
        super.initState();
        _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
    }
    
  • iOS先不动

  • Android

    new EventChannel(getFlutterView(), "samples.flutter.io/test").setStreanHandler(
    new EventChannel.StreamHandler() {
        @Override
        public void onListen(Object o, EventChannel.EventSink eventSink) {
            this.eventSink = eventSink;
        }
        
        @Override
        public void onCancel(Object o) {
            
        }
        
        
    });
    
    private EventChannel.EventSink eventSink;
    private int count = 0;
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage();
            eventSink.success((count++) + "主动发送消息到Flutter");
        }
    }
    

相关文章

网友评论

      本文标题:Flutter与Native交互的方式

      本文链接:https://www.haomeiwen.com/subject/lukcmctx.html