'Calling dispose function in stateless widget using provider
I maintain a state of a counter(let say) in a separate Singelton class I am using provider in my app and I want to reset that state when I pop the current screen widget will it be possible.
Note: I want to use the stateless widget as in stateful its possible but any idea about achieving this in stateless.Like some sort of dispose function in changeNotifier provider.
Solution 1:[1]
Any class extended with ChangeNotifier
gets an Dispose function you can override.
Example:
class MyClass with ChangeNotifier {
@override
void dispose() {
// dispose your stuff here
super.dispose();
}
}
Solution 2:[2]
ChangeNotifierProvider() and ChangeNotifierProvider.value() is different. ChangeNotifierProvider() will set dispose method, but ChangeNotifierProvider.value() won't.
ChangeNotifierProvider({
Key? key,
required Create<T> create,
bool? lazy,
TransitionBuilder? builder,
Widget? child,
}) : super( key: key, create: create, dispose: _dispose, lazy: lazy, builder: builder, child: child, );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cas |
Solution 2 | fat eagle |