如何在flutter中将响应数据保存到sharedPreference中

问题描述 投票:0回答:1

我想将用户详细信息响应保存在sharedPreference中,以便用户只要不注销就可以随时恢复应用程序,但当我尝试检索存储在sharedpreference中的数据时,它会继续返回null。我真的不知道该怎么办。

这是我登录成功后后台返回的数据:

{"message":"Login Successfully","data":{"id":1,"type":1,"name":"Elijah","email":"[email protected]","profileImage":"http://192.168.229.108:8080/download/887c17f8-1f45-450e-8e45-a12b8a307e5a","accessToken":"OPXI5X98lcdvjUjgRiZTYvcDSjH2"},"code":200}

如果我尝试在

result.toString
方法中打印
asyncPostData
,我会得到
UserLoginResponseEntity
的实例,并且
result.data
返回
UserItem
的实例而不是 json 数据。我所需要的只是知道如何在sharedPreference 中存储包含登录用户的姓名、电子邮件等的“数据”项。 “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;
  }
json flutter sharedpreferences
1个回答
0
投票

这似乎是一个班级的信息。根据你的问题,我发现result.data是一个名为UserItem的类,result是一个名为UserLoginResponseEntity的类。

如果您的问题是如何将其转换为 json 文本,您可以按照以下说明操作

将类转换为 Json

result.data.toJson();

这是将

result.data
转换为
Map<String, dynamic>

要获得

Map<String, dynamic>
String
,请尝试

json.encode(mapObject);

json.decode(encodedObject);

获取

String
Map<String, dynamic>

然后为了保存字符串,您可以使用Hive共享首选项

© www.soinside.com 2019 - 2024. All rights reserved.