我希望将用户详细信息响应保存在sharedPference中,以便用户可以在任何时候恢复应用程序,只要他/她没有注销,但当我试图检索我存储在sharedPreferences中的数据时,这会一直返回NULL.我真的不知道该怎么做.
这是我后台登录成功后返回的数据:
{"message":"Login Successfully","data":{"id":1,"type":1,"name":"Elijah","email":"ukemedmet@gmail.com","profileImage":"http://192.168.229.108:8080/download/887c17f8-1f45-450e-8e45-a12b8a307e5a","accessToken":"OPXI5X98lcdvjUjgRiZTYvcDSjH2"},"code":200}
如果我try 打印asyncPostData
方法中的result.toString
,我得到的是UserLoginResponseEntity
的实例,而result.data
返回的是UserItem
的实例,而不是json数据.所有我需要知道的是如何存储"数据"项目,其中包含姓名,邮箱等登录的用户在共享首选项."data"项是一个json对象,它包含响应中所示的所有用户信息
class AppApi {
static login({LoginRequestEntity? loginRequestEntity}) async {
var response = await NetworkRequestUtil().post(
AppConstants.LOGIN_URL,
data: loginRequestEntity!.toJson(),
);
return UserLoginResponseEntity.fromJson(response);
}
}
Future<void> asyncPostData(LoginRequestEntity loginRequestEntity) async {
var result = await AppApi.login(loginRequestEntity: loginRequestEntity);
if (result.code == 200) {
try {
//method to save the user data in sharedpreference
Global.service.setString(
AppConstants.STORAGE_USER_PROFILE_KEY, jsonEncode(result.data));
if (context.mounted) {
Navigator.of(context)
.pushNamedAndRemoveUntil("/home", (route) => false);
}
} catch (e) {
print("Local storage info saving error ${e.toString()}");
}
} else {
toastInfo(msg: "Error Occurred");
}
}
class UserLoginResponseEntity {
int? code;
String? msg;
UserItem? data;
UserLoginResponseEntity({
this.code,
this.msg,
this.data,
});
factory UserLoginResponseEntity.fromJson(Map<String, dynamic> json) =>
UserLoginResponseEntity(
code: json["code"],
msg: json["message"],
data: UserItem.fromJson(json["data"]));
}
class UserItem {
String? token;
String? name;
String? description;
String? avatar;
int? type;
String? email;
UserItem({
this.token,
this.name,
this.description,
this.avatar,
this.type,
this.email,
});
factory UserItem.fromJson(Map<String, dynamic> json) => UserItem(
token: json["accessToken"],
name: json["name"],
avatar: json["profileImage"],
type: json["type"],
email: json["email"]);
Map<String, dynamic> toJson() => {
"accessToken": token,
"name": name,
"profileImage": avatar,
"type": type,
"email": email
};
}
class StorageService {
late SharedPreferences _pref;
Future<StorageService> initSharedPreference() async {
_pref = await SharedPreferences.getInstance();
return this;
}
//method to return the stored user data if it's not null
//this method always returns null I don't know why my data wasn't saved in sharedpreference
UserItem? getUserProfile() {
var offlineProfile =
_pref.getString(AppConstants.STORAGE_USER_PROFILE_KEY) ?? "";
if (offlineProfile.isNotEmpty) {
UserItem.fromJson(jsonDecode(offlineProfile));
}
return null;
}