ebenjs
ebenjs

Reputation: 429

Dart return keyword in an async function

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

Upvotes: 0

Views: 353

Answers (2)

Osama Kashif
Osama Kashif

Reputation: 416

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
}

Upvotes: 2

Maurice Raguse
Maurice Raguse

Reputation: 4567

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

Upvotes: 1

Related Questions