为什么我的听众不返回任何数据?
我正在尝试将所有内容保持模块化,然后偶然发现了一个问题。我想在我的message_dao
窗口小部件中保留所有代码与Firebase实时数据库和Firebase Cloud存储有关激活侦听器的功能。但是,看起来接收到
正在接收一个空列表,因为当我打印出chats
变量时,它是空的。
message_dao
Future<List> activateChatListener() async {
var msg;
_receivedChatsStream = _messagesRef.onValue.listen((event) {
event.snapshot.children.forEach((snapshot) {
dataList.add(snapshot.value);
});
//...other code that returns a future...
});
return dataList;
}
接收chat
class _ReceivedChatsState extends State<ReceivedChats> {
var chats = [];
@override
void initState() {
super.initState();
loadChats();
}
Future<void> loadChats() async {
var dataList = await messageDao.activateChatListener();
setState(() {
chats = dataList;
});
print('chats: ' + chats.toString()) //This shows an empty list
}
//...other code...
}
I'm trying to keep everything modular and I stumbled onto a problem. I want to keep all code related to Firebase Realtime Database and Firebase Cloud Storage in my message_dao
widget, so I have my receivedChats
widget calling a message_dao
function that activates the listener. However, it looks like receivedChats
is receiving an empty list because when I print out the chats
variable it's empty.
message_dao
Future<List> activateChatListener() async {
var msg;
_receivedChatsStream = _messagesRef.onValue.listen((event) {
event.snapshot.children.forEach((snapshot) {
dataList.add(snapshot.value);
});
//...other code that returns a future...
});
return dataList;
}
receivedChats
class _ReceivedChatsState extends State<ReceivedChats> {
var chats = [];
@override
void initState() {
super.initState();
loadChats();
}
Future<void> loadChats() async {
var dataList = await messageDao.activateChatListener();
setState(() {
chats = dataList;
});
print('chats: ' + chats.toString()) //This shows an empty list
}
//...other code...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在返回listbe之前的API完成获取数据之前,
请尝试使用此列表
You are returning the listbefore the api has finished fetching data
Try this instead
因为您的
loadchats
将被调用一次。 将数据存储到datalist
数组中,您可以直接通过
streamBuilder
示例而是完整的示例您可以参考并且可以解决问题。
Because your
loadChats
will be called once. Instead of storing your data intodataList
array, you can directly use that snapshot throughStreamBuilder
Example:
Here is the full example that you can refer and you can solve your problem.