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

43 views Asked by At

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);
    }
  }
2

There are 2 answers

3
Rishan Shrestha On

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

0
Hamed On

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'] ?? '',
      ));
    });
...
}