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

时间:2017-11-18 15:46:58

标签: flutter

将新项目(例如ListTile)添加到ListView时,有没有办法将新添加的项目滚动到视图中?新项目可能不在列表的底部(例如,按字母顺序排序)。

3 个答案:

答案 0 :(得分:2)

您可以使用ScrollController滚动浏览ListView

final scrollController = ScrollController();

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

您必须自己确定身高。这可以使用商品的索引和一般商品高度来完成。

full example available here

答案 1 :(得分:0)

您可以使用 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(),
)

答案 2 :(得分:0)

也许不一定要扩展@creativecreator,否则,如果您想在添加项目后执行此操作,则当然需要提示它以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);
  }