我真的很陌生。我尝试搜索此问题,尽管我找到了解决方案,但并非所有问题都得到了解决,因为大多数问题只是使用return。
我有一个从API调用的JSON:
{
"error": false,
"message": "LOGIN_SUCCESS",
"user": {
"id": 1219,
"email": "[email protected]"
"name": "John Doe",
"category": 1,
"branch": 1004,
"lastlogin": "2020-12-04 03:12:43"
}
}
我已经为用户创建了如下类
class User {
int id;
String name;
String email;
String category;
String branch;
String lastLogin;
User({
this.id,
this.name,
this.email,
this.category,
this.branch,
this.lastLogin
});
factory User.fromJson(Map<String, dynamic> datauser){
return User(
id: datauser['id'],
name: datauser['name'],
email: datauser['email'],
category: datauser['category'],
branch: datauser['branch'],
lastLogin: datauser['lastlogin']
);
}
}
以及如下的结果类。
class Result {
String message;
User user;
Result({
this.message,
this.user
});
factory Result.fromJson(Map<String, dynamic> resultData){
return Result(
message: resultData['message'],
user: User.fromJson(resultData['user'])
);
}
}
现在出现了我的问题,因为我不知道如何从这一点开始前进
login() async {
List<User> users;
final response = await http.post("myUrlWithAPIcalls",
body: {"email": email, "password": password});
final data = jsonDecode(response.body);
var rest = data['user'] as List;
users = rest.map<User>((json) => User.fromJson(json)).toList();
}
所以问题是,如何分配从已转换为列表的JSON获得的值到变量?
现在在示例中,如果它只是一个简单的JSON对象,我可以这样做。
final data = jsonDecode(response.body);
int id = data['id'];
String name = data['name'];
String email = data['email'];
String category = data['category'];
String branch = data['branch'];
但是如何在列表对象中做到这一点?
任何人都想知道为什么我要这样做,我试图将数据保存到我从其他人代码中复制的sharedpref类中。
共享首选项并不意味着存储对象。使用诸如sqflite之类的东西来持久化对象(此处为官方食谱)。
我不明白为什么您的JSON显示一个用户的数据,但是该login()
功能似乎可以解码用户列表。
我猜这就是你想要的:
login() async {
final response = await http.post("myUrlWithAPIcalls",
body: {"email": email, "password": password});
final data = jsonDecode(response.body);
var user = User.fromJson(data['user']); // the variable you want
}
您没有说该login()
功能在哪里,或者您想对该User
对象做什么。仅供参考,Flutter的重要组成部分是状态管理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句