如何设置一个flutter方法来返回一个未来值,该值是从该方法内部未来http post调用的结果中提取的?
下面的示例代码是调用web URL来添加新产品。我希望此方法只返回新建产品的Id(即响应中的"名称"(
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);
});
}
使用上面的代码,解析器显示以下错误/警告。。。
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.
关于如何解决这个问题,有什么建议吗?
您可以使用await来获取Future
或http
请求的值。之后,你可以简单地解码它并返回你想要的行为。
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'];
}
试试这个:
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 '';
}
}
这就像在http.post
语句之前放一个return
一样简单