Home > Software design >  Dart return keyword in an async function
Dart return keyword in an async function

Time:02-14

Can somebody please tell me why the return "NOK" code get executed anyway even if the status is true? Is this not the purpose of return keyword to stop the function execution and return the value? Or do i miss something about async functions or Dart langage itself?

static dynamic getUserRef() async {
    // HttpOverrides.global = MyHttpOverrides();
    bool status;
    await InfosHelper.getInfo('testinfo').then((response) {
      InfoModel info = InfoModel.fromJson(response.data);
      status = info.status;
      Map<String, dynamic> otherData = info.data;
      if (status) {
        return "OK";
      }
    });

    return "NOK";
  }

CodePudding user response:

you are calling .then which is a method it self so the status true will stop execution of .then method but the main getUserRef with always return 'Nok'

 static dynamic getUserRef() async {
    // HttpOverrides.global = MyHttpOverrides();
    bool status;
    var response=await InfosHelper.getInfo('testinfo');
     if (response!=null){
  InfoModel info=InfoModel.fromJson(response.data);
   Map<String, dynamic> otherData = info.data;
  if(info.status){
return 'ok';
}
else{
return 'nok'}
}
}
else{
//Error
}

CodePudding user response:

try this

 static Future<String> getUserRef() async {
        // HttpOverrides.global = MyHttpOverrides();            
        final response = await InfosHelper.getInfo('testinfo');
        InfoModel info = InfoModel.fromJson(response.data);
        bool status = info.status;
        Map<String, dynamic> otherData = info.data;
         
        return status ? "OK" : "NOK";
                
      }
  • Related