skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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'] ?? '',
          ));
        });
    ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search