1

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),
  );
}
3
  • See dart.dev/codelabs/async-await Commented Mar 11, 2022 at 16:10
  • when using await follow the pattern Future<type> func(string parm) async{} then call the future using a promise func().then((value){}); Commented Mar 11, 2022 at 16:17
  • add your get_number() function Commented Mar 11, 2022 at 16:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

if i using await i have to use a async and after that i have to use Future and i wanna returen widget not Future Widget. but am using await in get_number() function
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.