Reputation: 2217
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!
Upvotes: 8
Views: 8097
Reputation: 425
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}");
Upvotes: 0
Reputation: 2217
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(),
Upvotes: 9