简体   繁体   English

Flutter Firestore - 如何读写对象的 Arrays

[英]Flutter Firestore - How To Read And Write Arrays of Objects

So I've been struggling with reading and writing arrays of objects in Firestore using Flutter. For writing, the array never gets updated in Firestore and I don't know why.所以我一直在努力使用 Flutter 在 Firestore 中读取和写入 arrays 个对象。对于写入,数组永远不会在 Firestore 中更新,我不知道为什么。 I've tried:我试过了:

.updateData({"tasks": FieldValue.arrayUnion(taskList.tasks)});

and

.updateData(taskList.toMap());

but neither seem to do anything.但似乎都没有做任何事情。

For reading, I usually get the error type 'List<dynamic>' is not a subtype of type 'List<Task>' .对于阅读,我通常会得到错误type 'List<dynamic>' is not a subtype of type 'List<Task>' I'm pretty sure it has something to do with my class structure but I can't figure it out.我很确定它与我的 class 结构有关,但我无法弄清楚。 I've tried many different ways to get the data as a List of Tasks but all attempts have failed.我尝试了许多不同的方法来将数据作为任务列表获取,但所有尝试都失败了。 Here is my current broken code:这是我当前损坏的代码:

TaskList.dart任务列表.dart

class TaskList {
  String name;
  List<Task> tasks;

  TaskList(this.name, this.tasks);

  Map<String, dynamic> toMap() => {'name': name, 'tasks': tasks};

  TaskList.fromSnapshot(DocumentSnapshot snapshot)
      : name = snapshot['name'],
        tasks = snapshot['tasks'].map((item) {
          return Task.fromMap(item);
        }).toList();

}

Task.dart任务.dart

class Task {
  String task;
  bool checked;

  Task(this.task, this.checked);

  Map<String, dynamic> toMap() => {
        'task': task,
        'checked': checked,
      };

  Task.fromMap(Map<dynamic, dynamic> map)
      : task = map['task'],
        checked = map['checked'];
}

Any help or advice is appreciated!任何帮助或建议表示赞赏!

I ended up making the tasks list of type dynamic and that solved most of my reading problems. 最后,我使任务列表的类型变为动态的,从而解决了我的大多数阅读问题。 Still don't understand why though. 还是不明白为什么。

List<Task> tasks;

And for writing, I just changed the fromMap() to toMap() for initializing the tasks. 编写时,我只是将fromMap()更改为toMap()来初始化任务。

'tasks': tasks.map((item) {
      return item.toMap();
    }).toList(),

Get an array from firebase you can use query snapshot to get arraylist从 firebase 获取一个数组,您可以使用查询快照获取 arraylist

QuerySnapshot querySnapshot =
            await FirebaseFirestore.instance.collection('EnglishQuotes').get();
// for a specific field
final allData =  querySnapshot.docs.map((doc) => doc.get('item_text_')).toList();
print("length = ${allData.length}");
print("all data = ${allData}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM