英文:
How to dump the values I'm getting from firestore to list in flutter?
问题
我尝试从Firestore获取数据并将其添加到我的Flutter应用程序的列表中。但是尽管我已经在循环内部使用了list.add,但列表内仍然没有任何内容。
这是我尝试的代码:点击这里查看
这是我得到的输出:点击这里查看
我尝试将数据添加到列表中,因为我想在我的Flutter应用程序中创建一个下拉菜单。
英文:
I tried to get data from Firestore and add it to a list in my flutter app. But although I already put list.add inside the loop, it's still nothing inside the list.
this is the code I'm trying to do
I'm trying to add it to a list because I wanna make a dropdown menu in my flutter app.
答案1
得分: 0
querySnapshot.docs.forEach((documentSnapshot) {
Map<String, dynamic> data = documentSnapshot.data();
print("Name: ${data['nameCategory']}");
});
英文:
querySnapshot.docs.forEach((documentSnapshot) {
Map<String, dynamic> data = documentSnapshot.data();
print("Name: ${data['nameCategory']}");
});
答案2
得分: 0
从Firestore加载数据(就像几乎所有现代云API调用一样)是一个异步操作,它在后台进行,以防止阻塞应用程序。因此,当数据正在加载时,你的主要代码会继续执行并打印一个空列表。
然后,当数据加载完成时,你在then
回调中的代码会执行,循环遍历结果,依次打印每个结果,并将它们添加到列表中。
要在列表填充后打印列表,请将print(listCategory);
的位置移动到then
回调中的上一行。
从中可以得出一个一般规则,即需要数据库数据的任何代码都必须在then
回调中,从那里调用,或者通过其他机制进行同步(如Sơn Dương提到的setState
)。
英文:
Loading data from Firestore (like pretty much any modern cloud API call) is an asynchronous operation, which happens in the background to prevent blocking the app. So while the data is being loaded, you main code continues and prints an empty list.
Then when the data has loaded, your code inside the then
executes, loops over the results, prints each in turn, and adds them to the list.
To print the list after it's been populated, move the print(listCategory);
into the then
callback - one line up from where it is now.
The general rule from this is that any code that needs the data from the database has to be inside the then
callback, be called from there, or be synchronized by some other mechanism (such as setState
that Sơn Dương mentioned too).
答案3
得分: -2
不知道你正在使用哪种状态管理。
基本上,当你将其添加到列表中时,你需要使用setState()
。
英文:
Don't know what state management you are using.
Basically you need setState()
when you add it to the list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论