将值赋给从Flatter中的JSON转换而来的list对象中的变量
我真的是个新手。我试图寻找这个问题,虽然我已经找到了一个解决方案,但并不是所有的问题都解决了,因为大多数问题都是使用return 我有一个JSON,我从这里调用API得到:将值赋给从Flatter中的JSON转换而来的list对象中的变量,json,list,flutter,Json,List,Flutter,我真的是个新手。我试图寻找这个问题,虽然我已经找到了一个解决方案,但并不是所有的问题都解决了,因为大多数问题都是使用return 我有一个JSON,我从这里调用API得到: { "error": false, "message": "LOGIN_SUCCESS", "user": { "id": 1219, "email"
{
"error": false,
"message": "LOGIN_SUCCESS",
"user": {
"id": 1219,
"email": "john@example.com"
"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']
);
}
}
但是我如何在列表对象中做到这一点呢
当有人想知道我为什么要这样做时,我试图将数据保存到一个sharedpref类中,该类是我从其他代码复制的。共享首选项并不用于存储对象。使用类似于持久化对象(官方食谱)的方法 我不明白为什么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
对象做什么。仅供参考,颤振的一个重要部分是。我使用共享首选项,因为我只想暂时保留数据。在本机android中,我使用共享首选项,因为sqlite会将数据保存在设备中。我现在将调查sqflite。我的JSON只解码1个用户数据,用于返回当前尝试登录和使用该应用程序的用户。至于你的答案,我怎样才能从用户那里一个接一个地操作这个值呢?例如,电子邮件、名称等。好的,值在用户对象中,例如user.name
,user.branch
等。共享的pref与sqflite一样持久,只有在卸载时才会消失。如果您只想在应用程序打开时保留数据,请使用我说过的状态管理解决方案。是的。真管用!我将学习更多关于州管理的知识。谢谢你的帮助。很高兴这样做,不客气:)
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();
}
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'];
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
}