-1

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

nlmm
  • 19
  • 1
  • 5
  • In addition to the `.forEach` problem (and it's unclear why you've marked its callback as `async` when it doesn't seem to do any asynchronous work, unless that part was omitted), you neglect to `await` the result of `db.once().then()` (and calling `.then` then would be unnecessary anyway). – jamesdlin Jun 25 '21 at 18:07

1 Answers1

1

I think You Should fetch Your data at initializing stage i.e. you should create a function to fetch data from database and then call that function from initState

ItzJvs
  • 301
  • 10