Why changes made to this class field disappear after leaving async method?

Viewed 24

So, I'm trying to do something that seems simple, but I can't get why it is not working. I wrote this code:

class HomepageModel {


  List<dynamic> data = [];
  String _url = '[...]';   //My URL is working


  Future _comm() async {
    data = await httpFetch(_url); //This 'httpFetch' just does some json decoding 
    print(data);     //Shows data normally
  }

  HomepageModel() {
    _comm();
    print(data);     //Shows empty list
  }
}

I want to store data retrieved from an API in the field data. I was able to get the data in function _comm, and when I print the field, it shows normally. But, outside this method, the content of the data field seems to have disappeared! Both on the print in the constructor, and in other files, all the prints show just an empty list.

What should I do to be able to properly store data from the API in a class field?

1 Answers
class HomepageModel {


  List<dynamic> data = [];
  String _url = '[...]';   //My URL is working


  Future _comm() async {
    data = await httpFetch(_url); //This 'httpFetch' just does some json decoding 
    print(data);     //Shows data normally
  }

  HomepageModel() {
    _comm().then((_){
      print(data);     
    });
   
  }
}

Related