0
votes

I am working on decoding the JSON object I got from the firebase. But I get the error like below on typecasting the response to Map.

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List' is not a subtype of type 'List'

Product model

class Product with ChangeNotifier {
  final String id;
  final String title;
  final String description;
  final double price;
  final String imageUrl;
  bool isFavorite;

  Product(
      {this.isFavorite = false,
      @required this.id,
      @required this.title,
      @required this.description,
      @required this.price,
      @required this.imageUrl});

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    notifyListeners();
  }
}
Future<void> fetchAndSetProducts() async {
    const url = 'https://myshop-*****.firebaseio.com/products.json';
    try {
      final response = await http.get(url);
      final loadedProducts = [];
      print(response.body);
      final extractedData =
          json.decode(response.body) as Map<String, dynamic>;

      extractedData.forEach((prodId, value) {
        loadedProducts.add(Product(
            id: prodId,
            description: value['description'],
            title: value['title'],
            price: value['price'],
            imageUrl: value['imageUrl'],
            isFavorite: value['isFavorite']));
      });
      _item = loadedProducts;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

My response from Firebase is

{
  "-M0YDsU3HT89_wzAx1GQ": {
    "description": "shirt",
    "imageUrl": "https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
    "isFavorite": false,
    "price": 79,
    "title": "shirt"
  }
}
1
Can you add more context code to your problem, we don't see what code you execute to crash your app ? Thanks - Yooooomi
I have included the code where the url is called. - Prabitha Nair
What is the type of _item? - Augustin R
You are trying to forEach a map, and your answer from firebase is not a List neither - Yooooomi

1 Answers

1
votes

The problem is that you are trying to do this assignment

_item = loadedProducts;

where _item is of type List<Product> and loadedProducts a List<dynamic>.

Try to initialize loadedProducts like this :

// final loadedProducts = [];        // Remove this line
List<Product> loadedProducts = [];   // Use this instead