How to access a controller from multiple screens - flutter

Viewed 40

Let's say I created a ScrollController in a statefullWidget like so:

  late ScrollController controller;

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

Using this controller indside the widget is easy. But, if I want to access that controller from another screen, I have to pass it as a parameter maybe like so:

Navigator.pushNamed(context, '/another-screen', arguments: controller);

But, What if the screens are totally independent? (I can't pass it as an argument) I thought of using Provider to globally provide the controller. But now, I can't dispose it.

1 Answers

try to add on global late ScrollController controller; and then initialise that variable you can declare on main.dart late ScrollController controller;

Related