Issue
I don't know how to access a field that is a list of Strings from QueryDocumentSnapshot object in flutter.
It works if I access the item in the list directly like element['tags'][0]
Is there a way to get the 'tags' field to a list of Strings ? Or to get the size of the list to recreate it by separately getting each item?
Future<UserData> getUserData() async {
QuerySnapshot userExpenses = await getUserExpenses();
List<Expense> expenses = [];
userExpenses.docs.forEach((element) {
Expense e = new Expense();
e.description = element.get('description');
e.price = element.get('price');
e.tags = [];
e.tags.add(element.get('tags')[0]);
e.id = element.id;
expenses.add(e);
});
........
}
Future<QuerySnapshot> getUserExpenses() async {
return FirebaseFirestore.instance
.collection('expenses')
.where('uuid', isEqualTo: FirebaseAuth.instance.currentUser?.uid)
.get();
}
class Expense {
late String id;
late String price;
late String description;
late List<String> tags;
}
Solution
From the test I made, it is not necessary to use the add() method to assign element.get('tags') to the e.tags field.
Since you are initializing an array for your e Expense object, you can assign it straight away using the = equal operator.
But, just remember that when you assign a variable, both elements in the assignment has to be of the same type because if you do as the following:
e.tags = doc.get('tags');
You will get this error:
errors.dart:187 Uncaught (in promise) Error: Expected a value of type 'List', but got one of type 'List'
Because List<dynamic> is not a subtype of List<String>
From there, we should cast the List<dynamic> into List<String> to match the type, like this:
e.tags = List<String>.from(doc.get('tags'));
Answered By - Rogelio Monter

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.