简体   繁体   中英

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 eg 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM