Manohara321
Manohara321

Reputation: 23

How do I implement a timer to execute code after a certain delay?

I am a new developer using Flutter. After reading Flutter docs and Stackoverflow, I cannot resolve my problem. I have trying to write code that displays a screen then waits 2 seconds before executing a print statement. What am I missing? Thanks in advance for your help.

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Timer timer;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFF5C894E),
      body: Column(
        children: [
          Container(
            alignment: Alignment.center,
            child: Image(
              image: AssetImage('images/Mezzo_Welcome_Screen.png'),
            ),
          ),
        ],
      ),
    );
  }

  void timeDelay() {
    timer = new Timer(const Duration(seconds: 2), () {
      print("This line will print after two seconds");
    });
    timeDelay();
    timer.cancel();
  }
}

Upvotes: 1

Views: 1316

Answers (3)

Jitesh Mohite
Jitesh Mohite

Reputation: 34180

There are two ways to do that

  1. Timer
  2. Future

Timer

Timer(Duration(seconds: 2), () {
  print("Execute this code afer 2 seconds");
});

Future:

Future.delayed(Duration(seconds: 2), () {
   print("Execute this code afer 2 seconds");
});

So, What is the difference between the above two approaches?

With Timer

The timer runs its job after the given duration, but flutter not waiting for it to complete its execution, it performs below statements.

Example:

Timer(Duration(seconds: 2), () {
      print("Execute this code afer 2 seconds");
    }); 
 print("Other code");

Output:

Other code
Execute this code after 2 seconds

So as you can see code below timer will execute first and then the timer will be performed. Also, Timer can be stopped at any given point before its execution, if we crate the object of it.

 Timer timer = Timer(Duration(seconds: 2), () {
          print("Execute this code afer 2 seconds");
        }); 
timer.cancel();

With Future

The future also runs its job after the given duration, but its return future object means we can use await to get its execution first, and then below statements will be going to execute.

 await Future.delayed(Duration(seconds: 2), () {
          print("Execute this code afer 2 seconds");
        });
        print("My Code");
    print("Other code");

Output:

Execute this code after 2 seconds
Other code

The main disadvantage of the future is that we can't cancel it in between.

Upvotes: 2

Alex Radzishevsky
Alex Radzishevsky

Reputation: 3768

Though overall use case is still not clear from your question/description, I think there is no need to use timer. Use delayed future instead, like this:

class _HomeScreenState extends State<HomeScreen> {

...

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 2)).then((_) => action());
  }

  void action() {
    print("executing action ...");
  }
...

}

Upvotes: 0

Balasubramani Sundaram
Balasubramani Sundaram

Reputation: 1290

Use the timer, to the periodic operation. Refer the code snippet.

Initialise once in lifetime of the app, place you code inside the initState()

import 'dart:async';


  Timer timer;
  
  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(const Duration(seconds: 2), (timer) { 
      action();
    });
  }
  
  void action(){
    
  }

Upvotes: 0

Related Questions