【问题标题】:Flutter Null Safety error while creating a Timer | Flutter创建计时器时出现 Flutter Null 安全错误 |扑
【发布时间】:2021-11-26 08:19:39
【问题描述】:

当我将项目从旧版本转移到新的空安全版本时出现此错误。 这里显示错误不能无条件调用方法'-',因为接收者可以是'null'。尝试使调用有条件(使用'?.')或向目标添加空检查('!')。它在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;
        });
      }
    });
  }

【问题讨论】:

标签: flutter dart timer flutter-web dart-null-safety


【解决方案1】:

如果您像这样重写代码,则可以进行空值检查:

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

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 2023-04-09
    • 2023-01-23
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多