Flutter MultiProvider Classes构造函数问题 [英] Flutter MultiProvider Classes constructors issue
问题描述
我正在使用flutter创建购物应用程序,并使用Provider程序包进行状态管理.一切都很好,只是一个问题.我正在这样声明我的ChangeNotifierProviders.
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(),
));
}
所有课程都一样.
class NotificationManager with ChangeNotifier {
NotificationManager() {
print("Notification manager created");
}
}
现在这些在状态管理方面运行良好,但是我想在其构造上执行一些代码,例如我想在其构造函数中运行代码,但是 AuthStateManager.instance()
, BottomNavigationManager()
和 CartManager()
会在启动时执行代码,但在其余部分执行其他的 LocationManager()
和 NotificationManager()
不在执行代码,我不知道为什么会这样.我对所有班级都做同样的事情.
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.
推荐答案
我不确定这是否是答案,因为我从未使用过它,但是Provider软件包文档中确实说明了以下内容:
I am not sure if this is the answer as I never used it, but the Provider package documentation does states the following:
在使用提供程序的create/update回调时,值得注意的是,默认情况下此回调被延迟调用.这意味着,直到至少一次请求该值,才不会调用create/update回调.
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.
如果是这种情况,那么解决方法是添加带有false值的lazy参数.像这样:
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(创建:(_)=> NotificationManager(),懒惰:false)
这篇关于Flutter MultiProvider Classes构造函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!