首页 > 解决方案 > 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

标签: multithreadingflutterdartasynchronous

解决方案


我认为您应该在初始化阶段获取您的数据,即您应该创建一个函数来从数据库中获取数据,然后从 initState 调用该函数


推荐阅读