firebase - 从多个数据库节点填充 Flutter ListView
问题描述
我正在尝试使用来自我的 Firebase 实时数据库实例的多个节点的数据填充 ListView.builder。
我对监听节点上的更改(并在它们发生时更新列表视图)感兴趣,但对节点chats
上的实时更新不太感兴趣。chats-details
chats
-- 'chat1'
---- 'keyA' : 'This is some text'
---- 'keyB' : 'This is some text'
-- 'chat2'
---- 'keyA' : 'This is some text'
---- 'keyB' : 'This is some text'
chats-details
-- 'chat1'
---- 'keyC' : 'This is some text'
---- 'keyD' : 'This is some text'
-- 'chat2'
---- 'keyC' : 'This is some text'
---- 'keyD' : 'This is some text'
理想情况下,chat1、chat2...等的所有数据都将附加到 Object(myChats
在下面的示例中)并输入 ListView。
任何帮助将不胜感激。我当前的代码如下。此代码当前不会自动填充 ListView。
// Node 1 - Listen to changes
chatsRef = FirebaseDatabase().reference().child('chats');
// Node 2 - Update when node 1 is updated
chatsDetailsRef = FirebaseDatabase().reference().child('chats-details');
@override
Widget build(BuildContext context) {
List<Chats> myChats = [];
return Scaffold(
appBar: AppBar(),
body: StreamBuilder(
stream: chatsRef.onValue,
builder: (context, snap) {
if (snap.hasData && !snap.hasError && snap.data.snapshot.value != null) {
Map data = snap.data.snapshot.value;
data.forEach((index, data) {
chatsDetailsRef.child(index).once().then((DataSnapshot snapshot) {
Chats currentChat = Chats.fromMap(data);
if (snapshot.value == null) {
Chat emptyChatDetails = Chat();
currentChat.chatDetails = emptyChatDetails;
} else {
Chat foundChatDetails = ChatDetails.fromMap(snapshot.value);
currentChat.chatDetails = foundChatDetails;
}
myChats.add(currentChat);
});
});
return ListView.builder(
itemCount: myChats.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(myChats[index].title),
subtitle: Text(myChats[index].chatDetails.detail),
);
},
);
} else {
return Center(child: Text("No data"));
}
},
),
);
}
}
解决方案
每当您将项目添加到 myChats 时,您是否尝试过调用 setState?
setState(() {
myChats.add(currentChat);
});
https://api.flutter.dev/flutter/widgets/State/setState.html
此外,您当前myChats
每次运行构建函数时都重新定义数组,这意味着只要重新构建小部件,它将清除其中的所有聊天。如果您希望保留这些聊天,则必须将该数组声明为该类本身的成员
推荐阅读
- scala - spark 无法序列化 lambda
- babeljs - 使用 babel 像 iife 一样汇总输出
- kubernetes - Prometheus 操作员警告“资源版本太旧”
- c# - 自定义通知窗口窗体而不更改当前工作窗口的焦点
- ruby-on-rails - 有什么方法可以找到 Rails 切换方法起作用的方向吗?
- swift - 是否可以在没有编程经验的情况下开始快速学习?
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录,Pyinstaller 正在搜索目录 \\_MEI97962\\cmudict\\VERSION
- python - 如何仅获取由 MySQL 中唯一用户标识标识的列的值?请参阅问题以获得更详细的解释
- r - 如何在 R 中最好地结合独特和匹配?
- c++ - 在 switch case 中使用按位或运算符