如何在flutter中显示scrollController的滚动索引?

Ahm*_*abi 4 dart flutter

我想通过利用滚动控制器在 listView 底部显示索引,与下图中显示的方式相同:

在此输入图像描述

用户向下滚动或向上滚动后,左侧以红色突出显示的计数会根据用户的滚动方向增加/减少。

我想要实现的是自动更新显示项目的索引,如图中红色所示。因此,每当用户向下或向上滚动时,该索引就会根据显示项目的索引进行更新。

图为我已经到了第26项了。每当我向下或向上滚动时,该索引就会更新。

我尝试使用为滚动事件发出的偏移量,但没有成功。

Rod*_*Rod 6

方法是像您一样使用滚动控制器。

您需要使用已知的项目大小和侦听器。

// Declaring the controller and the item size
ScrollController _scrollController;
final itemSize = 100.0;

// Initializing
@override
void initState() {
  _scrollController = ScrollController();
  _scrollController.addListener(_scrollListener);
  super.initState();
}

// Your list widget (must not be nested lists)
ListView.builder(
      controller: _scrollController,
      itemCount: <Your list length>,
      itemExtent: itemSize,
      itemBuilder: (context, index) {
          return ListTile(<your items>);
      },
),

// With the listener and the itemSize, you can calculate which item
// is on screen using the provided callBack. Something like this:
void _scrollListener() {
  setState(() {
    var index = (_scrollController.offset / itemSize).round() + 1;
  });
}
Run Code Online (Sandbox Code Playgroud)

向scrollController 添加监听器将在每次滚动列表时调用提供的回调。您可以使用相同的逻辑处理列表的许多行为,包括识别触发侦听器的事件类型、滚动方向等。