330

I'd like to execute a function after a certain delay after my Widget is built. What's the idiomatic way of doing this in Flutter?

What I'm trying to achieve: I'd like to start with a default FlutterLogo Widget and then change its style property after some duration.

10 Answers 10

527

You can use Future.delayed to run your code after some time. e.g.:

Future.delayed(const Duration(milliseconds: 500), () {

// Here you can write your code

  setState(() {
    // Here you can write your code for open new view
  });

});

In setState function, you can write a code which is related to app UI e.g. refresh screen data, change label text, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

To avoid a warning check that your widget is still mounted before calling setState
148

To use Timer, Timer Class Documentation

import 'dart:async';

Trigger actions after countdown

Timer(Duration(seconds: 3), () {
  print("Yeah, this line is printed after 3 seconds");
});

Repeat actions

Timer.periodic(Duration(seconds: 5), (timer) {
  print(DateTime.now());
});

Trigger timer immediately

Timer(Duration(seconds: 0), () {
  print("Yeah, this line is printed immediately");
});

1 Comment

This has the advantage over Future.delayed in that it can be canceled if stored in a variable!
108

Just leaving here the snippet everyone is looking for:

Future.delayed(Duration(milliseconds: 100), () {
  // Do something
});

Comments

100

Figured it out 😎

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

4 Comments

where did you import Timer from?
got it import 'dart:async'
one modification would be to put timer = ... in the initState override. That way, you have access to widget which is set in the State<> constructor.
Yes, both APIs run a block of code after a delay. But the accepted answer here actually cancels the execution of that block of code should the widget disappear. This was to prevent memory leaks, but it might not be necessary! I'd need a flutter developer to check if the timer/future still executes after a widget is disposed
42

(Adding response on old q as this is the top result on google)

I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.

However, what did work was...

await Future.delayed(const Duration(milliseconds: 500));

yield newState;

Awaiting an empty future then running the function afterwards.

Comments

34

Synchronously

Future.delayed(Duration(milliseconds: 1000), () {
    // Your code
});

Asynchronously

await Future.delayed(const Duration(milliseconds: 1000));

1 Comment

this is not correct, both the Futures are Asynchronous operations.
19

A quick way is using Future.delayed as below:

Future.delayed(Duration(seconds: 10), (){
    print("Wait for 10 seconds");
});

or you can change duration to milliseconds like this:

Future.delayed(Duration(milliseconds: 3000), () {
        print("Wait for 3000 milliseconds");
});

Comments

14

Future.delayed(Duration(seconds: 3) , your_function)

Comments

13

Just adding more description over the above answers

The Timer functionality works with below duration time also:

const Duration(
      {int days = 0,
      int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliseconds = 0,
      int microseconds = 0})

Example:

  Timer(Duration(seconds: 3), () {
    print("print after every 3 seconds");
  });

Comments

6
import 'dart:async';   
Timer timer;

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

autoPress();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.