赞
踩
Notification可以实现将数据从子组件向父组件传递,与InheritedWidget的传递方向正好相反。
Flutter中很多地方使用了通知,如可滚动(Scrollable) Widget中滑动时就会分发ScrollNotification,而Scrollbar正是通过监听ScrollNotification来确定滚动条位置的。除了ScrollNotification,Flutter中还有SizeChangedLayoutNotification、KeepAliveNotification 、LayoutChangedNotification等。
NotificationListener( onNotification: (notification){ print(notification.metrics.pixels); // 当前滚动位置 print(notification.metrics.maxScrollExtent); // 滚功最大范围 switch (notification.runtimeType){ case ScrollStartNotification: print("开始滚动"); break; case ScrollUpdateNotification: print("正在滚动"); break; case ScrollEndNotification: print("滚动停止"); break; case OverscrollNotification: print("滚动到边界"); break; } return true; }, child: ListView.builder( itemCount: 50, itemBuilder: (context, index) { return ListTile(title: Text("$index"),); } ), )
class MyNotification extends Notification {
final String msg;
MyNotification(this.msg);
}
class NotificationRoute extends StatefulWidget { @override _NotificationRouteState createState() { // TODO: implement createState return _NotificationRouteState(); } } class _NotificationRouteState extends State<NotificationRoute> { String text = ''; @override Widget build(BuildContext context) { // TODO: implement build return NotificationListener( onNotification: (MyNotification notification) { setState(() { text = notification.msg; }); return false; }, child: Center( child: Column( children: <Widget>[ Text('msg: $text'), Builder( builder: (context) => RaisedButton( onPressed: () => MyNotification('接受到通知').dispatch(context), child: Text('发送通知'), ), ) ], ), ), ); } }
当点击按钮会发送一个包含信息的通知,在其上层便可监听获取了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。