Home > Back-end >  Flutter await for another method complete
Flutter await for another method complete

Time:04-18

I want to check if new update is available for my application or not. if update is available redirect user to UpdateScreen and if update is not available get the user info and redirect to HomeScreen

_check() async {

  await _checkForUpdate();
  
  await _getUserData(token);

}
  _checkForUpdate() async {
     print('check for update');
      var url = Uri.parse(Endpoints.mainData);
      var response = await http.get(url);

      var jsonResponse = convert.jsonDecode(response.body);

      var data = jsonResponse['data'];


      int lastVersionCode = data['lastVersionCode'];

      if(lastVersionCode > Data.versionCode){
        redirectToScreen(context, UpdateScreen());
      }
  }
_getUserData(String token) async {
    print('get user data');
    var url = Uri.parse(Endpoints.accountInfo   '/?token='   token);
    var response = await http.get(url);
    var jsonResponse = convert.jsonDecode(response.body);
    var data = jsonResponse['data'];

    //setup user data in my app
    redirectToScreen(context, HomeScreen());

When I run my application two methods( _checkForUpdate, _getUserData) get fired and in output I the get following message that i printed:

check for update
get user data

and i see Update screen for 1 second and then user is redirect to HomeScreen.

i want to skip running the other codes after _checkForUpdate redirect user to UpdateScreen

CodePudding user response:

return a bool whether there is an update available and use it to skip other methods:

_check() async {
  bool needsUpdate = await _checkForUpdate();
  if (!needsUpdate)
      await _getUserData(token);
}


Future<bool> _checkForUpdate() async {
     print('check for update');
      var url = Uri.parse(Endpoints.mainData);
      var response = await http.get(url);

      var jsonResponse = convert.jsonDecode(response.body);
      var data = jsonResponse['data'];

      int lastVersionCode = data['lastVersionCode'];

      if (lastVersionCode > Data.versionCode) {
        redirectToScreen(context, UpdateScreen());
        return true;
     }
     return false;
  }
  • Related