颤动滚动到列表中的特定项目 [英] Flutter scroll to specific item in list
问题描述
我在Flutter中有一个ListView
,允许用户动态添加项目.添加项目后,我希望列表滚动到添加的项目.我在ListView
上附加了ScrollController
,因此可以使用animateTo
滚动,但是我不确定如何确定向下滚动的偏移量.我有这样的东西:
I have a ListView
in Flutter that I allow users to dynamically add items to. After adding an item I would like for the list to scroll to the item that was added. I've attached a ScrollController
to the ListView
so I could use animateTo
to scroll, but I'm unsure of how to determine the offset to scroll down to. I had something like this:
_scrollController.animateTo(
addedIndex.toDouble() * 100,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
其中,addedIndex
是将该项目添加到列表的顺序.但这并不是很有效,并且似乎只有在我能弄清楚列表中每个项目的高度时才能起作用,但我不确定该怎么做.有没有一种更好的方法可以准确地找到要滚动到的位置?
where addedIndex
is the order that the item was added to the list. That doesn't quite work though, and seems like it would only work if I could figure out the height of each item in the list, which I'm not sure how to do. Is there a better way to figure out exactly where to scroll to?
推荐答案
首先,创建一个新的globalKey.
First, create a new globalKey.
final GlobalKey globalKey = GlobalKey();
第二,将globalKey添加到要移动到的小部件.
Second, add globalKey to the widget you want to move to.
然后,基于globalKey获取窗口小部件的位置.
Then, get the widget location based on globalKey.
RenderBox box = globalKey.currentContext.findRenderObject();
Offset offset = box.localToGlobal(Offset.zero);
获得的窗口小部件位置是相对于当前页面显示状态的,窗口小部件的高度包括状态栏和AppBar的高度.
The widget position obtained is relative to the current page display status , widget height includes status bar and AppBar height.
状态栏高度
import 'dart:ui’;
MediaQueryData.fromWindow(window).padding.top
AppBar高度56.0
AppBar height 56.0
scrollView的偏移量需要添加
scrollView's offset need to add
double animationHeight = _controller.offset + offset.dy - MediaQueryData.fromWindow(window).padding.top - 56.0;
_controller.animateTo(animationHeight, duration: Duration(milliseconds: 500), curve: Curves.decelerate);
希望它会对您有所帮助.
hope it will help you.
这篇关于颤动滚动到列表中的特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!