Home > Back-end >  How to have a flutter class method return a future?
How to have a flutter class method return a future?

Time:02-24

How do I set up a flutter method to return a future value that is drawn from the results of a future http post call inside the method?

The example code below is making a call to a web URL to add a new product. I want this method to return just the Id of the newly created product (i.e. 'name' inside response)

  Future<String> add(Product aNewProduct) async {
    var  aUrl = Uri.parse(dbUrl);
    http.post(aUrl,body: toBody(aNewProduct),).then((response) {
      var aStr = json.decode(response.body)['name'];
      return Future<String>.value(aStr);
    });
  }

With the code above, the parser is showing the following error/warning...

The body might complete normally, causing 'null' to be returned, 
but the return type, 'FutureOr<String>', is a potentially non-nullable type. 
(Documentation)  Try adding either a return or a throw statement at the end.

Any suggestions on how to fix this?

CodePudding user response:

You can use the await to get the value of a Future or rather your http request. After that you can simple decode it and return your desired behavior.

Future<String> add(Product aNewProduct) async {
  var aUrl = Uri.parse(dbUrl);
  final response = http.post(
    aUrl,
    body: toBody(aNewProduct),
  );

  return json.decode(response.body)['name'];
}

CodePudding user response:

try this:

Future<String> add(Product aNewProduct) async {
    var  aUrl = Uri.parse(dbUrl);
  var response= await http.post(aUrl,body: toBody(aNewProduct),);
if(response.statusCode==200){
 var rawData = await response.stream.bytesToString();
 Map data=json.decode(rawData);
 return data['name'];
}else{
return '';
}


  }

CodePudding user response:

It is as simple as putting a return before the http.post statement

  • Related