Firestore returns List<dynamic> instead of List<String> (flutter)

Viewed 627

I have a firestore database set up with an Array of strings. In my code I have this:

  factory Item.fromMap(Map<String, dynamic> map) {
    return Item(
      name: map['name'],
      imageUrls: map['imageUrls'];

imageUrls is a List of Strings. I googled how to handle Lists, but I think it should be able to handle it like this? I get this error:

  Expected a value of type List<String>, but got one of type List<dynamic>

Thank you for any input

2 Answers

you have to cast map['imageUrls'] to List

   factory Item.fromMap(Map<String, dynamic> map) {
        return Item(
          name: map['name'],
          imageUrls: (map['imageUrls'] as List)?.map((item) => item as String)?.toList();

You can try one of the following ways to handle type conversion.

imageUrls: List<String>.from(map['imageUrls']),
imageUrls: (map['imageUrls'] as List).map((element) => element as String).toList(),
imageUrls: <String>[...map['imageUrls']],
Related