Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' get data

I want to take the product(entry) id in the database as the ['id'] of the object in the code, but I get this error code database

Future<void> fetchAndSetProducts() async {
    final url =
        Uri.parse('https://flutter-update.firebaseio.com/products.json');
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      final List<Product> loadedProducts = [];
      extractedData.forEach((prodId, prodData) {
        loadedProducts.add(Product(
          id: prodId,
          title: prodData['title'],
          description: prodData['description'],
          price: prodData['price'],
          isFavorite: prodData['isFavorite'],
          imageUrl: prodData['imageUrl'],
        ));
      });
      _items = loadedProducts;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

Upvotes: 0

Views: 50

Answers (2)

Hamed Rezaee
Hamed Rezaee

Reputation: 7232

try this one:

Future<void> fetchAndSetProducts() async {
...
    extractedData.forEach((prodId, prodData) {
      loadedProducts.add(Product(
        id: prodId,
        title: prodData['title'] ?? 'Untitled',
        description: prodData['description'] ?? '',
        price: (prodData['price'] ?? 0).toDouble(),
        isFavorite: prodData['isFavorite'] ?? false,
        imageUrl: prodData['imageUrl'] ?? '',
      ));
    });
...
}

Upvotes: 0

Rishan Shrestha
Rishan Shrestha

Reputation: 76

Errorsuggest that, you are trying to access an element of a string with an index of non-integer value Could you share the data received from the json file, and also printing prodData would be more help, as it suggest that prodData seems to be string rather than Map type you are expecting

Upvotes: 0

Related Questions