Ahmed Dolabi
Ahmed Dolabi

Reputation: 485

How to display scrolling index for scrollController in flutter?

I would like to display the index at the bottom of the listView by utilizing the scrollController, the same way it's displayed in the follow image :

enter image description here

After the user scrolls down, or scrolls up, the count on the left, highlighted by red, gets increased/decreased based on the scroll direction of the user.

What I want to achieve is to automatically update the displayed item's index, indicated by red on the picture. So whenever the user scrolls down or up, this index gets updated by the displayed item's index.

The picture shows that I have reached the 26th item. Whenever I scroll down or up, this index gets updated.

I have tried using the offset that is getting emitted for the scrolling event with no luck.

Upvotes: 5

Views: 10085

Answers (2)

Rod
Rod

Reputation: 1651

The way is using the scroll controller like you were doing.

You need to use a known item size and a listener.

// 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;
  });
}

Adding a listener to a scrollController will call the callback provided every time the list is scrolled. You can handle many behaviours of the list using the same logic, including identifying the type of event that fired the listener, the direction of the scroll, etc.

Upvotes: 8

Alperen Ekin
Alperen Ekin

Reputation: 318

https://medium.com/flutter-community/create-shop-list-with-flutter-d13d3c20d68b Maybe this one can help you. Also source code is available. A simple math about item height might help.

Upvotes: 0

Related Questions