Flutter数据(事件)传递
1.构造方法属性传递
在前面的文章中我们多次使用到自定义Widget并传入相应的参数,这就是最简单的数据传递方法,上层通过下层Widget的构造方法将值传递给下层widget。
就比如下面的例子,我们定义了一个MyPageView的View,构造方法需要传入,leading和content两个参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class MyPageView extends StatelessWidget { final Widget _leading; final Widget _content;
MyPageView(this._leading, this._content);
@override Widget build(BuildContext context) { return Card( margin: EdgeInsets.all(30), color: Colors.white, elevation: 15, shadowColor: Colors.grey, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), child: ListTile( leading: _leading, title: _content, ), ); } }
|
我们在调用的地方就需要传入这两个属性,这样以来数据就从上层传递到了下层。
1 2 3 4 5 6 7
| MyPageView( Icon( Icons.home, color: Colors.blueAccent, ), Text("我是内容")), )
|

实现起来非常的简单,但是如果碰见多级别View的情况怎么办?对的,那么你的参数就需要从最上层一层一层的往下传递。
这就要用到我们下面要说到的内容了
InheritedWidget 是 Flutter 中的一个功能型 Widget,在构建Widget的同时可以在Widget层中向下传递,适用于在 Widget 树中共享数据的场景。通过它,我们可以高效地将数据在 Widget 树中进行跨层传递。
可能大家对InheritedWidget比较陌生,但是实际上我们会在很多场景中接触这个东西,比如我们常用的MediaQuery,和theme都会为我们提供很多有用的功能,比如
1
| MediaQuery.of(context).devicePixelRatio
|
来获取设备分辨率
或者
1
| Theme.of(context).accentColor
|
来获取主题颜色
这其中都用到了InheritedWidget,当上层的Theme或者分辨率发生变更时下层的所有Widget都会发生变更,
InheritedWidget的数据是从上往下传递的。
接下来,我们就使用一个简单的例子来看下如何使用InheritedWidget,还是以计数器为例。
我们先声明一个数据类用来存储计数器的值
1 2 3 4 5
| class MyInheritedModel { final int count;
const MyInheritedModel(this.count); }
|
然后定义CountContainer继承InheritedWidget来完成数据的更新判断与获取工作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class CountContainer extends InheritedWidget { static CountContainer of(BuildContext context) => context.inheritFromWidgetOfExactType(CountContainer) as CountContainer; final MyInheritedModel model;
CountContainer({ Key key, @required this.model, @required Widget child, }) : super(key: key, child: child); @override bool updateShouldNotify(CountContainer oldWidget) => myInheritedModel != oldWidget.myInheritedModel; }
|
在CountContainer方法中,我们使用of方法来返回CountContainer对象,使用updateShouldNotify来判断数据是否可以更新。
在使用的地方调用CountContainer.of(context)方法即可获取CountContainer并获取model中的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| void main() { runApp(new MaterialApp( home: CountContainer( child: MyApp(), model: MyInheritedModel(100), ), )); }
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { CountContainer container = CountContainer.of(context); return Scaffold( appBar: AppBar( title: Text("InheritedWidget"), ), body: Center( child: Text("Count:${container.model.count}"), ), ); } }
|

通过InheritedWidget我们可以实现数据的从上往下层传递,无论有多少成的嵌套我们都可以获取到它。
但是如果想要修改InheritedWidget中的值,通常情况下我们还是需要用到State。
具体代码见下方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| void main() { runApp(new MaterialApp( home: MyApp(), )); }
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); }
class _MyAppState extends State<MyApp> { MyInheritedModel _inheritedModel = new MyInheritedModel(0);
add() { setState(() { _inheritedModel.count++; }); }
@override Widget build(BuildContext context) { return CountContainer(model: this, child: ContentWidget(), increment: add); } }
class ContentWidget extends StatelessWidget { @override Widget build(BuildContext context) { CountContainer container = CountContainer.of(context); return Scaffold( appBar: AppBar( title: Text("InheritedWidget"), ), body: Center( child: Text("Count:${container.model._inheritedModel.count}"), ), floatingActionButton: FloatingActionButton( onPressed: container.increment, child: Icon(Icons.add), ), ); } }
class MyInheritedModel { int count; MyInheritedModel(this.count); }
class CountContainer extends InheritedWidget { static CountContainer of(BuildContext context) => context.inheritFromWidgetOfExactType(CountContainer) as CountContainer; final _MyAppState model; final Function() increment;
CountContainer({ Key key, @required this.model, @required Widget child, @required this.increment, }) : super(key: key, child: child);
@override bool updateShouldNotify(CountContainer oldWidget) => model != oldWidget.model; }
|
可以看到,我们把model改为State,使InheritedWidget持有State这样我们就可以通过InheritedWidget在任意的地方调用State中setStete方法来更新数据。

3.Notification
Notification中文意思是通知,与Android中的广播机制类似,在Flutter中Notification的功能是子节点状态变更,发送通知上报。
Notification的数据变更是通过Widgte树向上冒泡的,我们往往在下层Wdiget发送通知然后在上层处理通知。
首先我们创建通知类
1 2 3 4
| class MyNotification extends Notification { final String info; MyNotification(this.info); }
|
然后创建子Widget发送通知
1 2 3 4 5 6 7 8 9 10 11
| class ChildWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: RaisedButton( onPressed: () => MyNotification("我是随机下面发送的数据:${Random().nextInt(1000)}").dispatch(context), child: Text("提交"), ), ); } }
|
最后我们创建parentWidgte使用NotificationListener接收通知并显示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class ParentWidget extends StatefulWidget { @override _ParentWidgetState createState() => _ParentWidgetState(); }
class _ParentWidgetState extends State<ParentWidget> { String msg = "";
onReceiveMessage(String message) { setState(() { msg =message; }); }
@override Widget build(BuildContext context) { return NotificationListener<MyNotification>( child: Column( children: [Text(msg), ChildWidget()], ), onNotification: (notification) { onReceiveMessage(notification.info); return true; }, ); } }
|
我们在界面上放置了一个按钮,每次点击按钮们就会发送一个随机数通知,上层Widget通过监听获得下层发送的通知并并过SetState方法来更新UI。
看下效果:

4.EventBus
在上面的文章中我们具体了解了InheritedWidget从上往下的数据传递,和Notification从下往上的数据传递,虽然都可以实现数据跨多层传递的效果,但是他们都必须依赖于Wdiget树,没有办法脱离Wdiget使用。
下面我们就来介绍下Flutter中第三方组件EventBus的用法。
既然是事件总线,肯定是遵循发布/订阅模式的,允许任何订阅者接收并处理事件。
因为EventBus是第三方库,所以我们需要在 pubspec.yaml 引入它
1 2
| dependencies: event_bus: ^1.1.1
|
首先我们创建CustomEvent事件类
1 2 3 4 5
| class CustomEvent { String info;
CustomEvent(this.info); }
|
然后创建EventBus并监听事件,在任意位置调用 eventBus.fire()即可发送事件,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class HomePage extends StatefulWidget { @override _MyState createState() => _MyState(); }
class _MyState extends State<HomePage> { EventBus eventBus = new EventBus(); String info = "";
@override void initState() { super.initState(); eventBus.on<CustomEvent>().listen((event) { setState(() { info = event.info; }); }); }
@override void dispose() { eventBus.destroy(); super.dispose(); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("EventBusTitle"), ), body: Container( child: Center( child: Column( children: [ Text(info), RaisedButton( child: Text("发送"), onPressed: () { eventBus.fire( CustomEvent("我是随机下面发送的数据:${Random().nextInt(1000)}")); }, ) ], ), ), ), ); } }
|
当然效果与前面的Notification基本一致

小结
- 使用构造方法可以传递数据,但是多层传递比较麻烦
- InheritedWidget可以沿着Wdiget树自上往下传递数据,尽量放在子Widget上一层
- Notification可以沿着Widget自下往上传递数据
- EventBus不用依赖Widget树可以在任何位置传递事件。