Notification可以实现将数据从子组件向父组件传递,与InheritedWidget的传递方向正好相反。
一、使用NotificationListener监听滚动进度
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('发送通知'),
),
)
],
),
),
);
}
}
当点击按钮会发送一个包含信息的通知,在其上层便可监听获取了。