Shahzad Akram
Shahzad Akram

Reputation: 5254

Flutter MultiProvider Classes constructors issue

I am creating a shopping app using flutter and using the Provider package for state management. Everything is working super fine just an issue. I am declaring my ChangeNotifierProviders like this.

void main() {
  runApp(MultiProvider(
    providers: <SingleChildWidget>[
      ChangeNotifierProvider(create: (_) => AuthStateManager.instance()),
      ChangeNotifierProvider(create: (_) => CartManager()),
      ChangeNotifierProvider(create: (_) => LocationManager()),
      ChangeNotifierProvider(create: (_) => BottomNavigationManager()),
      ChangeNotifierProvider(create: (_) => NotificationManager()),
    ],
    child: EvendorApp(),
  ));
}

All classes are like.

class NotificationManager with ChangeNotifier {
  NotificationManager() {
    print("Notification manager created");
  }
}

Now these are working fine in terms of state management, but I want to execute some code on their construction e.g. I wanna run code in their constructors, but AuthStateManager.instance() , BottomNavigationManager() and CartManager() are executing codes on start but rest of others LocationManager() and NotificationManager() are not executing code, I don't know why is this happening. I am doing the same for all classes.

Upvotes: 1

Views: 649

Answers (1)

Eduardo
Eduardo

Reputation: 554

I am not sure if this is the answer as I never used it, but the Provider package documentation does states the following:

When using the create/update callback of a provider, it is worth noting that this callback is called lazily by default. What this means is, until the value is requested at least once, the create/update callbacks won't be called.

If it's the case here, then the solution would be to add the lazy parameter with a value of false. Something like so:

ChangeNotifierProvider(create: (_) => NotificationManager(), lazy: false)

Upvotes: 4

Related Questions