Search code examples
flutterdartlistviewindexing

How to get current index of listview in flutter?


I have list include 5 items, i want get current index when scroll. I was use scrollcontroller and addListener it. But when use this way it will lag when scroll. I want instead it with another way. How to do it? Thank for everyone!

I was try with similar code is:

void _scrollListener() {
    int firstVisibleIndex = _scrollLayoutController.hasClients
        ? (_scrollLayoutController.offset / _itemHeight).floor()
        : 0;

    setState(() {
      _currentIndex = firstVisibleIndex;
    });
  }

Solution

  • I was solve issue when use timer, this helps reduce the number of index calculations and prevents unnecessary updates during continuous scrolling, leading to better performance.

    class Debouncer {
      final Duration delay;
      Timer? _timer;
    
      Debouncer(this.delay);
    
      void call(VoidCallback action) {
        _timer?.cancel(); // Cancel any previous timer that hasn't executed yet
        _timer = Timer(delay, action); // Create a new timer to execute the action after the specified delay
      }
    
      void cancel() {
        _timer?.cancel();
      }
    }
    
    class Throttle {
      final Duration delay;
      Timer? _timer;
      bool _canCall = true;
    
      Throttle(this.delay);
    
      void call(VoidCallback action) {
        if (_canCall) {
          _canCall = false; // Mark that a function call is in progress
          action(); // Execute the action
          _timer = Timer(delay, () {
            _canCall = true; // Allow the next function call after the specified delay
          });
        }
      }
    
      void cancel() {
        _timer?.cancel(); 
        _canCall = true;
      }
    }
    void _scrollListener() {
        _debouncer(() {
          int firstVisibleIndex = _scrollLayoutController.hasClients
              ? (_scrollLayoutController.offset / _itemHeight).floor()
              : 0;
    
          setState(() {
            _currentIndex = firstVisibleIndex;
          });
        });
      }