我有:
my-app
community-list
附加上,my-app获取用户并加载app.user。同时,附加了社区列表(甚至在加载app.user之前),因此我还无法获得该用户的已加星标社区。因此,我正在研究的解决方案如下。
在community-list.attached()中:
app.changes.listen((List<ChangeRecord> records) {
if (app.user != null) {
getUserStarredCommunities();
}
});
有人说社区列表中的其他方法:
// This is triggered by an app.changes.listen.
void getUserStarredCommunities() {
// Determine if this user has starred the community.
communities.forEach((community) {
var starredCommunityRef = new db.Firebase(firebaseLocation + '/users/' + app.user.username + '/communities/' + community['id']);
starredCommunityRef.onValue.listen((e) {
if (e.snapshot.val() == null) {
community['userStarred'] = false;
} else {
community['userStarred'] = true;
}
});
});
}
请注意,社区是社区列表中的可观察列表:
@observable List communities = toObservable([]);
最初填充在community-list.attached()中:
getCommunities() {
var f = new db.Firebase(firebaseLocation + '/communities');
var communityRef = f.limit(20);
communityRef.onChildAdded.listen((e) {
var community = e.snapshot.val();
// If no updated date, use the created date.
if (community['updatedDate'] == null) {
community['updatedDate'] = DateTime.parse(community['createdDate']);
}
// snapshot.name is Firebase's ID, i.e. "the name of the Firebase location"
// So we'll add that to our local item list.
community['id'] = e.snapshot.name();
// Insert each new community into the list.
communities.add(community);
// Sort the list by the item's updatedDate, then reverse it.
communities.sort((m1, m2) => m1["updatedDate"].compareTo(m2["updatedDate"]));
communities = communities.reversed.toList();
});
}
总而言之,即使在拥有用户之前,我也要加载社区列表,但是一旦有了用户,我想使用userStarred = true / false来更新社区列表中的每个社区( map ),然后将其用于社区列表模板。
最佳答案
1)toList()
创建列表的副本。您需要再次应用toObservable
以获得可观察的列表。
communities = toObservable(communities.reversed.toList());
这还将为
communities
覆盖的@observable
分配一个新列表。我认为还是应该触发
2)您明确更新社区。不必听
changes
。您可以调用包含if (app.user != null) {
getUserStarredCommunities();
}
每次更改列表时都会明确显示。
当
communities
发生更改时,您还可以为每个社区调用Firebase。我不了解Firebase,但似乎您每次都向服务器发送请求,这当然很昂贵。您应该记住已经进行了哪种
user
+ community
组合,并改用记住的结果。使用
app.changes.listen
,您可以侦听组件中任何@observable
字段的更新。如果在communities
之外还有其他可观察的字段,则此方法可能被调用得太频繁。如果您只对
communities
的更改感兴趣,则应将此代码放入类似的方法中communitiesChanged(oldVal, newVal) {
if (app.user != null) {
getUserStarredCommunities();
}
}
但是更好的选择是不听更改和其他方法名称,并尽可能地将其显式地调用为状态。
关于dart - 为什么我的更新的可观察列表未反射(reflect)在模板中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633717/