创建计时器时发生 Flutter Null 安全错误 |扑

Flutter Null Safety error while creating a Timer | Flutter

我在将项目从旧版本转移到新的空安全版本时遇到此错误。 这里显示错误 The method '-' can't be unconditionally invoked because the receiver can be 'null'.Try making the call conditional (using '?.') or adding对目标 ('!'). 的空检查它在行 secondsRemaining--; 中显示错误所以我再次添加了一个空检查运算符 secondsRemaining!--; 它显示错误为对不可赋值表达式的非法赋值。下面是我的定时器函数。

int? secondsRemaining;
bool enableResend = false;
late Timer timer;

void startTimer() {
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      if (secondsRemaining != 0) {
          setState(() {
            secondsRemaining--;
          });
      } else {
        setState(() {
          enableResend = true;
        });
      }
    });
  }

如果您像这样重写代码,将无法检查是否有效:

int? secondsRemaining;
bool enableResend = false;
late Timer timer;

void startTimer() {
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      if (secondsRemaining != 0 || secondsRemaining != null) {
          setState(() {
            secondsRemaining = secondsRemaining! - 1;
          });
      } else {
        setState(() {
          enableResend = true;
        });
      }
    });
  }