Home > Net >  How to load a futurebuilder function after async await and then in flutter
How to load a futurebuilder function after async await and then in flutter

Time:07-27

.How can i run a function of Future inside the then function after await here is the code am currently trying

getData() async {
    await MainClass().getToken().then((value) {
      getSchools();
    });
  }

But the getSchools(); function is not runinng but when i try this method

getSchools() {
print('234');
}

the result is printed but when i run this method

Future<List<SchoolInfo>> getSchools async {
    http.Response response = await http.post(
        Uri.parse(MainClass().getBaseUrl()   'api/getMegaCandidByAgentId'),
        body: jsonEncode(<String, String>{
          'api_key': tk,
          'agent_id': id,
        }));
    var js = json.decode(response.body);
    var status = js['success'];

    if (status == 'Ok') {
      final data = js['data'];

      List<SchoolInfo> info_ = [];

      for (var ls in data) {
        SchoolInfo info = SchoolInfo(
            ls['id'],
            ls['name'],
        info_.add(info);
      }
      return info_;
    } else if (status == 'Error') {
      var sms = js['message'];
      print(sms);
      return error_;
    } else {
      print('Unknown Error');
      return error_;
    }
  }

the function does run or throws any error but the function runs successfully directly in my future builder but as you can see from the code i need the token first before i call call the function, am kindof new to flutter so am not sure what possible or not. Any help will be greatly appreciated

CodePudding user response:

I'm not exactly sure why you'd want to run it like that. You should call the getToken() function with async/await, and then async/await getSchool().

getData() async {
    String token = await MainClass().getToken();

    // We're passing 'token' from our first asynchronous call to getSchools()
    List<SchoolInfo> schools = await getSchools(token);
  }

Now you need to update getSchools to accept this parameter.

Future<List<SchoolInfo>> getSchools(String tk) async {
  ... your code here
}
  • Related