multithreading - Flutter : Function need to wait
问题描述
Here is my code
Future<List<Record>> getRecordElements() async {
int i=0;
String at;
var cont =0;
List<String> name= [];
var db = await FirebaseDatabase.instance.reference().child("Volunteers/"+widget.vname+"/Records");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
print(values);
values.forEach((key,values) async {
if(values["cont"]!=null){
//Few complicated operations
values.forEach((key,values) {
print(values);
if(key=="name"){
name.add(values);
}
});
});
});
print("name " + name.toString());
//few more operations
return items;
}
I have modified out irrelevent parts of the code.
Thing is, name
is an array whose values are fetched from the database. Only after the array is set, can function proceed.
But what is happening is that name
is being printed before it has been set. And hence the other operations after that are also being affected.
I need the fetching to finish first, and only then move ahead.
Please help
解决方案
我认为您应该在初始化阶段获取您的数据,即您应该创建一个函数来从数据库中获取数据,然后从 initState 调用该函数
推荐阅读
- ios - SwiftUI“取消绑定”文本字段中的字符串
- c++ - 制作 sfml c++ 滚动条不会在 veiw 内绘制形状
- reactjs - TodoList 应用程序中的重复问题
- sql - sqlite 将毫秒转换为 HH:MM:SS.SSS
- scrapy - 如何在scrapy中点击一个链接,在新页面解析一些数据然后返回上一页继续解析
- r - 情节错误(qs,道具):未使用的参数(道具)
- python - 为什么我有一个简单的应用程序 /xff 问题
- testng.xml - testng.xml 文件不执行所有方法
- javascript - Ant select如何访问key的值
- json - JQ - 在数组打印后获取另一个更高级别的键值