我期待一个 JSON 数据对象,但我得到了 Instance of 'Post'
我是 flutter 的新手,并尝试使用 http.dart 包通过 post 请求访问 API。我正在使用异步未来和未来建筑来使用返回的数据填充小部件(遵循此处的颤振示例:https : //flutter.io/docs/cookbook/networking/fetch-data)。
Future<Post> fetchPost() async {
String url = "https://example.com";
final response = await http.post(url,
headers: {HttpHeaders.contentTypeHeader: 'application/json'},
body: jsonEncode({"id": "1"}));
if (response.statusCode == 200) {
print('RETURNING: ' + response.body);
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
class Post {
final String title;
Post({this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
title: json['title']
);
}
}
void main() => …Run Code Online (Sandbox Code Playgroud)