方法 'cancel' 不能无条件调用,因为接收者可以是 'null'

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

我有以下代码:

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

以及以下错误:

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 ('!').

如何修复此错误消息?

将这些代码行更改为:

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

      _authTimer!.cancel();

问题是 Dart 知道 _expiryDate_authTimer 可以是 null。但是,您通过在 if 语句中检查它们是否都不是 null 来断言它们此时不可能是 null。因此,您可以添加一个 !,这是一个非空断言,基本上是说“我知道这个变量的值可以是 null,但我确定它不能是 null此时'.