Search code examples
timerflutter

Flutter - How to show a timer running for 60 seconds inside a Text()


I am building an app that will need to show a timer inside a Text(), with duration of 60 seconds, when the screen opens, the timer starts from 0 to 60 seconds automatically inside a Text().

I tried to use Time Builder lib but I have no ideia how to get the time (minutes and seconds) running to put inside the Text().

class ClockWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return TimerBuilder.periodic(Duration(seconds: 60),
      builder: (context) {
        return Text("00:00");
      }
    );
  }

}

Solution

  • I had to use AnimatedBuilder to solve my problem.

      String get timerString {
        Duration duration = controller.duration * controller.value;
        return '${(duration.inSeconds  % 60).toString().padLeft(2, '0')}';
      }
    
    AnimatedBuilder(
                  animation: controller,
                  builder: (context, child){
                    return Text(
                      timerString,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ) ,
                    );
                  }
              ),