如何使用scroll_to_index在Flutter中自动滚动随机生成的列表项?

时间:2019-08-28 07:23:55

标签: listview flutter

我有两个listviews,其中物品是随机生成的。这些列表视图相互嵌套。我想以某种方式滚动到某个索引,但是滚动到索引并不会导致正确的位置。

ListView.separated(
      shrinkWrap: true,
      itemCount: Random().nextInt(10),
      controller: _scrollController,
      itemBuilder: (context, index) {
        return AutoScrollTag(
          key: ValueKey(index),
          child: Container(
            color: Color(0xffF4F7FA),
            padding: EdgeInsets.all(16.0),
            margin: EdgeInsets.only(top: 8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  //  18+8+8
                  child: Text(
                    "SP",
                    style: TextStyle(
                        fontSize: 18.0, fontWeight: FontWeight.w500),
                  ),
                ),
                ListView.builder(
                    shrinkWrap: true,
                    physics: ClampingScrollPhysics(),
                    itemCount: Random().nextInt(7),
                    itemBuilder: (context, index) {
                      return Text("Something $index");
                    })
              ],
            ),
          ),
          index: index,
          controller: _scrollController,
        );
      },
      separatorBuilder: (BuildContext context, int index) {
        return SizedBox(
          height: 2.0,
        );
      },
    )

这是_scrollController

 AutoScrollController(

  //add this for advanced viewport boundary. e.g. SafeArea
  viewportBoundaryGetter: () => Rect.fromLTRB(
      0, 0, 0, MediaQuery.of(context).padding.bottom),

  //choose vertical/horizontal
  axis: Axis.vertical,

)

这是scrollToIndex(index)方法所做的

        _scrollController.scrollToIndex(3, preferPosition: AutoScrollPosition.begin);

0 个答案:

没有答案