'The property 'quantity' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.')

Relevent code

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });
}

class Cart with ChangeNotifier {
  Map<String, CartItem> _items = {}; // see that I have initialized the items

The code where I am getting the null safety error 'The property 'quantity' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').' The error I am getting is on the below quantity variable. I am not sure how to fix it. I have watched videos which talked about int?, ! and ?: operators but this particular scenario was not covered.

if (_items[productID].quantity == 1) _items.remove(productID);

Additional questions, what is the receiver here that the error is point to which can be null?



Solution 1:[1]

try this, it's works for me.

if (_items[productID]?.quantity != 1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick