flutter 事件总线如何使用
在Flutter中如何使用事件总线进行组件间通信?具体需要引入哪个库,能否提供一个简单的代码示例说明如何注册事件和触发事件?不同页面之间通过事件总线传值时有哪些需要注意的地方?
2 回复
Flutter事件总线(如EventBus)使用步骤:
- 创建EventBus实例:
EventBus myBus = EventBus(); - 注册监听:
myBus.on<EventType>().listen((event) { ... }); - 发送事件:
myBus.fire(EventType(data)); - 取消监听:
subscription.cancel();
注意:避免内存泄漏,及时取消订阅。
更多关于flutter 事件总线如何使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在 Flutter 中,事件总线(Event Bus)用于实现组件间的解耦通信,常用 event_bus 库。以下是使用方法:
1. 添加依赖
在 pubspec.yaml 中:
dependencies:
event_bus: ^2.0.0
2. 创建事件总线实例
import 'package:event_bus/event_bus.dart';
EventBus eventBus = EventBus();
3. 定义事件类
class UserLoggedInEvent {
final String username;
UserLoggedInEvent(this.username);
}
4. 发送事件
eventBus.fire(UserLoggedInEvent('张三'));
5. 监听事件
// 在 initState 中订阅
late StreamSubscription subscription;
@override
void initState() {
super.initState();
subscription = eventBus.on<UserLoggedInEvent>().listen((event) {
print('用户登录: ${event.username}');
});
}
// 在 dispose 中取消订阅
@override
void dispose() {
subscription.cancel();
super.dispose();
}
6. 全局使用建议
在应用中创建全局的 EventBus 实例:
// event_bus.dart
class GlobalEventBus {
static final EventBus instance = EventBus();
}
注意事项:
- 记得在
dispose中取消订阅避免内存泄漏 - 适合跨组件通信,但简单状态管理推荐使用 Provider 或 Bloc
- 事件类最好使用不可变数据
这样就能在任意 Widget 间通过事件总线通信了。

