Notification can realize the transfer of data from the child component to the parent component, which is the opposite of the transfer direction of InheritedWidget.
I. use NotificationListener to monitor rolling progress
In addition to ScrollNotification, there are SizeChangedLayoutNotification, KeepAliveNotification, LayoutChangedNotification, etc. in the Flutter.
NotificationListener( onNotification: (notification){ print(notification.metrics.pixels); // Current scroll position print(notification.metrics.maxScrollExtent); // Maximum range of rolling work switch (notification.runtimeType){ case ScrollStartNotification: print("Start rolling"); break; case ScrollUpdateNotification: print("Rolling"); break; case ScrollEndNotification: print("Rolling stop"); break; case OverscrollNotification: print("Scroll to boundary"); break; } return true; }, child: ListView.builder( itemCount: 50, itemBuilder: (context, index) { return ListTile(title: Text("$index"),); } ), )
II. Use custom notice
- First create a notification:
class MyNotification extends Notification { final String msg; MyNotification(this.msg); }
- Next, we can use our customized Notifications:
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('Notice received').dispatch(context), child: Text('Sending notice'), ), ) ], ), ), ); } }