0

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!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Pieter
  • 2,621
  • 4
  • 19
  • 26

1 Answers1

1

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • tried that, but then the app crashes at runtime saying "_TypeError (type 'List' is not a subtype of type 'List')" (referring to the tags line in the Score class) – Pieter Dec 30 '21 at 19:05
  • That's a different error, but I added it to my answer too. – Frank van Puffelen Dec 30 '21 at 19:13
  • 1
    fantastic, that works! I tried the latter method too, did not work, and I've discarded it as a viable solution... only to see now that my argument between the parentheses contains an error... so your solution is 100% helpful and on the go I learned something on different sorts of casting too... thanks!! – Pieter Dec 31 '21 at 05:59