Search code examples
fluttertimerstate

My Timer is going crazy , It decrements 2 , 3 seconds when it should only 1 (Timer is being called every second)


A very simple timer written in Flutter. But the timer's time is jumping from 1 to 3 , 3 to 6 (crazy) and it goes to -(minus) value when it should stop. Using setState to update the time. Here is the code

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Timer Demo',
      home: MyHomePage(title: 'My Timer'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void updateUI()=>setState((){});
  var timer=MyTimer();
  
  @override
  Widget build(BuildContext context) {
    timer.start(updateUI);
    return Scaffold(
      appBar: AppBar(
        title: Text('Timer'),
      ),
      body: Center(
        child: Text(timer.time.toString()),
      ),
    );
  }
}

class MyTimer{
  int time=10;
  
  start(Function callback){
    Timer.periodic((Duration (seconds:1)),(timer){
      time--;
      callback();
      if(time<1) timer.cancel();
    });
  }
}

I am building the app for windows desktop


Solution

  • You are starting timer inside the build() method, meaning every time the UI is rerendered, the start() function is called inside MyTimer class.

    You can try calling the timer.start(updateUI) inside the initState method (add it to _MyHomePageState), e.g:

    @override
    void initState() {
      super.initState();
      timer.start(updateUI);
    }