Timer Widget

Introduction of Timer Widget

In Flutter, there isn’t a specific Timer widget, but there is a Dart class named Timer that is commonly used for scheduling future or periodic tasks. The Timer class is part of the Dart dart:async library and is often used in Flutter applications to execute code after a specified duration or at regular intervals.

Here’s a short explanation of some of the key properties:

Timer(Duration duration, void Function(Timer timer) callback) Constructor: Creates a new timer that calls the specified callback after the given duration.

Timer(Duration(seconds: 2), () {
  // Code to execute after 2 seconds
});

Timer.periodic(Duration duration, void Function(Timer timer) callback) Constructor: Creates a periodic timer that repeatedly calls the specified callback with a fixed time interval.

Timer.periodic(Duration(seconds: 1), (Timer timer) {
  // Code to execute every 1 second
});

cancel() Method: Cancels the timer, stopping it from further execution.

Timer timer = Timer(Duration(seconds: 2), () {
  // Code to execute after 2 seconds
});

// Later, cancel the timer
timer.cancel();

Usage: Here’s an example of using the Timer class to execute code after a specific duration:

import 'dart:async';

void main() {
  print('Start');

  Timer(Duration(seconds: 2), () {
    print('Callback executed after 2 seconds');
  });

  print('End');
}

In this example, “Start” is printed, then the timer is set for 2 seconds, and “End” is printed immediately after. After 2 seconds, the callback is executed, printing “Callback executed after 2 seconds.”

Final Code: This is the final code with some of the above Timer Widget properties.

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

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int timeLeft = 5;

  void _startCountDown() {
    Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (timeLeft > 0) {
          timeLeft--;
        } else {
          timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              timeLeft == 0 ? 'Done' : timeLeft.toString(),
              style: TextStyle(fontSize: 70),
            ),
            MaterialButton(
              color: Colors.teal,
              height: 60,
              minWidth: 190,
              onPressed: _startCountDown,
              child: Text(
                'S T A R T',
                style: TextStyle(
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Keep in mind that Flutter applications typically use asynchronous programming and the Future class for handling delayed tasks, but the Timer Widget class can be useful for specific timing scenarios.

Thank for visiting Hybrid App Development
Posted by Hussam HM

Premium Partner

WordPress Wallah offer's premium WordPress themes, plugins, and Template Kits free.

Details