如何在Flutter中获取ScrollView中的子滚动偏移位置

lan*_*224 5 flutter

我制作了一个 CustomScrollView 小部件,其中包含:

  • 银应用栏

  • Sliver持久标头

  • 银格

  • Sliver持久标头

  • 银格

SliverPercientHeader 将是 SliverGrid 中项目的描述,一旦点击(我用 GestureDetector 包裹它),我希望滚动偏移量在 SliverPercientHeader 所在的中间发生变化。

怎么做?ScrollController 似乎只知道滚动范围,到目前为止,我还没有在 ScrollView (CustomScrollView 继承的)中看到任何可以给我单个小部件的偏移位置的属性。

mko*_*lys 2

根据文档,ScrollController有一个 offset 属性:https://api.flutter.dev/flutter/widgets/ScrollController/offset.html这就是获取当前偏移量的方法。

如果你想滚动到特定位置,可以使用方法animateTo: https: //api.flutter.dev/flutter/widgets/ScrollController/animateTo.html。例如:

scrollController.animateTo(123, duration: Duration(seconds: 1), curve: Curves.easeIn);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您应该计算要滚动的偏移值(示例中为 123)。

如果您需要“查找”该偏移值,一种方法是使用小部件上的键并使用 RenderObject 获取它的位置。这个答案对此进行了解释:https ://stackoverflow.com/a/54303022/15427566