1

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
  • 79
  • 3
  • 10

1 Answers1

1

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();
}
Akif
  • 7,098
  • 7
  • 27
  • 53
Mustafa yıldiz
  • 325
  • 1
  • 8
  • 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. – Muneeb Ahmad Nov 23 '20 at 17:24
  • then try _controller.position.extentAfter. Put this variable into if condition and send a request with it. – Mustafa yıldiz Nov 24 '20 at 09:23