I know this question has been asked multiple times, but even with the suggestions in the other posts I cannot get it solved... I have a class Score
that I want to load from a Firebase backend using Flutter. Here is what the Score
class looks like:
class Score {
final String name;
final List<String> tags;
Score(this.name, this.tags);
Score.fromJson(Map<String, dynamic> json)
: name = json['name'] ?? '',
tags = json['tags'] ?? [''];
}
Now I am loading this from Firebase using a Streambuilder<QuerySnapshot>
, code snippet:
List<Score> scores = snapshot.data!.docs
.map((e) => Score.fromJson(e.data()))
.toList();
This leads to the error The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'
. If I try to cast e.data() as Map<String, dynamic>
as suggested in other posts, the whole app crashes at startup.
Could someone please help me how to convert the snapshot data to a List<Score>
? Thx!
CodePudding user response:
If you know you're getting a map from the database, you can cast the Object
to such a Map
with:
Score.fromJson(e.data() as Map<String, dynamic>)
To convert the tags to a List<String>
requires a different kind of conversion:
List<String>.from(json['tags'])
To learn more about why this is a different type of conversion, see Difference between List<String>.from() and as List<String> in Dart