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

Issue

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

This is because you are trying to access a valid in a map, by passing a key to it.
If the id exist as a key in the map, then you will have a cartitem object indeed. But if the id does not exist, the result will be null, and your operation will become null.quantity.

The receiver here is your cartitem object.

Try:

_items[productID]!.quantity

This way, you promise dart that it’s impossible to be null. Your error will go away, but this is a risky operation. The proper way to fix this, is make sure it’s not null, before calling quantity on it.

Before your if statement, do this:

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

This way, you will for sure not make it into your second if statement, unless cartitem is not null, 100%.

Answered By – Huthaifa Muayyad

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.