How do I get the current scroll offset inside a Flutter ListView, SliverList
, etc?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
- If you're inside the scroll view use
Scrollable.of(context).position.pixels
. - If you're outside, you probably want to hand a
ScrollController
in as the controller argument of the scroll view, then you can readcontroller.offset
. - Alternatively, use scroll notifications with
NotificationListener
.
This was asked on Flutter Gitter, and answered: https://gitter.im/flutter/flutter?at=591243f18a05641b1167be0e
回答2:
For someone else, looking for code implementation, you can use ScrollController
like this:
ScrollController _scrollController;
@override
void initState() {
super.initState();
_scrollController = ScrollController()
..addListener(() {
print("offset = ${_scrollController.offset}");
});
}
@override
Widget build(BuildContext context) {
return ListView(
controller: _scrollController,
children: <Widget>[],
);
}
@override
void dispose() {
_scrollController.dispose(); // it is a good practice to dispose the controller
super.dispose();
}