8

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!

3
  • have a look at this answer please stackoverflow.com/a/53149420/2863386 Commented Jan 3, 2019 at 6:24
  • Look at this answer, this has solved the issue for me Commented Dec 9, 2020 at 10:48
  • Look at this answer, this has solved the issue for me Commented Dec 9, 2020 at 10:50

2 Answers 2

9

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(),
Sign up to request clarification or add additional context in comments.

1 Comment

Similar documentation from Flutter here: flutter.dev/docs/development/data-and-backend/…
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}");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.