Home > Software engineering >  I have a method in a class but it is not returning values, is it because I'm passing parameters
I have a method in a class but it is not returning values, is it because I'm passing parameters

Time:01-24

Im trying to make a class and method to do HTTP requests using Dio


class appCommunicate {

  appGetRequest(String url, {headers = ''})
  async {

    if (headers.length > 0) {

      _res =  await dio.get(url, options: Options(headers: headers));
    }
    else
    {
      _res = await dio.get(url);

    }


    return _res;

  }

}

And then when I try to invoke this class as follows:

          final communicate = appCommunicate();
          final response = await communicate.appGetRequest(_myUrl);

Nothing happens, no communication and the app just stops there

CodePudding user response:

dio.get() is venerable for exception. You must add dio.get code in try catch block to handle exception.

appGetRequest(String url, {headers = ''}) async {
    try {
        if (headers.length > 0) {
            _res =  await dio.get(url, options: Options(headers: headers));
        }
        else
        {
            _res = await dio.get(url);
        }
        return _res;
    }
    catch (e) {
        print(e);
    }
}

CodePudding user response:

I made a mistake, the class and method as posted above are fine and work fine.

I had another piece of code that was causing the error. Stupid me!

CodePudding user response:

As it is a async type function its return type should be Future like this-

class appCommunicate {

Future<Response> appGetRequest(String url, {headers = ''})
async {

if (headers.length > 0) {

  _res =  await dio.get(url, options: Options(headers: headers));
}
else
{
  _res = await dio.get(url);

}


return _res;

 }

}
  •  Tags:  
  • Related