Home > Software engineering >  fetcing data error :Unhandled Exception: NoSuchMethodError: The method '[]' was called on
fetcing data error :Unhandled Exception: NoSuchMethodError: The method '[]' was called on

Time:09-01

Hello everyone!
I am trying to fetch my product Data from Firebase server ,when i sign in i got this error:
Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.

when I face this problem before i added these variable to the function below:

   bool? _isFavorite =
        favoriteData[key] != null || favoriteData[key] == 'true'
            ? true
            : false;

but when i deleted favorite data from the server it gave me error again! it should take the "False"value when it null!
i think my error related to null safety but i cant fix it i will share the Function which related to to this error and model and if there any solution I would be grateful for it ,Thank you!

Fetch Data Function:

  Future<void> fetchAndSetProducts([bool filterByUser = false]) async {
final filterString =
    filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' : '';
var url =
    'https://ecommerce-test-753ad-default-rtdb.firebaseio.com/products.json?auth=$authToken&$filterString';
try {
  final response = await http.get(Uri.parse(url));
  final extractedData = json.decode(response.body) as Map<String, dynamic>;
  if (extractedData == {}) {
    return;
  }
  url =
      'https://ecommerce-test-753ad-default-rtdb.firebaseio.com/userFavorites/$userId.json?auth=$authToken';
  final favoriteResponse = await http.get(Uri.parse(url));
  final favoriteData = json.decode(favoriteResponse.body);
  print(favoriteData);
  print(extractedData);
  final List<Product> loadedProduct = [];
  extractedData.forEach((key, value) {
    bool? _isFavorite =
        favoriteData[key] != null || favoriteData[key] == 'true'
            ? true
            : false;
    loadedProduct.add(
      Product(
        id: key,
        title: value['title'],
        price: value['price'],
        imageUrl: value['imageUrl'],
        description: value['description'],
        isFavorite: _isFavorite,
      ),
    );
  });
  _productItems = loadedProduct;
  notifyListeners();
} catch (e) {
  rethrow;
}

}

product Model class:

 class Product with ChangeNotifier {
     final String id;
     final String title;
     final double price;
     final String imageUrl;
     final String description;
     bool isFavorite;

    Product({
   required this.id,
 required this.title,
 required this.price,
 required this.imageUrl,
 required this.description,
 this.isFavorite = false,
  });


 void _setFavValue(bool newValue) {
  isFavorite = newValue;
  notifyListeners();
  }

Future<void> toggleFavoriteStatus(String authToken, String 
 userId) async {
  final oldStatus = isFavorite;
   isFavorite = !isFavorite;
  notifyListeners();
 final url =
     'https://ecommerce-test-753ad-default- 
rtdb.firebaseio.com/userFavorites/$userId/$id.json? 
auth=$authToken';
  try {
   final response = await http.put(
     Uri.parse(url),
    body: json.encode(isFavorite),
  );
  if (response.statusCode >= 400) {
    _setFavValue(oldStatus);
  }
} catch (error) {
  _setFavValue(oldStatus);
}
}

I also Added this line to Firebase rules:
"products":{ ".indexOn":["creatorId"],

CodePudding user response:

By checking favoriteData[key] for null is not enough, it is possible that favoriteData itself is null, try this:

bool? _isFavorite =
       favoriteData != null && favoriteData[key] != null && favoriteData[key] == 'true'
            ? true
            : false;

CodePudding user response:

Try this:

   final value = favoriteData == null ? false : favoriteData[key] != null || favoriteData[key] == 'true';
   bool? _isFavorite = value;
  • Related