乐趣区

关于flutter: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}
}

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())
    }
}

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 博客(330 个控件用法 + 实战入门系列文章):http://laomengit.com

欢送退出 Flutter 交换群(微信:laomengit)、关注公众号【老孟 Flutter】:

退出移动版