0

Can a ChangeNotifierProvider's ChangeNotifier get recreated?

My impression from reading this is that when a ChangeNotifierProvider does create: (context) => SomeChangeNotifier(), SomeChangeNotifier is guaranteed to never be recreated:

This is done one time when the widget is first built, and not on subsequent rebuilds.

This is what I would hope and expect. However, according to the Flutter documentation:

ChangeNotifierProvider is smart enough not to rebuild [its ChangeNotifier] unless absolutely necessary.

Note the "unless absolutely necessary" part, which suggests that the ChangeNotifier can be recreated.

jesper
  • 385
  • 1
  • 4
  • 15
  • If you close your app and then open up again, it's ***absolutely necessary*** to recreate, I guess :-) Or when you navigate to another screen and after that navigate back. – intraector Dec 10 '20 at 00:10

1 Answers1

2

What you need to understand is that the lifecycle of a ChangeNotifier depends on the lifecycle of what you are providing.

for example, if you want the state of a view to be alive all the while the app is not closed, then you would make it global and declare it above the MaterialApp.

But sometimes you might want the recreate the state of a particular view for example,

if the views are so, 1->2->3 then 3rd view might want to be reset, and this time you provide it only above the route which resets the state and rebuilds when accessed again.

I believe this is what

ChangeNotifierProvider is smart enough not to rebuild [its ChangeNotifier] unless absolutely necessary.

means

You could also manually call dispose on it whenever you want even if its provided globally.

sameer kashyap
  • 1,121
  • 1
  • 9
  • 14