【发布时间】:2019-05-31 12:10:59
【问题描述】:
我期待一个 JSON 数据对象,但得到的是 Instance of 'Post'
我是 Flutter 的新手,我尝试使用 http.dart 包通过发布请求来访问 API。我正在使用 async future 和 future building 来使用返回的数据填充小部件(按照此处的颤振示例: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() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.toString());
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}
我期待 FutureBuilder 中的 return 语句给我一个 json 对象。这是一个现有的 API,所以我知道它可以工作并且它返回我所期望的。
【问题讨论】: