小编T F*_*her的帖子

为什么 FutureBuilder snapshot.data 返回“Instance of Post”而不是 json?

我期待一个 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)

http dart flutter

5
推荐指数
1
解决办法
5358
查看次数

标签 统计

dart ×1

flutter ×1

http ×1