用订阅者模式实现消息的广播,通过event_bus可实现对事件的触发与监听。
一、安装event_bus
event_bus: ^1.1.0
二、event_bus
event_bus中两个比较重要的方法是on
、fire
方法,其中on
方法用来监听消息,fire
用来发送消息。
Stream<T> on<T>() {
if (T == dynamic) {
return streamController.stream;
} else {
return streamController.stream.where((event) => event is T).cast<T>();
}
}
void fire(event) {
streamController.add(event);
}
三、event_bus的使用
import 'package:flutter/material.dart';
import 'package:flutterdemo/event/event_bus.dart';
class EventBusRoute extends StatefulWidget{
@override
_EventBusRouteState createState() => _EventBusRouteState();
}
class _EventBusRouteState extends State<EventBusRoute>{
String text = '';
@override
Widget build(BuildContext context) {
// 监听消息on<T>,T为监听的消息类型,与fire发送的消息类型一致
ApplicationEvent.eventBus.on<String>().listen((event){
this.setState(()=>this.text = event);
});
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('event_bus_demo'),
),
body: Container(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
// 发送消息
ApplicationEvent.eventBus.fire('123');
},
child: Text('发送消息'),
),
Container(
child: Text(text),
)
],
),
),
);
}
}
event_bus.dart
import 'package:event_bus/event_bus.dart';
class ApplicationEvent{
static EventBus eventBus = EventBus();
}