一、InheritedWidget
是flutter中一个功能型widget,适用于widget树中共享数据场景,可以高效将数据在widget中进行跨层传递,例如主题风格Theme。在子wideget中通过theme.of方法 找到上层theme的widget,获得到其属性的同时,建立子widget和上层父wideget的观察者关系,当上层wideget属性改变的时候,子widget也会触发更新。 不过InheritedWidget仅提供数据读的能力,如果想修改数据,则需要把它和statefulWidget的state配套使用。
二、Notification
数据流动方式从子widget向上传递到父widget,这样适用于子widget状态变更,发送通知上报场景。自定义通知的监听首先需要继承Notification类,Notification提供了dispatch方法,可以沿着context对应Element节点树向上逐层发送通知。
三、EventBus
InheritedWidget和Notification都依赖widget树,标志着只有父子关系widget之间进行数据共享,在组件之间没有父子关系场景的时候就需要EventBus了。EventBus是一个三方插件,类似于IOS中的NSNotificationCenter机制。
class CustomEvent {
String msg;
CustomEvent(this.msg);
}
//建立公共的event bus
EventBus eventBus = new EventBus();
//第一个页面
class _FirstScreenState extends State<FirstScreen> {
String msg = "通知:";
StreamSubscription subscription;
@override
initState() {
//监听CustomEvent事件,刷新UI
subscription = eventBus.on<CustomEvent>().listen((event) {
setState(() {msg+= event.msg;});//更新msg
});
super.initState();
}
dispose() {
subscription.cancel();//State销毁时,清理注册
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body:Text(msg),
...
);
}
}
发起eventbus
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
...
body: RaisedButton(
child: Text('Fire Event'),
// 触发CustomEvent事件
onPressed: ()=> eventBus.fire(CustomEvent("hello"))
),
);
}
}
四、总结: