Julie
Julie

Reputation: 65

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

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

Upvotes: 5

Views: 1491

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 5638

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']],

Upvotes: 13

Fatima ayaa
Fatima ayaa

Reputation: 650

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();

Upvotes: 10

Related Questions