如何在Flutter的ListView
,GridView
,SliverList
等中获取当前滚动偏移量?
如何在Flutter的ListView
,GridView
,SliverList
等中获取当前滚动偏移量?
Scrollable.of(context).position.pixels
。ScrollController
作为滚动视图的控制器参数传递,然后可以读取 controller.offset
。NotificationListener
进行滚动通知。这是在 Flutter Gitter 上提出的问题,并得到了回答:https://gitter.im/flutter/flutter?at=591243f18a05641b1167be0e
对于其他人寻找代码实现,您可以像这样使用ScrollController
:
NotificationListener
:NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
print(scrollNotification.metrics.pixels); // <-- This is it.
return false;
},
child: ListView.builder(
itemCount: 200,
itemBuilder: (c, i) => Text('Item $i'),
),
)
ScrollController.offset
final ScrollController _controller = ScrollController();
@override
void initState() {
super.initState();
_controller.addListener(() {
print(_controller.offset); // <-- This is it.
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: _controller,
itemCount: 200,
itemBuilder: (c, i) => Text('Item $i'),
),
);
}
NotificationListener
。NotificationListener(
child: ListView(
controller: _scrollController,
children: ...
),
onNotification: (notification) {
if (notification is ScrollEndNotification) {
print(_scrollController.position.pixels);
}
return false;
},
)