【发布时间】:2020-06-13 02:38:38
【问题描述】:
我有一个具有聊天功能的 Flutter 应用程序,其中的聊天记录存储在 Firebase 数据库中。我有一个BottomNavigationBar,它有一个用于聊天的图标按钮。如果有任何未读聊天,我会在此图标上显示一个徽章:
BottomNavigationBarItem(
icon: new Stack(
children: <Widget>[
ImageIcon(AssetImage('images/icons.png')),
_unreadCount != null && _unreadCount > 0 ? Positioned(
right: 0,
child: new Container(
padding: EdgeInsets.all(1),
decoration: new BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: BoxConstraints(
minWidth: 12,
minHeight: 12,
),
child: new Text(
'$_unreadCount',
style: new TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
),
) : null
].where((c) => c != null).toList(),
),
title: Text('Chats', style: TextStyle(fontWeight: FontWeight.w500))
),
我使用返回Future<int> 的方法获取_unreadCount。它将查询 chats firebase 数据库并返回未读聊天的数量:
Future<int> getUnreadCount() async {
bool isLoggedIn = await connection.isUserLoggedIn();
int count = 0;
if(isLoggedIn) {
int userId = await _getUserId();
final QuerySnapshot chatsQuerySnapshot =
await Firestore.instance.collection("chats")
.where("userIds", arrayContains: userId)
.getDocuments();
final List<DocumentSnapshot> documents = chatsQuerySnapshot.documents;
if(documents != null && documents.isNotEmpty) {
for (DocumentSnapshot chatsSnapshot in documents) {
if(chatsSnapshot['unread'] as bool) {
count++;
}
}
}
}
return count;
}
但是,因为这将返回 Future,所以只有在重建 BottomNavigationBar 时(即当我单击另一个选项卡时)并且调用 Future 方法时,徽章才会更新。
我需要一个返回 Stream 的方法,但我找不到任何可以按我想要的方式工作的示例。在我看来,流仅在返回数据集合/列表时使用,但我只想要一个int。我对响应式编程知之甚少,而且我是新手,但是如何以这种方式查询 Firebase?
【问题讨论】:
标签: firebase flutter reactive-programming