我期待一个 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() => 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();
},
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我期待 FutureBuilder 中的 return 语句给我一个 json 对象。这是一个现有的 API,所以我知道它可以工作并且返回我所期望的。
当您说“JSON 对象”时,我不确定您指的是什么。Dart 是一种类型化语言,您将任何内容表示为 json 字符串的方式要么是嵌套的,Map<String, dynamic>要么是类(就像您的情况一样)。如果它是一个类,则有执行实际反/序列化的代码。在您的情况下, fromJson 方法与 json.decode() 结合可以进行反序列化,但您还没有任何序列化。
因此,您未来的建设者正在按照您的要求返还。下面这段代码明确地定义了返回Post对象的未来类型:
final Future<Post> post;
Run Code Online (Sandbox Code Playgroud)
并在创建未来的构建器时使用它:
child: FutureBuilder<Post>(
future: post,
Run Code Online (Sandbox Code Playgroud)
如果您想要返回JSON String(或Map<String,dynamic>),您需要首先在您的fetchPost方法中执行此操作(该方法目前也返回一个Post对象。
例如:
Future<Map<String, dynamic>> fetchPost() async { // <------ CHANGED THIS LINE
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 json.decode(response.body); // <------ CHANGED THIS LINE
} else {
throw Exception('Failed to load post');
}
}
Run Code Online (Sandbox Code Playgroud)
或者像这样:
Future<String> fetchPost() async { // <------ CHANGED THIS LINE
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 response.body; // <------ CHANGED THIS LINE
} else {
throw Exception('Failed to load post');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要继续努力,直到您更改 MyApp 类中的 Future 为止。
final Future<Map<String,dynamic>> post;
Run Code Online (Sandbox Code Playgroud)
请阅读这些文档以了解 Flutter 中的 JSON。
| 归档时间: |
|
| 查看次数: |
5358 次 |
| 最近记录: |