Flutter: _TypeError

56 Views Asked by At

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?

2

There are 2 best solutions below

0
JuniorBOMB On BEST ANSWER

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");
});
1
Ivo On

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