我希望将用户详细信息响应保存在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;
  }

推荐答案

更新您的类以覆盖toStringMedthod.这将在您打印时以可读的格式显示您的类:

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"]));

  @override
  String toString() {
    return 'UserLoginResponseEntity{code: $code, msg: $msg, data: $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
      };

  @override
  String toString() {
    return 'UserItem{token: $token, name: $name, description: $description, avatar: $avatar, type: $type, email: $email}';
  }
}

但是,您不能使用共享首选项保存DART类,但可以保存字符串来执行此操作,而不使用类的toString方法;请执行以下操作:

UserItem中使用toJson方法将result.data转换为Map<String, dynamic>;然后将该数据编码为Json字符串,如下所示:

final userItemJsonString =  json.encode(result.data.toJson());

要从共享首选项中获取UserItem对象,解码返回的Json字符串:

final userItem = UserItem.fromJson(json.decode(userItemJsonString))

Json相关问答推荐

如何在JMESPath中区分空和假?

JOLT转换过滤出特定值/对象

按照对象键的值对PostgreSQL JSONB对象进行排序'

来自json的可分析的构建报告

使用快速json库编写json可以消除所有缩进

nlohmann json:为什么我会得到一个解析错误?

如何强制仅有一个元素的数组在JSON中生成方括号

无法在 json --data 中使用变量

shell解析json并循环输出组合变量

如何在 wso2 中组合 2 个 json 有效负载?

使用 json 值过滤 Django 模型

从 JSON 对象中删除键值对

JSON Schema 与 XML Schema 的比较及其future

将json字符反序列化为枚举

如何在 json 编码字符串内的子数组数据周围添加方括号?

如何创建 JSON 对象 Node.js

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

case 类只有一个字段时如何将json转为 case 类

从 JSON 到 JSONL 的 Python 转换

在 iPhone 上解析 JSON 日期