user11874694
user11874694

Reputation:

The method 'cancel' can't be unconditionally invoked because the receiver can be 'null'

I have the following code:

class Auth with ChangeNotifier {
  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;

  String? get token {
    if (_expiryDate != null &&
        _expiryDate.isAfter(DateTime.now()) &&
        _token != null) {
      return _token;
    }
    return null;
  }

  Future<void> logout() async {
    _token = null;
    _userId = null;
    _expiryDate = null;
    if (_authTimer != null) {
      _authTimer.cancel();
      _authTimer = null;
    }
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    // prefs.remove('userData');
    prefs.clear();
  }
}

And the following errors:

The method 'isAfter' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').

The method 'cancel' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').

How can I fix this error messages?

Upvotes: 1

Views: 305

Answers (1)

Tim Jacobs
Tim Jacobs

Reputation: 1183

Change these lines of code to this:

        _expiryDate!.isAfter(DateTime.now()) &&

      _authTimer!.cancel();

The issue is that Dart knows that _expiryDate or _authTimer can be null. However, you assert by checking them both for not being null in your if statement that they cannot possibly be null at that point. Thus, you can add a !, which is a non-null assertion, basically saying 'I know this variable can have a value of null, but I'm sure that it can't be null at this point'.

Upvotes: 1

Related Questions