Flutter List View Builder Scroll Controller is not working

743

You need to call your fetchData function inside the addListener of ScrollController. Here is a proper example of the use of ScrollController:

@override
  void initState() {
    _feedController = new ScrollController()..addListener(function);
    super.initState();
  }


void function(){
   print("scrolling");
   _fetchData();
}
Share:
743
Muneeb Ahmad
Author by

Muneeb Ahmad

Updated on December 01, 2022

Comments

  • Muneeb Ahmad
    Muneeb Ahmad over 1 year

    I have a Instagram like app with stories on the top and then feed data. I want my feed list view to scroll to the top in a function (i.e. button click or whatever).

      ScrollController _feedController;
     
      @override
      void initState() {
        _feedController = new ScrollController();
        _feedController.addListener(() {
          print("scrolling");
        });
        _fetchData();
        super.initState();
      }
    
      // This is in the build function.
      return ListView.builder(
          padding: EdgeInsets.all(0.0),
          shrinkWrap: true,
          controller: _feedController,
          physics: ClampingScrollPhysics(),
          itemCount: _listFeed.length,
          itemBuilder: (BuildContext context, int index) {
            return ProductWidget(
              product: _listFeed[index],
              navigateOnImage: true,
            );
          },
        );
    
      // This function should scroll the list view to the top.
      refresh() {
        _fetchData();
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          _feedController.animateTo(
            0.0,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        });
        print("home screen refreshed");
      }
    
    

    I am initializing my controller on initState() and added a listener. neither the listener nor the controller's animateTo() function is working. I have also tried using WidgetsBinding.instance.addPostFrameCallback(). What am I missing.. ??

  • Muneeb Ahmad
    Muneeb Ahmad over 3 years
    The listener was just so i could so if its printing something or not.. what i really wanna do is just scroll my list view to the top in my refresh() function. i dont need to fetch data every time the user scrolls.
  • Mustafa yıldiz
    Mustafa yıldiz over 3 years
    then try _controller.position.extentAfter. Put this variable into if condition and send a request with it.