【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 EventChannel 通信 )
文章目錄
- 一、EventChannel 簡介
- 二、EventChannel 在 Dart 端的實現
- 1、EventChannel 構造方法
- 2、創建廣播流 Stream
- 3、設置監聽回調函數
- 4、EventChannel 使用流程
- 三、相關資源
一、EventChannel 簡介
EventChannel 一般用于持續的通信 , 如 : 將 Android 應用中采集的陀螺儀 , GPS 等信息 , 持續的發送給 Flutter 應用 ;
該通信時單向的 , 收到信息的一方無法回復 ;
二、EventChannel 在 Dart 端的實現
1、EventChannel 構造方法
EventChannel 的構造函數原型如下 :
class EventChannel {/// Creates an [EventChannel] with the specified [name].////// The [codec] used will be [StandardMethodCodec], unless otherwise/// specified.////// Neither [name] nor [codec] may be null. The default [ServicesBinding.defaultBinaryMessenger]/// instance is used if [binaryMessenger] is null.const EventChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger]): assert(name != null),assert(codec != null),_binaryMessenger = binaryMessenger;/// The logical channel on which communication happens, not null.final String name;/// The message codec used by this channel, not null.final MethodCodec codec; }EventChannel 構造方法參數說明 :
-
String name 參數 : Channel 通道名稱 , Native 應用端 與 Flutter 中的 Channel 名稱 , 必須一致 ;
-
MethodCodec<T> codec 參數 : 消息編解碼器 , 默認類型是 StandardMethodCodec ; Native 應用端 與 Flutter 中的消息編解碼器也要保持一致 ;
2、創建廣播流 Stream
創建了 EventChannel 實例對象之后 , 調用
/// Sets up a broadcast stream for receiving events on this channel.////// Returns a broadcast [Stream] which emits events to listeners as follows:////// * a decoded data event (possibly null) for each successful event/// received from the platform plugin;/// * an error event containing a [PlatformException] for each error event/// received from the platform plugin.////// Errors occurring during stream activation or deactivation are reported/// through the [FlutterError] facility. Stream activation happens only when/// stream listener count changes from 0 to 1. Stream deactivation happens/// only when stream listener count changes from 1 to 0.Stream<dynamic> receiveBroadcastStream([ dynamic arguments ]) {}方法 , 可以創建一個 廣播流 Stream , 調用該 Stream 實例對象的 listen 方法 , 可以注冊消息持續監聽 , 用于從 Channel 消息通道中持續接收消息 ; 如果要停止監聽 , 可以調用 Stream 的 cancel 方法 ;
receiveBroadcastStream 方法參數 / 返回值 說明 :
- [ dynamic arguments ] 參數 : 監聽 Native 傳遞來的消息時 , 向 Native 傳遞的數據 ;
- Stream<dynamic> 返回值 : 創建的監聽用的廣播流 ;
注意 : 消息的監聽 , 和 取消監聽 , 一定個要一一對應 , 防止出現
3、設置監聽回調函數
調用 Stream 的 listen 方法 , 傳入兩個方法參數 ,
StreamSubscription<T> listen(void onData(T event)?,{Function? onError, void onDone()?, bool? cancelOnError});第一個參數 void onData(T event) , 參數為 T 泛型 , 返回值 void , 這是消息到來后回調的函數 ;
Function? onError 參數 , 參數 和 返回值都是 void , 這是出現錯誤后回調的函數 ;
代碼示例 :
// 注冊 EventChannel 監聽_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回調的方法(message) {setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});},onError: (error){print(error);});4、EventChannel 使用流程
使用流程 :
首先 , 導入 Flutter 與 Native 通信 的 Dart 包 ;
import 'package:flutter/services.dart'; import 'dart:async';然后 , 定義并實現 EventChannel 對象實例 ;
static const EventChannel _eventChannel =EventChannel('EventChannel');/// 監聽 EventChannel 數據的句柄late StreamSubscription _streamSubscription;接著 , 創建廣播流 , 并監聽消息 , 一般在 initState 方法中設置監聽 ;
@overridevoid initState() {// 注冊 EventChannel 監聽_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回調的方法(message) {setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});},onError: (error){print(error);});super.initState();}最后 , 如果監聽完畢 , 取消監聽 ; 這樣可以防止不必要的內存泄漏 ;
@overridevoid dispose() {// 取消監聽_streamSubscription.cancel();super.dispose();}三、相關資源
參考資料 :
- Flutter 官網 : https://flutter.dev/
- Flutter 插件下載地址 : https://pub.dev/packages
- Flutter 開發文檔 : https://flutter.cn/docs ( 強烈推薦 )
- 官方 GitHub 地址 : https://github.com/flutter
- Flutter 中文社區 : https://flutter.cn/
- Flutter 實用教程 : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart 中文文檔 : https://dart.cn/
- Dart 開發者官網 : https://api.dart.dev/
- Flutter 中文網 : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter 相關問題 : https://flutterchina.club/faq/ ( 入門階段推薦看一遍 )
- GitHub 上的 Flutter 開源示例 : https://download.csdn.net/download/han1202012/15989510
- Flutter 實戰電子書 : https://book.flutterchina.club/chapter1/
- Dart 語言練習網站 : https://dartpad.dartlang.org/
重要的專題 :
- Flutter 動畫參考文檔 : https://flutterchina.club/animations/
博客源碼下載 :
-
GitHub 地址 : ( 隨博客進度一直更新 , 有可能沒有本博客的源碼 )
- Flutter Module 工程 : https://github.com/han1202012/flutter_module
- Android 應用 : https://github.com/han1202012/flutter_native
- 注意 : 上面兩個工程要放在同一個目錄中 , 否則編譯不通過 ;
-
博客源碼快照 : https://download.csdn.net/download/han1202012/21670919 ( 本篇博客的源碼快照 , 可以找到本博客的源碼 )
總結
以上是生活随笔為你收集整理的【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 EventChannel 通信 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Flutter】Flutter 混合开
- 下一篇: 【错误记录】Flutter 混合开发报错