6

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?

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432

1 Answers1

3

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.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432