How to Execute Code on Loop With Time Interval

In this example, we are going to show you the way to execute or call code, functions on loop with time interval. For example, you want to call some function every 5 seconds, then see the example below to learn how to set Time Interval in Flutter App.

To Use Timer, import the following dart library:

import 'dart:async';

Run Code on Every 5 Seconds:

Timer mytimer = Timer.periodic(Duration(seconds: 5), (timer) {
  //code to run on every 5 seconds
});

Run Code on Every 2 minutes 5 seconds:

Timer mytimer = Timer.periodic(Duration(minutes:2, seconds: 5), (timer) {
  //code to run on every 2 minutes 5 seconds
});

Run Code on Every 2 Hours and 30 Minutes:

Timer mytimer = Timer.periodic(Duration(hours:2, minutes: 30), (timer) {
  //cde to run on every 2 hours and 30 minutes
});

To Cancel or Terminate Timer:

Timer mytimer = Timer.periodic(Duration(seconds: 5), (timer) {
  //code to run on every 5 seconds
});

mytimer.cancel(); //to end timer

You can add more attributes to Duration() widget such as day, hours, minutes, seconds, microseconds, milliseconds. 

See the example below to show current Time:

import 'dart:async';
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String time = "";

   @override
  void initState() {
     Timer mytimer = Timer.periodic(Duration(seconds: 1), (timer) {
        DateTime timenow = DateTime.now();  //get current date and time
        time = timenow.hour.toString() + ":" + timenow.minute.toString() + ":" + timenow.second.toString(); 
        setState(() {
          
        });
        //mytimer.cancel() //to terminate this timer
     });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold(
        appBar: AppBar(
            title:Text("Execute Code With Timer"),
            backgroundColor: Colors.redAccent,
        ),
        body: Container(
          height: 260,
          color: Colors.red.shade50,
          child: Center(
            child: Text(time, style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),),
            //show time on UI
          )
        )
      )
    );
  }
}

Output Screenshot:

In this way, you can set time intervals using Timer in Flutter to execute code on loop.

No any Comments on this Article


Please Wait...