【发布时间】:2021-02-16 17:03:28
【问题描述】:
我从 flutter.dev 获取了代码,它使用工厂从互联网上获取数据。
import 'dart:convert';
Future<Album> fetchAlbum() async {
final response = await http.get('https://jsonplaceholder.typicode.com/albums/1');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album({this.userId, this.id, this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
我曾尝试在我的代码中重复它,但它不起作用。我很困惑为什么它不起作用,因为我做的和例子一样。
Future<Album> fetchAlbum() {
Map<String, dynamic> map = {
"photo": "another data",
"id": "dsiid1dsaq",
};
return Album.fromJson(map);
}
class Album {
String photo;
String id;
Album({this.photo, this.id});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
photo: json['photo'],
id: json['id'],
)`
}
}
它告诉我:“无法从函数 'fetchAlbum' 返回类型为 'Album' 的值,因为它的返回类型为 'Future'。”
【问题讨论】: