使用这种方法,我们可以使用AnimatedListState的scrollTo和scrollToIndex方法来向下滚动,然后向上滚动。
scrollToEnd() async {
await Future.delayed(Duration(milliseconds: 300));
_listKey.currentState.scrollController.animateTo(
_listKey.currentState.scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 800),
curve: Curves.easeOut,
);
await Future.delayed(Duration(milliseconds: 800));
_listKey.currentState.scrollController.animateTo(
0.0,
duration: Duration(milliseconds: 800),
curve: Curves.easeOut,
);
}
在构建AnimatedList并给AnimatedListState添加scrollController后,我们可以使用方法scrollToEnd()从任何位置触发滚动。
AnimatedList(
key: _listKey,
controller: _animationController,
initialItemCount: _messages.length,
itemBuilder: (BuildContext context, int index, Animation animation) {
// ...
},
),
当用户在屏幕上滚动时,还要更新_scrollToBottom值,以便在下一次插入时知道是否滚动到底部。
_scrollListener() {
if (_listKey.currentState != null &&
_listKey.currentState.scrollController != null &&
_listKey.currentState.scrollController.offset >=
_listKey.currentState.scrollController.position.maxScrollExtent) {
setState(() {
_scrollToBottom = true;
});
} else {
setState(() {
_scrollToBottom = false;
});
}
}