0

I'm trying to get datas from api and add them a list. But at this moment, I see datas i got but I can't get it out of the function. What should i do?

function

  List<dynamic> xxx = [];

  @override
  void initState() {
    super.initState();

    Future<List<dynamic>> fetchCompanies(List<dynamic> datas) async {
      var response = await Dio().get(CompaniesPath().url);
      if (response.statusCode == HttpStatus.ok) {
        Map<String, dynamic> company = jsonDecode(response.data);
        for (int i = 0; i < company['Data'].length; i++) {
          datas.add(company['Data'][i]);
        }
        //print(datas); //=> I see datas here

      } else {
        throw Exception();
      }
      return datas;
    }

    print(fetchCompanies(xxx));
  }

When I run print(fetchCompanies(xxx)); I got "Instance of 'Future<List<dynamic>>'". How can i get data inside fetchCompanies to my xxx list?

Aaron
  • 3,209
  • 1
  • 12
  • 14
macropyre
  • 45
  • 3

2 Answers2

2

You're trying to print future instance of List that's why you got

Instance of Future<List>

You have to wait until function finish executing.

Catch here is you can't call wait in initState() so you have to use .then method

try this:

fetchCompanies(xxx) 
.then((result) {
    print("result: $result");
});
JuniorBOMB
  • 336
  • 1
  • 3
  • 11
-1

It should already work fine like it is. But you probably want to call a setState to refresh the page. Try this:

  @override
  void initState() {
    super.initState();

    Future<List<dynamic>> fetchCompanies(List<dynamic> datas) async {
      var response = await Dio().get(CompaniesPath().url);
      if (response.statusCode == HttpStatus.ok) {
        Map<String, dynamic> company = jsonDecode(response.data);
        for (int i = 0; i < company['Data'].length; i++) {
          datas.add(company['Data'][i]);
        }
        //print(datas); //=> I see datas here

        setState(() {}); // added this

      } else {
        throw Exception();
      }
      return datas;
    }

    print(fetchCompanies(xxx));
  }
Ivo
  • 18,659
  • 2
  • 23
  • 35
  • Other solution has solved my problem, my page got datas but this time didn't refresh it. And i used your solution(setstate). So, both of your answers helped me a lot. Thank you so much – macropyre Feb 13 '23 at 10:51