Flutter与原生通信之EventChannel
EventChannel
是原生向Flutter
传递数据流的通道,属于单向传输,只能由原生端调用,Flutter
端是接收信息,常见的有网络变化监听,屏幕横竖屏切换,位置切换,电池电量,远程通知等事件。
下面结合iOS
端代码来描述下使用方法
Flutter
端代码
final eventChannel = const EventChannel('test_event_channel');
定义channel
Future<void> setEventChannel() async {
_streamSubscription = eventChannel.receiveBroadcastStream().listen((event) {
print('Flutter收到了原生端的事件:$event');
}, onError: (error) {
print(error);
}, onDone: () {
print('done');
}, cancelOnError: true);
}
组件初始化中设置回调
- 闭包第一个回调为
onData
,参数event
为泛型,表示原生端返回的信息内容 onError
: 报错会执行
/// Otherwise it is called with just the error object.
/// If [onError] is omitted, any errors on this stream are considered unhandled,
/// and will be passed to the current [Zone]'s error handler.
/// By default unhandled async errors are treated
/// as if they were uncaught top-level errors.
onDone
: 时间完成会执行
/// If this stream closes and sends a done event, the [onDone] handler is
/// called. If [onDone] is `null`, nothing happens.
cancelOnError
: 报错后是否取消事件
/// If [cancelOnError] is `true`, the subscription is automatically canceled
/// when the first error event is delivered. The default is `false`.
iOS
原生端
class EventChannelManager: NSObject {
var channel: FlutterEventChannel
var eventSink: FlutterEventSink?
var count = 0
var timer: Timer?
init(messager: FlutterBinaryMessenger) {
channel = FlutterEventChannel(name: "test_event_channel", binaryMessenger: messager)
}
func config() {
channel.setStreamHandler(**self**)
}
func startTimer() {
timer = Timer(timeInterval: TimeInterval(2), target: self, selector: #selectortriggerEventChannel), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: .common)
}
@objc func triggerEventChannel() {
count += 1
eventSink?("当前数值为:\(count)")
}
}
extension EventChannelManager : FlutterStreamHandler {
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = events
startTimer()
return nil
}
func onCancel(withArguments arguments: **Any**?) -> FlutterError? {
return nil
}
}
AppDelegate
中调用:
let eventChannelManager = EventChannelManager(messager: messager)
eventChannelManager.config()
和其他两种通信方式不同的是,EventChannel
需要在原生端实现 FlutterStreamHandler
协议,获取到 FlutterEventSink
,用它来进行消息的发送
eventSink?("当前数值为:\(count)")
打印结果如下: