Home > Back-end >  I get a empty list when using then async and await functions
I get a empty list when using then async and await functions

Time:03-12

it's the first time to write a Flutter code so i am confused, when i tring to get data from API, API working normaly and return a response with data but after that i need to save this data in a list and give it as a variable in another Function but it still empty

Widget number() {
  List number_list=[];
  get_number().then((value) {number_list=value.values.toList();
  print(number_list);// i am giting a list with Values 
   });


  print(number_list); // i am giting an empty list 
  return ListView(
    padding: const EdgeInsets.all(8),
    children: buttons(number_list),
  );
}

CodePudding user response:

You need to make your 'get_number' function an async function and then use 'await' to wait for the API's response to reach and then continue with creating variables and widgets out of the response. The code becomes like this:

Widget number() {
  List number_list=[];
  var value = await get_number();
  number_list=value.values.toList();

  return ListView(
    padding: const EdgeInsets.all(8),
    children: buttons(fleet_list),
  );
}

if you don't use 'await', your code won't wait for getting data from API.

CodePudding user response:

try using a Future and a promise

List number_list=[];
  Future<List<int>> get_number() async{
    return [1,2,3,4];
  }
  
  foo(){
  get_number().then((values) {
      number_list=values;
      print(number_list);// i am giting a list with Values 
   });
  }
  
 foo();
  • Related