I’m having trouble deciding where to define my controller which is used for scrolling.
My Widget is stateless (and I’d like to keep it like that).
Should I define the controller inside the build method, outside the Widget itself or somewhere else?
P.S. Does the fact that the Widget is stateless mean that I can’t dispose of the controller?
I tried creating the controller outside of the Widget but that doesn’t seem very good design wise (global variables…)
2
Answers
If you have the capability to use stacked architecture, you could do as follows.
In pubspec
Your Stateless View
Then stacked will auto generate the necessary code for you to access your controller outside of your stateless widget by running:
in the terminal.
To use the generated code import the file something like
You could use a
ChangeNotifier
. So wrap you widget in aChangeNotifierProvider
(requires theprovider
package) and then initialise the controller in theChangeNotifierProvider
. Then when you build you stateless widget, you can attach the controller to the widget, and then listen to events from the controller, callnotifyListeners()
. For example, this is with aTextEditingController
.ChangeNotifierProvider
Parent widget
Stateless child