Home > Back-end >  How to get data from nested object from firebase?
How to get data from nested object from firebase?

Time:09-10

So I'm currently following course flutter and here I'm trying to get some data from the nested object from firebase

this one call when fetching data

 final favoriteResponse = await http.get(url);
      final favoriteData = json.decode(favoriteResponse.body);
      final List<Product> loadedProducts = [];
      extractedData.forEach((prodId, prodData) {
        loadedProducts.add(Product(
          id: prodId,
          title: prodData['title'],
          description: prodData['description'],
          price: prodData['price'],
          isFavorite: favoriteData == null
              ? false
              : favoriteData[prodId]['isFavorite'] ?? false,
          imageUrl: prodData['imageUrl'],
        ));
        print(favoriteData[prodId]);
      });
      _items = loadedProducts;
      notifyListeners();

as you can see on the is favorite I want to get it from favoritedata[prodId]['isFavorite], why I'm using it like that because if I print favoritedata[prodId] the result is {'isFavorite':true} so I call like this favoritedata[prodId]['isFavorite] that get of boolean data, but its give me an error like this:

/flutter (15722): Receiver: null
I/flutter (15722): Tried calling: []("isFavorite")

also, this one is for updating the value to the database

try {
      final response = await http.put(
        url,
        body: json.encode(
          {
            'isFavorite': isFavorite,
          },
        ),
      );

      if (response.statusCode >= 400) {
        _setFavValue(oldStatus);
      }
    } catch (error) {
      _setFavValue(oldStatus);
    }

CodePudding user response:

You just checking for favoriteData to not be null, but also favoriteData[prodId] could be null, so you need check that too. Change this

isFavorite: favoriteData == null
              ? false
              : favoriteData[prodId]['isFavorite'] ?? false,

to this:

isFavorite: favoriteData == null || favoriteData[prodId] == null
              ? false
              : favoriteData[prodId]['isFavorite'] ?? false,
  • Related