1.??前言
在文章Flutter框架分析(八)-Platform Channel中,我们分析了EventChannel的原理和结构,并详细讲解了与其相关的一些核心类,例如StreamHandler和MethodCodec等,本文主要讲解使用EventChannel的示例。
2.??使用流程
EventChannel一般用于事件流的传递,用于将Platform的点击等一系列事件等传递至Platform,仅支持native到Flutter的单向传递,接下来将分析其使用流程。
流程如下:
1)native端创建某channel name的EventChannel。
2)native端使用setStreamHandler函数,设置该EventChannel的StreamHandler。
3)Flutter端创建该channel name的EventChannel。
4)Flutter端创建该EventChannel的广播流,通知native端channel创建完毕,并注册广播接收函数。
5)native端刚刚注册的StreamHandler收到发送的消息,在onListen中处理消息,拿到其中的EventSink接口,通过该接口给Flutter端传递广播。
6)Flutter端处理该广播。
其流程图如下:
Flutter端关键代码如下:
class?_EventChannelState?extends?State<EventChannelWidget> {
??EventChannel?_eventChannelPlugin?=?EventChannel('flutter2/testeventchannel');
??StreamSubscription?_streamSubscription;
??@override
??void?initState() {
????_streamSubscription?=?_eventChannelPlugin
????????.receiveBroadcastStream(["abc",?123,?"你好"]).listen(_onToDart,
????????????onError: _onToDartError, onDone: _onDone);
????super.initState();
??}
??@override
??void?dispose() {
????if?(_streamSubscription?!=?null) {
??????_streamSubscription.cancel();
??????_streamSubscription?=?null;
????}
????super.dispose();
??}
void?_onToDart(message) {
????print("eventchanneltest _onToDart?$message");
??}
void?_onToDartError(error) {
????print("eventchanneltest _onToDartError?$error");
??}
void?_onDone() {
????print("消息传递完毕");
??}
??@override
??Widget?build(BuildContext?context) {
????return?Scaffold(
??????appBar:?AppBar(
????????title:?Text("event channel test"),
??????),
????);
??}
}
native端关键代码如下:
class EventChannelActivity : FlutterActivity(), EventChannel.StreamHandler {
private var eventSink: EventSink? = null
private var mHandler: Handler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mHandler = Handler()
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
Log.d("FirstNativeActivity", "configureFlutterEngine")
initChannel(flutterEngine)
}
private fun initChannel(flutter2Engine: FlutterEngine) {
EventChannel(flutter2Engine.dartExecutor, STREAM).setStreamHandler(this)
}
override fun onListen(arguments: Any, events: EventSink) {
eventSink = events
Log.i(TAG, "onListen Object:$arguments")
Toast.makeText(this, "onListen——obj:$arguments", Toast.LENGTH_SHORT).show()
mHandler!!.postDelayed( {
eventSink!!.success("hello")
eventSink!!.endOfStream()
} , 3000)
}
override fun onCancel(arguments: Any) {
Log.i(TAG, "onCancel:$arguments")
Toast.makeText(this, "onCancel——obj:$arguments", Toast.LENGTH_SHORT).show()
eventSink = null
}
companion object {
private const val TAG = "eventchanneltest"
const val STREAM = "flutter2/testeventchannel"
fun startActivity(activity: Activity) {
val intent = Intent(activity, EventChannelActivity::class.java)
activity.startActivity(intent)
}
}
}
3. 小结
本文主要介绍了EventChannel的使用流程,并列举了一个使用EventChannel的示例。
|