您好,我正在尝试弄清楚工厂构造器如何在飞镖中工作



我已经从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'],
)`
}
}

它告诉我:"类型为'Album'的值不能从函数'fetchAlbum'返回,因为它有一个返回类型'Future'。">

希望这对你有帮助。

Future<Album> fetchAlbum() async {
Map<String, dynamic> map = {
"photo": "another data",
"id": "dsiid1dsaq",
};
return Album.fromJson(map);
}

或者像这样

Album fetchAlbum() {
Map<String, dynamic> map = {
"photo": "another data",
"id": "dsiid1dsaq",
};
return Album.fromJson(map);
}

问题不在于factory构造函数本身。问题是你将函数fetchAlbum声明为Future<Album>类型,而实际上它返回的只是同步的Album

来自Flutter文档的示例返回类型为Future<T>,因为它在处理网络请求时使用asyncawait关键字,因此它返回Future

改变:

Album fetchAlbum() {
Map<String, dynamic> map = {
"photo": "another data",
"id": "dsiid1dsaq",
};
return Album.fromJson(map);
}

最新更新