'How to have a flutter class method return a future?

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?



Solution 1:[1]

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'];
}

Solution 2:[2]

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


  }

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quoci
Solution 2 Vishal_VE
Solution 3 Ahmed Rajab