【Flutter 混合开发】与原生通信-EventChannel

留略
• 阅读 3777

【Flutter 混合开发】与原生通信-EventChannel

Flutter 混合开发系列 包含如下:

  • 嵌入原生View-Android
  • 嵌入原生View-iOS
  • 与原生通信-MethodChannel
  • 与原生通信-BasicMessageChannel
  • 与原生通信-EventChannel
  • 添加 Flutter 到 Android Activity
  • 添加 Flutter 到 Android Fragment
  • 添加 Flutter 到 iOS

每个工作日分享一篇,欢迎关注、点赞及转发。

EventChannel

Flutter 端

Flutter 端创建 EventChannel 通道,用于与原生端通信:

var _eventChannel = EventChannel('com.flutter.guide.EventChannel');

com.flutter.guide.EventChannel 是 EventChannel 的名称,原生端要与之对应。

监听原生端发送的消息:

var _data;
  @override
  void initState() {
    super.initState();
    _eventChannel.receiveBroadcastStream().listen(_onData);
  }

  _onData(event){
    setState(() {
      _data = event;
    });
  }

Flutter 端完整代码:

class EventChannelDemo extends StatefulWidget {
  @override
  _EventChannelDemoState createState() => _EventChannelDemoState();
}

class _EventChannelDemoState extends State<EventChannelDemo> {

  var _eventChannel = EventChannel('com.flutter.guide.EventChannel');
  var _data;
  @override
  void initState() {
    super.initState();
    _eventChannel.receiveBroadcastStream().listen(_onData);
  }

  _onData(event){
    setState(() {
      _data = event;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Text('$_data'),
      ),
    );
  }
}

Android 端

android 下创建 EventChannelDemo

class EventChannelDemo(var activity: Activity, messenger: BinaryMessenger):EventChannel.StreamHandler {
    private var channel: EventChannel
    private var index = 0
    private var events: EventChannel.EventSink? = null
    init {
        channel = EventChannel(messenger, "com.flutter.guide.EventChannel")
        channel.setStreamHandler(this)
        startTimer()
    }


    fun startTimer() {
        var timer = Timer().schedule(timerTask {
            index++
            var map = mapOf("name" to "laomeng${index}",
                    "age" to "${index}"
            )
            activity.runOnUiThread {
                events?.success(map)
            }

        }, 0, 1000)

    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        this.events = events
    }

    override fun onCancel(arguments: Any?) {
        this.events = null
    }
}

【Flutter 混合开发】与原生通信-EventChannel

events?.success(map) 方法是向 Flutter 端发送数据,此方法必须在主线程执行:

activity.runOnUiThread {
    events?.success(map)
}

MainActivity 启动:

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        EventChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger)
        flutterEngine.plugins.add(MyPlugin())
    }
}

【Flutter 混合开发】与原生通信-EventChannel

iOS 端

ios 下创建 MethodChannelDemo,按如下方式:

import Flutter
import UIKit

public class EventChannelDemo:NSObject, FlutterStreamHandler{
    
    var channel:FlutterEventChannel?
    var count =  0
    var events:FlutterEventSink?
    
    public override init() {
        super.init()
    }
    
    convenience init(messenger: FlutterBinaryMessenger) {
        
        self.init()
        
        channel = FlutterEventChannel(name: "com.flutter.guide.EventChannel", binaryMessenger: messenger)
        channel?.setStreamHandler(self)
        startTimer()
    }
    
    func startTimer() {
        let timer = Timer.scheduledTimer(timeInterval:1, target: self, selector:#selector(self.tickDown),userInfo:nil,repeats: true)
    }
    @objc func tickDown(){
        count += 1
        let args = ["count":count]
        if(events != nil){
            events!(args)
        }
    }
    
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.events = events
        return nil;
    }
    
    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        self.events = nil
        return nil;
    }

}

AppDelegate 启动:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    EventChannelDemo(messenger: controller.binaryMessenger)
    GeneratedPluginRegistrant.register(with: self)
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

【Flutter 混合开发】与原生通信-EventChannel

交流

老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com

欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:

【Flutter 混合开发】与原生通信-EventChannel【Flutter 混合开发】与原生通信-EventChannel
点赞
收藏
评论区
推荐文章
浩浩 浩浩
4年前
Flutter 2.0 下混合开发浅析
多余的前言Flutter2.0发布时,其中最受大家关注之一的内容就是AddtoApp相关的更新,因为除了热更新之外,Flutter最受大家诟病的就是混合开发体验不好。为什么不好呢?因为Flutter的控件渲染直接脱离了原生平台,也就是无论页面堆栈和渲染树都独立于平台运行,这固然给Flutter带来了较好的跨平台体验
Stella981 Stella981
3年前
Flutter与Android混合开发及Platform Channel的使用
1.相对于单独开发Flutter应用,混合开发对于线上项目更具有实际意义,可以把风险控制到最低,也可以进行实战上线。所以介绍集成已有项目2.混合开发涉及原生Native和Flutter进行通信传输,还有插件编写,所以介绍两端通信FlutterPlatformChannel的使用WanAndroid客
Stella981 Stella981
3年前
Flutter混合开发踩坑指北
2020年这个长假因为新型冠状病毒疫情显得格外不一样,好多小伙伴应该已经闲的长毛了,再坚持一下,相信国家很快就会控制住的。这两天实在不知道做啥了,开始跟着keep计划健身,为即将来临的工作热身,今天学习了一下Flutter的混合开发知识。Flutter与Android的原生混合开发学习中遇到一些问题,现在记录如下。首先看一下如何创建一个Flutter
Stella981 Stella981
3年前
DStack
混合开发这项技术由来已久,目前市面上主流的有Hybird,ReactNative,Weex,Flutter等。其中,Flutter以他独有的实现方式,优秀的性能,成为近两年最火的混合开发方案,我们学而思网校1v1客户端团队也是比较早的开始了Flutter技术的研究,在学而思网校1v1家长端和学而思网校1v1教师端两个App进行了大规模的实践尝试,由此也沉淀出
少湖说 少湖说
9个月前
鸿蒙Flutter实战:06-使用ArkTs开发Flutter鸿蒙插件
使用ArkTs开发Flutter鸿蒙平台插件本文讲述如何开发一个Flutter鸿蒙插件,如何实现Flutter与鸿蒙的混合开发,以及双端消息通信。Flutter侧,编写MethodChanneldartconstMethodChannelmethodCha
少湖说 少湖说
9个月前
鸿蒙Flutter实战:07-混合开发
鸿蒙Flutter实战:混合开发鸿蒙Flutter混合开发主要有两种形式。1.基于har将fluttermodule打包成har包,在原生鸿蒙项目中,以har包的方式引入。其优点是主项目开发者可以不关注Flutter实现,不需要安装配置Flutter开发环