在我的应用中,我使用 Stream
来检查 badges
的值是真还是假。
void _listenToBadges() {
_subscription = activityFeedref
.where('userId', isEqualTo: authUser.id)
.snapshots()
.listen((event) {
allBadges.clear();
for (final doc in event.docs) {
allBadges.add(Badge.fromDocument(doc));
}
//print(allBadges);
if (!isDisposed) {
notifyListeners();
}
});
}
然后我将它们保存在一个类中:
class Badge {
Badge(
{this.menuBadge = false,
this.userId});
Badge.fromDocument(DocumentSnapshot doc) {
if (doc.data().containsKey('menuBadge')) {
menuBadge = doc['menuBadge'] as bool;
}
if (doc.data().containsKey('userId')) {
userId = doc['userId'] as String;
}
}
bool menuBadge;
String userId;
}
我使用 getter 来获取徽章的值:
Badge get showFeedbadge {
for (int i = 0; i < allBadges.length; i++) {
if (allBadges.elementAt(i).userId == authUser.id) {
print(allBadges.elementAt(i).menuBadge);
return allBadges.elementAt(i);
}
}
return null;
}
最后我使用 badge
的值来调用我的 AppBar
中的徽章:
AppBar(
leading: Builder(
builder: (BuildContext context) {
final badgeManager = context.read<BadgeManager>();
badge = badgeManager.showFeedbadge.menuBadge;
return IconButton(
icon: BadgeIcon(show: badge, icon: Icon(Icons.menu)),
onPressed: () {
Scaffold.of(context).openDrawer();
//badgeManager.updateMenuBadge(menuBadge);
},
);
},
),
但每次应用初始化时,我都会收到 The getter 'menuBadge' was called on null. Receiver: null Tried calling: menuBadge
。尽管该功能正在运行,但我不知道如何摆脱此错误。大家有什么想法吗?