'Type 'List<dynamic>' is not a subtype of type 'List<String> in flutter

when I fetch data from firebase

I got these errors like

why list dynamic could change into String type ?

type 'List<dynamic>' is not a subtype of type 'List<String> 

I put the code below it. the loaded product does not contain items

Future<void> fetchandSetProduct() async {
    final url =
        Uri.https('cakejaffna-default-rtdb.firebaseio.com', '/cakelist.json');

    try {
      final response = await http.get(url);
      print(response.statusCode);

      final extractData = json.decode(response.body) as Map<String, dynamic>;
      final List<Cake> loadedProduct = [];
      print(extractData);
      extractData.forEach((cakeId, cakeData) {
        loadedProduct.add(Cake(
            id: cakeId,
            imageUrl: cakeData['imageUrl'],
            title: cakeData['title'],
            hotelName: cakeData['hotelName'],
            rating: cakeData['rating'],
            ratecount: cakeData['ratecount'],
            amount: cakeData['amount'],
            details: cakeData['details'],
            categories: cakeData['categories']));
      });
      _cakeList = loadedProduct ;
      notifyListeners();
    } catch (error) {
      print(error);
      print("relly error");
    }
  }


Solution 1:[1]

I think in your Cake model class categories is List<String> changing it to List<dynamic> should fix the problem.

Solution 2:[2]

you can use as for type.

for Example :

 extractData.forEach((cakeId, cakeData) {
        loadedProduct.add(Cake(
            id: cakeId as int,
            imageUrl: cakeData['imageUrl'] as String,
            title: cakeData['title'] as String,
            hotelName: cakeData['hotelName'] as String,
            rating: cakeData['rating'] as double,
            ratecount: cakeData['ratecount'] as int,
            amount: cakeData['amount'] as int,
            details: cakeData['details'] as list<String>,
            categories: cakeData['categories'] as String));
      });

Solution 3:[3]

Am assuming cakeData['categories'] is a list of categories? then you would do this

(cakeData['categories'].map((e) => e.toString())).toList()

Please note the parenthesis, they are important since you're converting the map to a list so you have to wrap the map with those parenthesis like this (map).toList();

And then you simply do this to each data point where you know it will be a list, of course you return any object if needed, in this case am returning a String. Simply trying to cast it to a list of strings List<String> will not work in this case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pradeep Tintali
Solution 2 mshamsi502
Solution 3 Bola Gadalla