--> JSON Response
{"data" {"CityName"空,"DOB"7/07/2022"DeviceType"0";"Email"test@gmail.com"MobileNo"1234567891","ProfileImage"","UserID"1","UserName"xyz"UserType"3";},消息": "成功登录","status" 200}
---> API SERVICE
Future<Loginmodel?> login() async {
if (passwordController.text.isNotEmpty && nameController.text.isNotEmpty) {
var response = await http.post(
Uri.parse(
'XYZ',
),
headers: {"Content-Type": "application/json"},
body: (jsonEncode({
'UserName': nameController.text,
'Password': passwordController.text,
'DeviceToken': '',
'DeviceType': ''
})));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
print(data['data']['UserID'].toString());
if (data['data']['UserID'] == null) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Invaild Credentials")));
} else {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Homescreen()));
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Succesfully Credentials")));
}
// await Storage.write(key: "token", value: output["token"]);
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Black Field Not Allowed")));
}
}
我建议您使用hive。这里有一篇文章提供了在Hive中实现它的适当指南。https://mukhtharcm.com/hive-custom-objects/
你也可以使用sqlite,因为sharedpreferences不支持对象
sharedpreferences仅用于原始数据而非对象。如果您熟悉sql数据库或Hive for NoSql,建议您使用sqlite
使用String
:写入时编码,读取时解码。可以这样做:
final prefs = await SharedPreferences.getInstance();
await prefs.setString('user', jsonEncode(data['data']));
final user = jsonDecode(prefs.getString('user'));