Where is the best place to put my ChangeNotifierProvider?

79 Views Asked by At

I use ChangeNotifierProvider.

The consumer who will use this ChangeNotifierProvider exists only in one widget, not across multiple widgets.

So I want to register ChangeNotifierProvider only for that widget and use it as a consumer. At this time, inefficiency occurs

(build first "blank screen" -> information load by calling function in consumer(after build is done by using delayed function) -> rebuild).

when i tried to load information by call a function in my viewModel(consumer) in build, it makes error because notifyListeners() function is called and it try to rebuild while build is not done. So I had no choice but to first build a blank screen and then call a function to initialize the information.

So, I try to register ChangeNotifierProvider at the top, but since the top is login (the top of all apps), this registration is not inefficiency too. documentation says:(You don’t want to place ChangeNotifierProvider higher than necessary (because you don’t want to pollute the scope))!

I'm wondering if I can do it. What choice should I make?

  1. Register ChangeNotifierProvider in the corresponding widget and use it as a consumer.

  2. Register ChangeNotifierProvider at the top (login widget) and use it by subscribing to the necessary widgets as a consumer.

  3. Use another method

1

There are 1 best solutions below

0
On

you should add provider in the main.dart file, if there are multiple providers then you can use MultiProvider for that