Home > front end >  Flutter Null Safety error while creating a Timer | Flutter
Flutter Null Safety error while creating a Timer | Flutter

Time:10-06

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

CodePudding user response:

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