Search code examples
flutterdartandroid-studiotimer

How to fix LateInitializationError: Field '_timer' has not been initialized in Flutter?


I'm building a Pomodoro app in Flutter and encountering a "LateInitializationError: Field '_timer' has not been initialized" error. I believe it's related to my use of the late keyword:

late Timer _timer; 

I've tried the following without success:

  • Timer? _timer;
  • Timer _timer!;

How can I resolve this error while maintaining the necessary functionality within my Flutter app?

Code:

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}
   

class _HomeState extends State<Home> {
  int remainingTime = pomodoroTotalTime;
  String mainBtnText = _btnTextStart;
  PomodoroStatus pomodoroStatus = PomodoroStatus.pausedPomodoro;
  late Timer _timer;
  int pomodoroNum = 0;
  int setNum = 0;
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: SafeArea(
        child: Center(
          child: Column(
           children:  [
          
          ],
         ),
        ),
      ),
    );
  }


  _cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
}

Solution

  • Please update your code like this,

    Timer? _timer;
    
     _cancelTimer() {
        if (_timer != null) {
          _timer.cancel();
        }
      }
    

    I believe if you use late then first you need to initialize the object and there after you can use it. And due to that, lateinit error was showing. Please update like this and let me know if you still facing error.