ScrollController animateTo()

12,669

Try wrapping the scroll with PostFrameCallback

WidgetsBinding.instance.addPostFrameCallback((_) {
    double _position =  index * (_width + 2 * _horizontalPadding)
                    + (_selectedWidth+_horizontalPadding);
    _scrollController.animateTo(
                  _position,
                  duration: Duration(milliseconds: 1000),
                  curve: Curves.ease);
}
Share:
12,669

Related videos on Youtube

Omar Farrag
Author by

Omar Farrag

Updated on June 04, 2022

Comments

  • Omar Farrag
    Omar Farrag almost 2 years

    I want the selected item in the horizontal listView to be centered, so I first calculate the position that should animate to (scroll to), and it is always calculated correctly, but when I select an item that is far from the currently selected one, the list doesn't scroll correctly to the calculated position.

    Code:

    double _position =  index * (_width + 2 * _horizontalPadding)
                        + (_selectedWidth+_horizontalPadding);
    _scrollController.animateTo(
                      _position,
                      duration: Duration(milliseconds: 1000),
                      curve: Curves.ease);
    

    where _width is the width of all elements but the selected one, as its width is _selectedWidth , and horizontal padding is constant .. and index is the index of the selected item

  • mohammad
    mohammad about 4 years
    you saved me !!
  • MSaudi
    MSaudi almost 3 years
    This is the only one that worked for me. Thanks a lot.