Flutter List View Builder Scroll Controller is not working

1.9k views Asked by At

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.. ??

1

There are 1 answers

2
Mustafa yıldiz On

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