-1

I getting this error while i shift my project from old version to new null safety version. Here it show error The method '-' 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 ('!'). It shows error in the line secondsRemaining--; so i added a null check operator secondsRemaining!--; again it shows error as Illegal assignment to non-assignable expression. The below is my timer function.

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

  • This is https://github.com/dart-lang/language/issues/1113. However, you should consider making `secondsRemaining` non-nullable. It'd make more sense for `timer` to be nullable instead. – jamesdlin Oct 06 '21 at 07:04

1 Answers1

1

null check on works if you re-write the code like this:

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;
        });
      }
    });
  }
Yann39
  • 14,285
  • 11
  • 56
  • 84
Hooshyar
  • 1,181
  • 4
  • 12
  • 28