i have a list of objects :

List<Hairdresser> HairdressersData = new List<Hairdresser>();

and i am using this method to add data in this list :

    void asyncInitState()  async {
     Hairdressercontroller HController = Hairdressercontroller();
     List<dynamic> value = await HController.GetHairdressers();
     int i = 0;
     value.forEach((dynamic entry) {

      Hairdresser p = new Hairdresser();
      p.name = value[i]["name"];
      p.location = value[i]["location"];
      this.HairdressersData.add(p);
      i++;

    });
     print("List length iniside the method : "+this.HairdressersData.length.toString());
  }

i am calling this method in the initState() :

  void initState() {
    super.initState();
    asyncInitState();
    print('data length is '+ this.HairdressersData.length.toString());
  }

the problem is thatdata is being added to the list inside the method scoop so the list length is not null however outside the method scope the list is empty.


Solution 1: Josteve

Your code is correct except, you are printing before asyncInitState executes completely. See Asynchronous Programming

Try

  void initState() {
    super.initState();
    asyncInitState().then((){
      print('data length is '+ this.HairdressersData.length.toString());
    });
  }

  Future asyncInitState()  async {
     Hairdressercontroller HController = Hairdressercontroller();
     List<dynamic> value = await HController.GetHairdressers();
     int i = 0;
     value.forEach((dynamic entry) {

      Hairdresser p = new Hairdresser();
      p.name = value[i]["name"];
      p.location = value[i]["location"];
      this.HairdressersData.add(p);
      i++;

    });
     print("List length iniside the method : "+this.HairdressersData.length.toString());
  }

Or

 void initState() {
    testAsyncInitState();
    super.initState();
  }

 void testAsyncInitState() async {
    await asyncInitState();
    print('data length is '+ this.HairdressersData.length.toString());
 }