【发布时间】:2021-03-13 13:17:12
【问题描述】:
所以我有这样的东西,它可以与 streamprovider 一起工作。
Stream<List<AppUser>> streamUsers() {
return firestore.collection('users').snapshots().map(
(snapshot) => snapshot.docs
.map((document) => AppUser.fromJson(document.data()))
.toList(),
);
}
我想要实现的是这样的,流将在后台运行,并且每次传输数据时,它都会更新我的提供程序中的本地变量,并通过这种方式通过提供程序通知我的小部件。这是坏主意吗?如果有,为什么?
class AppUsers with ChangeNotifier {
FirebaseFirestore firestore = FirebaseFirestore.instance;
List<AppUser> _users;
List<AppUser> get users => _users;
void streamUsers() {
List<AppUser> users = [];
firestore
.collection('users')
.snapshots()
.map((snapshot) => snapshot.docs.map((document) {
AppUser user = AppUser.fromJson(document.data());
users.add(user);
}));
_users = users;
notifyListeners();
}
}
更新
我能够通过以下代码实现这一点,并在我的应用加载时调用 init()。我想避免在我的应用程序加载时调用 init。有没有更清洁的方法?
List<AppUser> _users = [];
List<AppUser> get users => _users;
init() {
streamUsers().listen((event) {
_users = event;
notifyListeners();
});
}
Stream<List<AppUser>> streamUsers() {
return firestore.collection('users').snapshots().map(
(snapshot) => snapshot.docs
.map((document) => AppUser.fromJson(document.data()))
.toList(),
);
}
【问题讨论】:
标签: flutter dart flutter-provider