如何滚动ListView中的项目以使其可见?

7

当向ListView添加新项(例如ListTile)时,是否有一种方法可以将新添加的项滚动到视图中?新项可能不在列表底部(例如按字母顺序排序)。


有没有办法将新添加的项目滚动到视图中?-> 你是不是想让屏幕自动滚动到新添加的项目? - Arnold Parge
这个回答解决了你的问题吗?Flutter:在ListView中滚动到一个小部件 - TWL
3个回答

4
你可以使用 ScrollController 来滚动 ListView
final scrollController = ScrollController();

// ...
ListView(controller: scrollController // ...
);
// ...
scrollController.animateTo(height, duration: Duration(milliseconds: 678), 
  curve: Curves.ease);

你需要自己确定高度。可以使用项目的索引和通用项目高度来完成此操作。

这里有一个完整的示例


1
这个解决方案对我不适用,因为我的应用程序具有不同类型的内容(文本、照片、视频、联系人、位置),它们在 ListView 中的高度确实会有所变化(非相同)。感谢您的建议。 - Kamlesh

3
您可以使用 quire-io 团队的以下库将 ListView 滚动到指定位置:

https://github.com/quire-io/scroll-to-index

ListView(
  scrollDirection: scrollDirection,
  controller: controller,
  children: randomList.map<Widget>((data) {
    final index = data[0];
    final height = data[1];
    return AutoScrollTag(
      key: ValueKey(index),
      controller: controller,
      index: index,
      child: Text('index: $index, height: $height'),
      highlightColor: Colors.black.withOpacity(0.1),
    );
  }).toList(),
)

1

在 @creativecreatorormaybenot 的基础上进行扩展,如果您想在添加项目后执行此操作,当然需要使用setstate来提示其绘制,但还有其他一些关键要素。例如,此代码将自动滚动,以便在构建列表后可见列表末尾:

class MyList extends StatefulWidget {
  @override
  _MyState createState() => _MyState();
}

class _MyState extends State<MyList> {
  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
  }

  void _onAfterBuild(BuildContext context) {
    _scrollController.animateTo(double.maxFinite, /* <- the offset in units to scroll to */
        duration: Duration(milliseconds: 1), curve: Curves.ease);
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) => _onAfterBuild(context));

    return ListView.builder(
        controller: _scrollController,
        //initialScrollIndex: appState.doseEvents?.length ?? 0,
        itemCount: 20,
        itemBuilder: (BuildContext ctxt, int index) {
          return Row(
            children: <Widget>[
              Text("A"),
              Text("B"),
              Text("C"),
            ],
          );
        });
  }
}

如果您想跳转到特定的项目,您需要在_onAfterBuild中计算该项目的偏移量。例如:
  void _onAfterBuild(BuildContext context) {
    double scrollPos = _mostRecentlyAddedIndex * _itemHeight;
    _scrollController.animateTo(scrollPos, 
        duration: Duration(milliseconds: 1), curve: Curves.ease);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接