问题描述
我试图了解Flutter中的多提供商.在我的应用中,一个提供商需要根据另一提供商的值进行更改.
I'm trying to understand multiproviders in Flutter. In my App, one Provider need to change based on a value from an other Provider.
AuthProvider在构建时在小部件树中更高一级启动.如果可能的话,可以自动登录,就像超级按钮一样.
AuthProvider gets initiated higher up in the widget tree on build. Works like a charm with automatic sign in if possible...
在较低位置的小部件中,我尝试启动其他两个提供程序.其中之一,WhatEver,不依赖于其他数据,而是像应该使用ChangeNotifierProvider一样在构建时启动.
In a lower placed widget, I try to initiate two other Providers. One, WhatEver, is not depended on other data and gets initiated on build like it is supposed to using ChangeNotifierProvider.
ProductList但是取决于AuthProvider.如果登录状态更改,则ProducList应该相应地更新.
ProductList however is depended on AuthProvider. If log in status is changed, the ProducList should update accordingly.
在我的尝试中,我发现,即在SO上发现,ChangeNotifierProxyProvider是正确的方法.但是,当我运行该应用程序时,似乎在构建小部件时未启动ChangeNotifierProxyProvider的创建"部分.似乎在读取或写入ProductList提供程序之前,不会启动它.
In my attempts, I've found out, ie found on SO, that ChangeNotifierProxyProvider is the right way to go. But when I run the App, it seems like the 'create'-part of ChangeNotifierProxyProvider is not initiated when the widget gets build. It seems like the ProductList provider is not initiated until it's read or written to.
我使用MultiProviders和ChangeNotifierProxyProvider误解了什么?
What have I misunderstood using MultiProviders and ChangeNotifierProxyProvider?
return MultiProvider(
providers: [
ChangeNotifierProvider<WhatEver>(create: (context) => WhatEver()),
ChangeNotifierProxyProvider<AuthProvider, ProductList>(
create: (_) => ProductList(Provider.of<AuthProvider>(context, listen: false)),
update: (_, auth, productList) => productList..reloadList(auth)
),
],
ProductList看起来像这样:
The ProductList looks like this:
final AuthProvider _authProvider;
static const String _TAG = "Shop - product_list.dart : ";
ProductList(this._authProvider) {
print(_TAG + "ProductList Provider initiated");
reloadList(this._authProvider);
}
void reloadList(AuthProvider authProvider) {
print(_TAG + "ProductList reload started");
if (authProvider.user==null) {
print(_TAG + "ProductList: _authProvider == null");
_loadBuiltInList();
} else {
print(_TAG + "ProductList: user = " + authProvider.user.displayName);
_loadFirestoreList();
}
}
推荐答案
我有执行此操作的代码:
I have code that does this:
ChangeNotifierProxyProvider<AuthService, ProfileService>(
create: (ctx) => ProfileService(),
update: (ctx, authService, profileService) =>
profileService..updateAuth(authService),
),
我的ProfileService()在构造AuthService时并不依赖于它.该代码可以正常工作:)
My ProfileService() does not rely on AuthService being available when it is constructed. The code works fine :)
ChangeNotifierProxyProvider文档明确描述了这种方法:
The ChangeNotifierProxyProvider documentation explicitly describes this approach:
这篇关于未在构建时启动ChangeNotifierProxyProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!