需求:
在列表无人操作时自动下滚,并在触碰边界/用户操作时停一下再继续滚动,在触底时回滚到顶部
思路:
1. 列表两种状态:滚动和静止,可使用定时器使定时移动列表位置实现下滚,使用flagforscroll判断当前列表所处状态
//开头用Future.delayed推迟几秒是因为使用后端数据,立即绑定的话可能会因为列表组件
//未获得数据导致_scrollController绑定失败,该错误可能没有报错..
Future.delayed(Duration(seconds: 4)).then((_) {
_timerforautoscroll =
Timer.periodic(const Duration(milliseconds: 100), (timer) {
if (flagforscroll == 0) {//列表下滚
_offset++;
_scrollController.jumpTo(_offset);
} else if (flagforscroll == 1) {//使用动画过渡列表顶部
// scrollpauses(5, 0);
_scrollController.animateTo(0.0,
duration: Duration(milliseconds: 1000),
curve: Curves.linear); // 滚动回到顶部
}
});
2. addListener监听列表所处状态,并调用 scrollpauses(10, 1);做相应改变
// 滚动监听事件
_scrollController.addListener(() {
if (_scrollController.position.pixels <= 0) {
//触顶
scrollpauses(10, 0);
} else if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent) {
//触底
scrollpauses(10, 1);
}
});
});
3.scrollpauses控制静止时间与列表状态转换
//手势操作时自动滚动暂停 flagforisscroll 0触顶 1触底 3用户操作
void scrollpauses(int second, int flagforisscroll) {
flagforscroll = 3;
Future.delayed(Duration(seconds: second)).then((_) {
if (flagforisscroll == 0) {
_offset = 0;
flagforscroll = 0;
} else if (flagforisscroll == 1) {
flagforscroll = 1;
} else if (flagforisscroll == 3) {
_offset = _scrollController.position.pixels;
flagforscroll = 0;
}
});
}