Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scope a ChangeNotifier to some routes using Provider?

Tags:

flutter

I have a ChangeNotifier, and I would like to share it between multiple routes but not all routes:

enter image description here

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?

like image 609
Adejair Júnior Avatar asked Sep 16 '19 16:09

Adejair Júnior


People also ask

How do you get the provider value in Flutter?

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.

How do you use ChangeNotifier in Flutter?

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.

What is provider in Dart?

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.


1 Answers

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.

like image 129
Rémi Rousselet Avatar answered Nov 09 '22 02:11

Rémi Rousselet