简体   繁体   English

Flutter MultiProvider Classes 构造函数问题

[英]Flutter MultiProvider Classes constructors issue

I am creating a shopping app using flutter and using the Provider package for state management.我正在使用 flutter 创建一个购物应用程序,并使用 Provider 包进行状态管理。 Everything is working super fine just an issue.一切都很好,只是一个问题。 I am declaring my ChangeNotifierProviders like this.我像这样声明我的 ChangeNotifierProviders。

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.现在这些在状态管理方面工作正常,但我想在它们的构造上执行一些代码,例如我想在它们的构造函数中运行代码,但是AuthStateManager.instance()BottomNavigationManager()CartManager()在开始时执行代码但是其余的LocationManager()NotificationManager()没有执行代码,我不知道为什么会这样。 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:我不确定这是否是我从未使用过的答案,但 Provider 包文档确实说明了以下内容:

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.如果是这种情况,那么解决方案是添加值为 false 的 lazy 参数。 Something like so:像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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