0

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

1 Answer 1

1

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,
Sign up to request clarification or add additional context in comments.

1 Comment

This work but, I'm curious about what happened here could you please explain?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.