【问题标题】:Unable to store the list data into the Getx Storage无法将列表数据存储到 Getx 存储中
【发布时间】:2021-12-23 19:55:59
【问题描述】:

我正在尝试将列表数据保存到 GetX 存储中,即来自我应用程序中的 firestore。

但不知何故,它没有按预期执行。每次我收到错误提示:未处理的异常:将对象转换为可编码对象失败:'DocumentData'的实例

下面,列出我创建的变量:

RxList<DocumentData> todoList = <DocumentData>[].obs;

下面是我试图在 GetX Storage 中写入值的函数。

//Function to get the all todos from firestore
getAllTodosFromFirestore() async {
   await todos.where('uid', isEqualTo: uid).get().then((value) {
    Get.find<TodoController>().todoList.value = value.docs.map((e) => DocumentData.fromJson(e.data() as Map<String,dynamic>)).toList();
    GetStoragePref.instance.writeValues('todos_list',Get.find<TodoController>().todoList);
  });
  return Get.find<TodoController>().todoList;
}

下面是我的 DocumentData 模型类。

class DocumentData {
  DocumentData({
    required this.uid,
    required this.timer,
    required this.itemName,
    required this.isSelectedItem,
  });

  String uid;
  Timestamp timer;
  String itemName;
  bool isSelectedItem;

  factory DocumentData.fromJson(Map<String, dynamic> json) => DocumentData(
    uid: json["uid"],
    timer: json["timer"],
    itemName: json["itemName"],
    isSelectedItem: json["isSelectedItem"],
  );

  Map<String, dynamic> toJson() => {
    "uid": uid,
    "timer": timer,
    "itemName": itemName,
    "isSelectedItem": isSelectedItem,
  };
}

谁能帮我解决这个问题?

【问题讨论】:

    标签: flutter dart flutter-getx


    【解决方案1】:

    您不能直接在 GetStorage 上存储自定义类型(在您的情况下为 DocumentData)。您可以保存原始 JSON(在您的情况下,它应该位于 value.docs 内的某个位置)& 当从 GetStorage 获取数据时,再次将原始 JSON 解析为 DocumentData。

    【讨论】:

    • 是的,我后来也这样做了。但是,我以前的模型还有一个问题是,在获取数据并将数据设置到模态时,数据应该只是其原始类型的形式。 从后端我得到时间戳格式的值之一,这就是控制台中出现上述错误的原因。感谢您的回复!
    猜你喜欢
    • 2020-12-27
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多