skip to Main Content

I wrote a code that counts down from 240 seconds to 0 second in the Flutter app.
But only seconds come out here.
All I want is to have minutes and seconds represented

int _Counter = 240;
  late Timer _timer;

  void startTimer(){
    _timer = Timer.periodic(Duration(seconds: 1), (timer){
      if(_Counter > 0){
        setState(() {
          _Counter--;
        });
      }else{
        _timer.cancel();
      }
    });
  }

ex)

  • 240 = 04:00
  • 200 = 03:20
  • 60 = 01:00
  • 10 = 00:10
  • 0 = 00:00

I don’t know how to solve it.
Can someone give me a solution or tell me how?

Thank you.

3

Answers


  1. To calculate the minutes, you must divide the seconds by 60. To calculate the remaining seconds, you must subtract the minutes from the seconds. You can then use padLeft to place a zero in front of a number if it only has one digit.

    String formatTime(int seconds) {
      final minutes = seconds ~/ 60;
      final remainingSeconds = seconds - minutes * 60;
      return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
    }
    
    Login or Signup to reply.
  2. You want to manage it after counter decrementing, look at bellow,

    void startTimer() {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (_counter > 0) {
          setState(() {
            _counter--;
            timerText(); // Call timerText function after decrementing counter
          });
        } else {
          _timer.cancel();
        }
      });
    }
    
    String timerText() {
      int minutes = _counter ~/ 60;
      int seconds = _counter % 60;
      return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    }
    

    In this modification, timerText is now a function that returns a formatted string representing the remaining time. Inside the startTimer function, we call timerText() immediately after decrementing the counter within the setState callback. This ensures that the displayed time gets updated each time the counter decrements.

    Login or Signup to reply.
  3. Package intl has DateFormat. You can turn DateTime into any format you want.

    import 'package:intl/intl.dart';
    
    void main(List<String> arguments) {
      const seconds = 185; // for example
      final df = DateFormat.ms();
      // construct a DateTime that reliably has proper HMS:
      final d = DateTime.utc(2000, 1, 1, 0, 0, seconds);
      final printString = df.format(d);
      print(printString);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search