我正在尝试实现无限滚动功能.
我尝试使用ListView内部NotificationListener来检测Scroll事件,但我看不到一个事件,说明滚动是否已到达视图的底部.
哪个是实现这个目标的最佳方法?
Col*_*son 24
您可以使用a ListView.builder创建包含无限项的滚动列表.itemBuilder当新细胞被揭示时,您将根据需要被调用.
如果您希望收到有关滚动事件的通知,以便可以从网络加载更多数据,则可以传递controller参数并使用addListener将侦听器附加到ScrollController.所述position的ScrollController可被用于确定滚动是否接近底部.
我想为collin jackson 提供的答案添加示例。参考以下片段
var _scrollController = ScrollController();
_scrollController.addListener(() {
if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
// Perform your task
}
});
Run Code Online (Sandbox Code Playgroud)
这只会在列表中的最后一项可见时触发。
小智 7
_scrollController = new ScrollController();
_scrollController.addListener(
() {
double maxScroll = _scrollController.position.maxScrollExtent;
double currentScroll = _scrollController.position.pixels;
double delta = 200.0; // or something else..
if ( maxScroll - currentScroll <= delta) { // whatever you determine here
//.. load more
}
}
);
Run Code Online (Sandbox Code Playgroud)
应该接受科林的答案....
// create an instance variable
var _controller = ScrollController();
@override
void initState() {
super.initState();
// set up listener here
_controller.addListener(() {
if (_controller.position.atEdge) {
if (_controller.position.pixels == 0)
// you are at top position
else
// you are at bottom position
}
});
}
Run Code Online (Sandbox Code Playgroud)
用法:
ListView(controller: _controller) // assign it like this
Run Code Online (Sandbox Code Playgroud)
更简单的方法是这样的:
NotificationListener<ScrollEndNotification>(
onNotification: onNotification,
child: <a ListView or Wrap or whatever widget you need>
)
Run Code Online (Sandbox Code Playgroud)
并创建一个方法来检测位置:
bool onNotification(ScrollEndNotification t) {
if (t.metrics.pixels >0 && t.metrics.atEdge) {
log('I am at the end');
} else {
log('I am at the start')
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
t.metrics.pixel当用户滚动条位于顶部时为 0,当滚动条位于顶部时则大于 0。
t.metrics.atEdge是true当用户位于滚动条的顶部或滚动条的末尾时,
该log方法来自包import 'dart:developer';