Flutter中經(jīng)常使用event_bus實現(xiàn)跨頁面?zhèn)鬟f數(shù)據(jù)藏杖,其核心是基于Dart Streams(流)破喻。event_bus是一個典型的采用訂閱發(fā)布模式設(shè)計伪阶,包含發(fā)布者和訂閱者兩種角色唧领,可以通過事件總線來觸發(fā)事件和監(jiān)聽事件逆瑞。
使用
安裝
event_bus: ^1.1.0
創(chuàng)建EventBus
import 'package:event_bus/event_bus.dart';
/// 創(chuàng)建EventBus
EventBus eventBus = EventBus();
定義事件UpdateAppEvent
/// 更新App版本事件
class UpdateAppEvent {
final String from;
final String version;
final String title;
final List description;
final bool forcedUpdate;
final String link;
UpdateAppEvent(this.from, this.version, this.title, this.description, this.forcedUpdate, this.link);
@override
String toString() {
return "UpdateAppEvent {from: $from, version: $version, title: $title, description: $description, forcedUpdate: $forcedUpdate, link: $link}";
}
}
注冊事件監(jiān)聽器
import 'dart:async';
/// 監(jiān)聽版本檢查事件
StreamSubscription _busSubscription = eventBus.on<UpdateAppEvent>().listen((event) {
updateAppDialog.show(context, event);
});
觸發(fā)訂閱的事件
eventBus.fire(
UpdateAppEvent(
pageHome,
remoteVersion,
title,
remoteDescription,
forcedUpdate,
link,
),
);
銷毀已訂閱事件
@override
void dispose() {
_busSubscription.cancel();
super.dispose();
}