Open In App

How to Run Code After Some Delay in Flutter?

Last Updated : 05 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is an open-source UI toolkit developed and maintained by Google. It is used by big companies like Airbnb, Alibaba, and Google itself to serve billions of users around the globe. In this article, we will see how we can delay our code execution using Timer in Flutter. A sample video is given below to get an idea about what we are going to do in this article.

Approach

We will create a periodic timer using the Timer class and cancel the timer once it reaches the desired ticks and then we execute our code.

Syntax

Timer.periodic(const Duration(seconds: 1), (timer) {
    // Check if the tick number is 5
    if (timer.tick == 5) {
        timer.cancel();
        // Code to Run
    }
});

Implementation

This example illustrates how to delay code execution using the Timer. Here we change the background color of the screen to 3 seconds after the click of the button.

Dart




import 'package:flutter/material.dart';
import 'dart:async';
  
void main() => runApp(const MyApp());
  
class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            title: 'GFG Timer Example',
            home: Scaffold(
                appBar: AppBar(
                    backgroundColor: Colors.green,
                    title: const Text('GeeksforGeeks - Timer Example'),
                ),
                body: const TimerDemo(),
            ),
        );
    }
}
  
class TimerDemo extends StatefulWidget {
    const TimerDemo({Key? key}) : super(key: key);
  
    @override
    State<TimerDemo> createState() => _TimerDemoState();
}
  
class _TimerDemoState extends State<TimerDemo> {
    Color _bgColor = Colors.green.shade50;
    @override
    Widget build(BuildContext context) {
        return Container(
            color: _bgColor,
            child: Center(
                child: ElevatedButton(
                    onPressed: () {
                        changeBg();
                    },
                    child: const Text("Change the background after 3 Seconds."),
                ),
            ),
        );
    }
  
    void changeBg() {
        Timer.periodic(const Duration(seconds: 1), (timer) {
            if (timer.tick == 3) {
                timer.cancel();
                setState(() {
                    _bgColor = Colors.red.shade300;
                });
            }
        });
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads