Flutter Null Safety error while creating a Timer | Flutter

Issue

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

Solution

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

Answered By – Hooshyar

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *