7

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. 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>'. I'm pretty sure it has something to do with my class structure but I can't figure it out. 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

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

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!

Jared
  • 2,029
  • 5
  • 20
  • 39
  • have a look at this answer please https://stackoverflow.com/a/53149420/2863386 – Shyju M Jan 03 '19 at 06:24
  • Look at this [answer](https://stackoverflow.com/a/54851198/13648205), this has solved the issue for me – w461 Dec 09 '20 at 10:48
  • Look at this [answer](https://stackoverflow.com/a/54851198/13648205), this has solved the issue for me – w461 Dec 09 '20 at 10:50

2 Answers2

7

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.

'tasks': tasks.map((item) {
      return item.toMap();
    }).toList(),
Jared
  • 2,029
  • 5
  • 20
  • 39
  • Similar documentation from Flutter here: https://flutter.dev/docs/development/data-and-backend/json#serializing-json-inside-model-classes – Matthew Rideout Jul 04 '20 at 23:02
0

Get an array from firebase you can use query snapshot to get 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}");
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rishita Joshi
  • 203
  • 2
  • 3