【发布时间】:2022-01-17 03:42:53
【问题描述】:
我有一个user model class,如下所示
class User {
String? email;
String? about;
String? name;
String? picture;
int? index;
String? imageFetchType;
User({this.email, this.about, this.name, this.picture, this.index, this.imageFetchType});
factory User.fromJson(Map<String, dynamic> json) => User(
email: json["email"],
about: json["about"],
name: json["name"],
picture: json["picture"],
index: json["index"],
imageFetchType: json["imageFetchType"]
);
Map<String, dynamic> toJson() => {
"email": email,
"about": about,
"name": name,
"picture": picture,
"index": index,
"imageFetchType": imageFetchType
};
}
下面是 Future function,我用它来获取用户 list 并遍历列表以填充用户
Future<List<User>> _fetchUsersListUsingLoop() async {
try {
var response = await http.get(
Uri.parse(
"https://api.json-generator.com/templates/Eh5AlPjYVv6C/data"),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
});
List<User> usersList = [];
for (var u in json.decode(response.body)) {
User user = User(u["email"], u["about"], u["name"], u["picture"],
u["index"], u["imageFetchType"]);
usersList.add(user);
}
return usersList;
} catch (e) {
log("FetchUsersListUsingLoopException $e");
rethrow;
}
}
我在下面一行得到Too many positional arguments: 0 expected, but 6 found. (Documentation) Try removing the extra positional arguments, or specifying the name for named arguments.
User user = User(u["email"], u["about"], u["name"], u["picture"],
u["index"], u["imageFetchType"]);
当我尝试将user class 中的constructor 更改为低于其工作时
User(this.email, this.about, this.name, this.picture, this.index, this.imageFetchType);
但我在fromJson 中遇到另一个错误,在下面的代码行中显示6 positional argument(s) expected, but 0 found. (Documentation) Try adding the missing arguments.
factory User.fromJson(Map<String, dynamic> json) => User(
email: json["email"],
about: json["about"],
name: json["name"],
picture: json["picture"],
index: json["index"],
imageFetchType: json["imageFetchType"]
);
我怎样才能在用户类中使用构造函数User({this.email, this.about, this.name, this.picture, this.index, this.imageFetchType}); 并循环而不出现Too many positional arguments: 0 expected, but 6 found 错误
【问题讨论】:
标签: flutter for-loop dart constructor arguments