我正在尝试了解 Flutter 中的多提供者。在我的应用程序中,一个 Provider 需要根据另一个 Provider 的值进行更改。
AuthProvider 在构建时在小部件树中的较高位置启动。如果可能的话,它就像一个带有自动登录的魅力......
在较低位置的小部件中,我尝试启动另外两个提供程序。一,WhatEver,不依赖于其他数据,并在构建时启动,就像它应该使用 ChangeNotifierProvider 一样。
然而,ProductList 依赖于 AuthProvider。如果登录状态发生更改,则产品列表应相应更新。
在我的尝试中,我发现,即在 SO 上发现,ChangeNotifierProxyProvider 是正确的方法。但是当我运行应用程序时,似乎在构建小部件时没有启动 ChangeNotifierProxyProvider 的“创建”部分。似乎 ProductList 提供程序在被读取或写入之前不会启动。
我对使用 MultiProviders 和 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)
),
],
产品列表如下所示:
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();
}
}