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!
Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects. Firestore always stores numbers as doubles, regardless of what type of number you use in your code.
How do you create an array in Flutter? A new array can be created by using the literal constructor [] : import 'dart:convert'; void main() { var arr = ['a','b','c','d','e']; print(arr); import 'dart:convert'; void main() { var arr = new List(5);// creates an empty array of length 5.
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(),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With