Flutter Firestore - How To Read And Write Arrays of Objects

6,578

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(),
Share:
6,578
Jared
Author by

Jared

Updated on December 08, 2022

Comments

  • Jared
    Jared over 1 year

    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!

  • Matthew Rideout
    Matthew Rideout almost 4 years
    Similar documentation from Flutter here: flutter.dev/docs/development/data-and-backend/…