Home > other >  Flutter - Life Cycle
Flutter - Life Cycle

Time:01-20

Thanks for reading my questions

I wonder again why the error shown below is printed when I navigate to timer page.

I want to know how can I fix it.

The following LateError was thrown while finalizing the widget tree: LateInitializationError: Field 'timer' has not been initialized.

This is my timer code!

class Pomodoro extends StatefulWidget {
  @override
  _PomodoroState createState() => _PomodoroState();
}

class _PomodoroState extends State<Pomodoro> {
  double coinCount = 0;
  Stopwatch watch = Stopwatch();
  late Timer timer;
  bool startStop = true;

  String elapsedTime = '';

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  updateTime(Timer timer) {
    if (watch.isRunning) {
      setState(() {
        elapsedTime = transformMilliSeconds(watch.elapsedMilliseconds);
      });
      if (coinCount == 360000) {
        context.read<Counts>().add(1);
        coinCount = 0;
      } else {
        coinCount = coinCount   10;
      }
      context.read<Times>().timeAdd(100);
    }
  }

  restartTimer() {
    updateTime(timer).cancel();
    setState(() {
      startStop = true;
      watch.stop();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(elapsedTime,
                style: TextStyle(fontFamily: 'Kitto', fontSize: 25.0)),
            SizedBox(height: 20.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                IconButton(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  onPressed: () => startOrStop(),
                  icon: Image.asset('assets/button.png'),
                  iconSize: 50,
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  startOrStop() {
    if (startStop) {
      startWatch();
    } else {
      stopWatch();
    }
  }

  startWatch() {
    setState(() {
      startStop = false;
      watch.start();
      timer = Timer.periodic(Duration(milliseconds: 100), updateTime);
    });
  }

  stopWatch() {
    setState(() {
      startStop = true;
      watch.stop();
      setTime();
    });
  }

  setTime() {
    var timeSoFar = watch.elapsedMilliseconds;
    setState(() {
      elapsedTime = transformMilliSeconds(timeSoFar);
    });
  }

  transformMilliSeconds(int milliseconds) {
    int hundreds = (milliseconds / 10).truncate();
    int seconds = (hundreds / 100).truncate();
    int minutes = (seconds / 60).truncate();
    int hours = (minutes / 60).truncate();

    String hoursStr = (hours % 60).toString().padLeft(2, '0');
    String minutesStr = (minutes % 60).toString().padLeft(2, '0');
    String secondsStr = (seconds % 60).toString().padLeft(2, '0');

    return "$hoursStr:$minutesStr:$secondsStr";
  }
}

If you know how to fix it, I hope you answered to my question.

I would be grateful for your answer.

And Have a nice day!

CodePudding user response:

I don't think you should use late in that case. Adding late to field means that the field will be initialized when you use it for the first time. use late when you strongly convinced that first time you use late field it will be initialized. And always remember that using late makes you code less safe and adds possibility of runtime errors.

You don't want a late variable, you want a nullable one. If you need to check if something is initialized, you should be using a nullable variable instead and your code is already set up to check for null.

Just change

late Timer timer;

to

Timer? timer;
  •  Tags:  
  • Related