在widget树中,子widget滚动时会向上发送notification,通过NotificationListener可以监控到该notification。NotificationListener也是一个widget,可以将被监控的widget放入其child内。
1 2 3 4 5 6
| NotificationListener const NotificationListener({ Key key, @required this.child, 被监控的子widget树 this.onNotification, 监控到notification后的回调方法。 })
|
onNotification(ScrollNotification notification)
, 此方法需要一个返回值,表示是否拦截住notification,如果是true,那么notifcation到此为止;如果是false,那么notification会继续向更外层widget传递。参数ScrollNotification包含了监听到的信息。
1 2 3 4 5
| ScrollNotification ScrollNotification({ @required this.metrics, 所有信息都在这里存储 @required this.context, });
|
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
| class _MyHomePageState extends State<MyHomePage> {
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification){ ScrollMetrics metrics = notification.metrics; print(metrics.pixels); print(metrics.atEdge); print(metrics.axis); print(metrics.axisDirection); print(metrics.extentAfter); print(metrics.extentBefore); print(metrics.extentInside); print(metrics.maxScrollExtent); print(metrics.minScrollExtent); print(metrics.viewportDimension); print(metrics.outOfRange); print('------------------------'); return true; }, child: ListView.builder( itemExtent: 50, itemCount: 50, itemBuilder: (BuildContext context,int index){ return ListTile(title: Text(index.toString()),); }, ), ), ); } }
|
输出值:
1 2 3 4 5 6 7 8 9 10 11 12 13
| I/flutter (30825): 1896.5714285714284 I/flutter (30825): true I/flutter (30825): Axis.vertical I/flutter (30825): AxisDirection.down I/flutter (30825): 0.0 I/flutter (30825): 1896.5714285714284 I/flutter (30825): 603.4285714285714 I/flutter (30825): 1896.5714285714284 I/flutter (30825): 0.0 I/flutter (30825): 603.4285714285714 I/flutter (30825): false I/flutter (30825): ------------------------
|
转自:https://www.jianshu.com/p/6dc3cca1d99a