I have a ChangeNotifier, and I would like to share it between multiple routes but not all routes:
Page1 is my first page. I need share data of ChangeNotifierProvider with Page2, Page3 and Page only and on enter Page1 call dispose of my ChangeNotifierProvider.
How can I do this using provider?
Provider<String>(create: (context) => 'Hello Flutter'), This time Flutter will look for a String or text; so we've returned a text: “Hello Flutter”. Once we've passed this generic value we can try to access that value anywhere, in the widget tree. However, that value must be provided there inside the build method.
ChangeNotifier is a class that provides change notification to its listeners. That means you can subscribe to a class that is extended or mixed in with ChangeNotifier and call its notifyListeners() method when there's a change in that class.
A Provider that manages the lifecycle of the value it provides by delegating to a pair of Create and Dispose. It is usually used to avoid making a StatefulWidget for something trivial, such as instantiating a BLoC. Provider is the equivalent of a State.
To do so, the easiest solution is to have one provider per route, such that instead of:
Provider(
builder: (_) => SomeValue(),
child: MaterialApp(),
)
you have:
final value = SomeValue();
MaterialApp(
routes: {
'/foo': (_) => Provider.value(value: value, child: Foo()),
'/bar': (_) => Provider.value(value: value, child: Bar()),
'/cannot-access-provider': (_) => CannotAccessProvider(),
}
)
It is, on the other hand, not possible to have your model "automatically disposed".
provider
is not able in such a situation to know that it is safe to dispose of the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With