我想使用provider
(ChangeNotifierProvider
)和ChangeNotifier
来管理应用程序状态。但是如何从一个模型访问另一个模型中的状态呢?
用例:在聊天应用程序中,一个用于存储用户信息的模型。其他模型使用用户信息(例如用户id)来调用数据库(Firestore)并获取聊天数据流。
例如:
class Model1 extends ChangeNotifier {
final List<Item> items = [];
class Model2 extends ChangeNotifier {
//Access items from Model1 here
items;
这个是可能的吗?我不喜欢有非常大的模型,因为它很难维护。
谢谢!
发布于 2019-06-28 04:39:57
使用provider
,一个模型不能访问另一个模型。
相反,您应该使用ProxyProvider
来组合其他模型。
您的模型将如下所示:
class Foo with ChangeNotifier {
int count = 0;
void increment() {
count++;
notifyListeners();
}
}
class Bar with ChangeNotifier {
int _count;
int get count => _count;
set count(int value) {
if (value != count) {
_count = value;
notifyListeners();
}
}
}
然后你可以这样使用ChangeNotifierProxyProvider
(假设你的窗口小部件树中有一个更高的`ChangeNotifierProvider ):
ChangeNotifierProxyProvider<Foo, Bar>(
initialBuilder: (_) => Bar(),
builder: (_, foo, bar) => bar
..count = foo.count, // Don't pass `Foo` directly but `foo.count` instead
)
发布于 2020-03-06 16:17:04
在v4的ChangeNotifierProxyProvider
中,提供者可以像这样构造:
ChangeNotifierProxyProvider<Foo, Bar>(
create: (_) => Bar(),
update: (_, foo, bar) => bar
..count = foo.count,
)
请注意,initialBuilder:
已更改为create:
,builder:
已更改为update:
发布于 2021-03-02 13:56:17
我已经尝试简单地实现了这一点。
提供程序版本^4.3.3
这里我给出了一个简单的例子
main.dart
ChangeNotifierProxyProvider<AuthProvider, ProductsProvider>(
create: (context) => ProductsProvider(),
update: (context, auth, previousProducts) => previousProducts
..update(auth.token, previousProducts.items == null ? [] : previousProducts.items),
),
authProvider.dart
class AuthProvider with ChangeNotifier {
String _token;
// _token is a response token.
String get token {
return _token;
}
productsProvider.dart
产品是一类单一产品。
class ProductsProvider with ChangeNotifier {
List<Product> _items = [];
String _authToken;
void update(authToken, items) {
_items = items;
_authToken = authToken;
notifyListeners();
}
}
Product.dart
class Product with ChangeNotifier {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product({
@required this.id,
@required this.title,
@required this.description,
@required this.price,
@required this.imageUrl,
this.isFavorite = false,
});
}
https://stackoverflow.com/questions/56798046
复制相似问题