Null while returning a Future in Dart

2019-07-30 08:38发布

问题:

I have two classes, a user_api_manager and a base_api_manager. From user_api_manager i call the get method of base_api_manager which performs an http get request and returns a Future<String>. The getrequest is performed but i am not pass the result to my user_api_manager class. The callback result is always null.

This is my user_api_manager.dart

static Future<Map<String,dynamic>> forgotPasswordAPI(String email) async{

String url = Constants.BASE_URL + Constants.FORGOT_PASSWORD_URL + email;

await BaseApiManager.get(url: url).then((val) {

  var response = JSON.decode(val);

  var status = response['status'];
  String message = '';
  print(response);
  switch (response['status']) {
    case Constants.SUCCESS:
      message = Constants.SUCCESS_RESPONSE;
      break;
    case Constants.SERVER_ERROR:
      message = Constants.SERVER_ERROR_MESSAGE;
      break;
    case Constants.UNAUTHORISED:
      message = Constants.UNAUTHORISED_MESSAGE;
      break;
  }
  return {'status':status,'message':message};
 });
}

and here is my base_api_manager.dart

static Future<String> get({url : String,
parameters : Map ,
headers: Map }) async {
    var client = new http.Client();
    Map<String,dynamic> resultJSON;
    final c = new Completer();
    await client.get(url).then((response) {  //response is always null
    resultJSON  = {
        'status' : response.statusCode,
        'body' : JSON.decode(response.body)
    };
    c.complete(resultJSON.toString());
    return c.future;
  });
}

How to solve this issue?

回答1:

Move the return c.future outside of the response processing, i.e you want to return this from your get otherwise you will return null.



回答2:

You can simplify the code. That should make it easier to locate the problem

static Future<String> get({url : String, parameters : Map, headers: Map }) async {
  var client = new http.Client();
  final response = await client.get(url);
  print(response.body);
  var resultJSON  = {
      'status' : response.statusCode,
      'body' : JSON.decode(response.body)
  };
  return resultJSON.toString()
}

What does that code print?



标签: dart flutter