Search code examples
flutterlistviewflutter-listviewscrollcontroller

How best to make my scroll controllers available throughout the app?


Context: I'll be having a couple of scrollable lists in my app and I always want to scroll them to the latest item whenever an item is added.

Problem: My ListView.builders and the places where items are added are going to be quite far apart in my widget tree. Passing around all those scroll controllers via constructors seems to be super awkward.

My Solution:As I'm practising with Provider at the moment, I came up with a working solution using Provider:

class ScrollControllerProvider with ChangeNotifier {
  ScrollController _paneController = ScrollController();
  //setting up all other controllers here later

  get paneController {
    return _paneController;
  }

  void scrollHistory() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if (_paneController.hasClients) {
        _paneController.jumpTo(_paneController.position.maxScrollExtent);
      }
    });
  }
}

I'll add all scroll controllers to that provider and grab what I need, where I need it. It already works with one, but someone on reddit told me it's not a good idea, as scroll controllers should be disposed. Im not super knowledgeable on the topic of life cycle yet and find it difficult to assess this.

Questions: Is it really a bad idea to use Provider here? Can you help me to understand why? If yes, what is the best approach to solve this issue?


Solution

  • Provider is not the problem, using a disposable item inside a provider is. ScrollController is a disposable item related to its main Widget, or better to say its State.

    If you want to notify your widgets about newly added items, create a variable inside the provider and listen to that variable in your widgets, then use your ScrollController to change the position.

    To find out more about your question take a look at ScrollController class and Disposable class