flutter - how to best practice make a countdown widget

Muhammad Imanudin

Im developing a soccer match schedule application see image. I want to add a countdown when kick off the match. How to best practice make a countdown widget with the format hh : mm : ss ?

MαπμQμαπkγVπ.0

Both in the comment will have good results. It is also best to rely on Flutter documentation for guidance.

With that, I've made a little sample of a countdown timer based on your requirements.

First, I've tried to define what kind of input I'm going to use. Decided to implement the input this way:

//Update the time in 'YYYY-MM-DD HH:MM:SS' format
final eventTime = DateTime.parse('2021-01-09 03:41:00');

So that I can supply the exact date and time I needed.

Then get the difference from the current date and time and convert it to seconds:

int timeDiff = eventTime.difference(DateTime.now()).inSeconds;

Then created a function that would handle the clocking of the timer:

void handleTick() {
    if (timeDiff > 0) {
      if (isActive) {
        setState(() {
          if (eventTime != DateTime.now()) {
            timeDiff = timeDiff - 1;
          } else {
            print('Times up!');
            //Do something
          }
        });
      }
    }
  }

So when the timer is working as expected, I've just used mathematical operation to define the remaining days, hours, minutes and seconds:

int days = timeDiff ~/ (24 * 60 * 60) % 24;
int hours = timeDiff ~/ (60 * 60) % 24;
int minutes = (timeDiff ~/ 60) % 60;
int seconds = timeDiff % 60;

If you just need the HH:MM:SS format you can just play around and omit that section, check the working code:

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

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

class TimerApp extends StatefulWidget {
  @override
  _TimerAppState createState() => _TimerAppState();
}

//Update the time in 'YYYY-MM-DD HH:MM:SS' format
final eventTime = DateTime.parse('2021-01-09 03:41:00');

class _TimerAppState extends State<TimerApp> {
  static const duration = const Duration(seconds: 1);

  int timeDiff = eventTime.difference(DateTime.now()).inSeconds;
  bool isActive = false;

  Timer timer;

  void handleTick() {
    if (timeDiff > 0) {
      if (isActive) {
        setState(() {
          if (eventTime != DateTime.now()) {
            timeDiff = timeDiff - 1;
          } else {
            print('Times up!');
            //Do something
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (timer == null) {
      timer = Timer.periodic(duration, (Timer t) {
        handleTick();
      });
    }

    int days = timeDiff ~/ (24 * 60 * 60) % 24;
    int hours = timeDiff ~/ (60 * 60) % 24;
    int minutes = (timeDiff ~/ 60) % 60;
    int seconds = timeDiff % 60;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.grey[700],
          title: Center(
            child: Text('Countdown Timer'),
          ),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  LabelText(
                      label: 'DAYS', value: days.toString().padLeft(2, '0')),
                  LabelText(
                      label: 'HRS', value: hours.toString().padLeft(2, '0')),
                  LabelText(
                      label: 'MIN', value: minutes.toString().padLeft(2, '0')),
                  LabelText(
                      label: 'SEC', value: seconds.toString().padLeft(2, '0')),
                ],
              ),
              SizedBox(height: 60),
              Container(
                width: 200,
                height: 47,
                margin: EdgeInsets.only(top: 30),
                child: RaisedButton(
                  color: isActive ? Colors.grey : Colors.green,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25)),
                  child: Text(isActive ? 'STOP' : 'START'),
                  onPressed: () {
                    setState(() {
                      isActive = !isActive;
                    });
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class LabelText extends StatelessWidget {
  LabelText({this.label, this.value});

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5),
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25),
        color: Colors.grey,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text(
            '$value',
            style: TextStyle(
                color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
          ),
          Text(
            '$label',
            style: TextStyle(
              color: Colors.white70,
            ),
          ),
        ],
      ),
    );
  }
}

Here is the output of the countdown timer I've created:

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to make a countdown in flutter?

From Dev

how the best practice for to create dynamic content of SimpleDialog widget in flutter?

From Dev

Initialize final variable in Flutter widget - best practice

From Dev

Flutter - Create a countdown widget

From Dev

How to Make Widget Flutter Fast?

From Dev

How to make a spinning circle animation during a countdown in flutter?

From Dev

How to make a widget flexible on different screens in Flutter?

From Dev

flutter: how to make reusable gridView widget

From Dev

Flutter how to make a selectable / focusable widget

From

How to make copyable Text Widget in Flutter?

From Dev

How to make custom widget/component in flutter?

From Dev

How to make a widget that is constantly growing and shrinking in Flutter?

From Dev

how to make one widget as master in flutter

From Dev

How can make an expand/collapse widget in flutter?

From Dev

how can I make this stack widget in flutter?

From Dev

how to make similar widget list with addition Flutter

From Dev

How to make the design using widget in Flutter

From Dev

make reverse countdown timer in flutter

From Dev

Flutter - How to make a custom widget that adds a footer to a received scrollable widget?

From Dev

How to make a countdown?

From Dev

How to make countdown with time()

From Dev

Flutter How to make a Text widget in a Wrap widget start from the end of the previous widget and not start bellow the previous widget?

From Dev

Best practice to report errors in Flutter

From Dev

Flutter Firestore Logical OR best practice

From Dev

How to make system calls cross-platform: maintainable and best practice

From Dev

Best practice for building a make file

From Dev

Best practice for calling two different endpoints for a widget?

From Dev

Flutter. How to make a child widget go beyond it's parent?

From Dev

How to make an image provider from an Icon in flutter for FadeInImage widget?

Related Related

  1. 1

    How to make a countdown in flutter?

  2. 2

    how the best practice for to create dynamic content of SimpleDialog widget in flutter?

  3. 3

    Initialize final variable in Flutter widget - best practice

  4. 4

    Flutter - Create a countdown widget

  5. 5

    How to Make Widget Flutter Fast?

  6. 6

    How to make a spinning circle animation during a countdown in flutter?

  7. 7

    How to make a widget flexible on different screens in Flutter?

  8. 8

    flutter: how to make reusable gridView widget

  9. 9

    Flutter how to make a selectable / focusable widget

  10. 10

    How to make copyable Text Widget in Flutter?

  11. 11

    How to make custom widget/component in flutter?

  12. 12

    How to make a widget that is constantly growing and shrinking in Flutter?

  13. 13

    how to make one widget as master in flutter

  14. 14

    How can make an expand/collapse widget in flutter?

  15. 15

    how can I make this stack widget in flutter?

  16. 16

    how to make similar widget list with addition Flutter

  17. 17

    How to make the design using widget in Flutter

  18. 18

    make reverse countdown timer in flutter

  19. 19

    Flutter - How to make a custom widget that adds a footer to a received scrollable widget?

  20. 20

    How to make a countdown?

  21. 21

    How to make countdown with time()

  22. 22

    Flutter How to make a Text widget in a Wrap widget start from the end of the previous widget and not start bellow the previous widget?

  23. 23

    Best practice to report errors in Flutter

  24. 24

    Flutter Firestore Logical OR best practice

  25. 25

    How to make system calls cross-platform: maintainable and best practice

  26. 26

    Best practice for building a make file

  27. 27

    Best practice for calling two different endpoints for a widget?

  28. 28

    Flutter. How to make a child widget go beyond it's parent?

  29. 29

    How to make an image provider from an Icon in flutter for FadeInImage widget?

HotTag

Archive