How to run code after some delay in Flutter?

239,371

Solution 1

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,
    );
  }
}

Solution 2

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.

Solution 3

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");
});

Solution 4

Just leaving here the snippet everyone is looking for:

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

Solution 5

(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.

Share:
239,371

Related videos on Youtube

Bradley Campbell
Author by

Bradley Campbell

Updated on April 14, 2022

Comments

  • Bradley Campbell
    Bradley Campbell about 2 years

    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.

  • Lucem
    Lucem almost 6 years
    where did you import Timer from?
  • Lucem
    Lucem almost 6 years
    got it import 'dart:async'
  • stevenspiel
    stevenspiel about 5 years
    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.
  • Andris
    Andris almost 4 years
    I don't t think this should be accepted answer, cause it not just runs code after delay, but also repeats code. @Rahul Sharma solution just for delay is much better.
  • Bradley Campbell
    Bradley Campbell almost 4 years
    Rahul's answer doesn't cancel the timer, so surely if your widget goes away you have a leak? (Note: I am not a flutter developer, I used this once a couple years ago!)
  • Banana
    Banana almost 4 years
    @BradleyCampbell Rahul's answer doesn't have a timer. It's a function which runs once after the delay.
  • Bradley Campbell
    Bradley Campbell almost 4 years
    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
  • Abhishek Thapliyal
    Abhishek Thapliyal over 3 years
    duration can be added: Duration(seconds: 3) for new bee
  • Tom
    Tom over 3 years
    To avoid a warning check that your widget is still mounted before calling setState
  • chethanv77777
    chethanv77777 about 3 years
    short and perfect
  • VegetaSaiyan
    VegetaSaiyan almost 3 years
    hey Jai, by any chance, you know how to solve this? stackoverflow.com/questions/68324422/…
  • VegetaSaiyan
    VegetaSaiyan almost 3 years
    hey Armands, by any chance you know how to solve this? stackoverflow.com/questions/68324422/…
  • VegetaSaiyan
    VegetaSaiyan almost 3 years
    hey Paresh, by any chance you know how to solve this? stackoverflow.com/questions/68324422/…
  • VegetaSaiyan
    VegetaSaiyan almost 3 years
    hey Jitesh, by any chance you know how to solve this? stackoverflow.com/questions/68324422/…
  • Gicu Mironica
    Gicu Mironica over 2 years
    this should be the accepted solution
  • Luis_RH
    Luis_RH over 2 years
    I don't think this should be the accepted answer since the code keeps repeating until the widget is disposed, the solution should execute the code after the delay only once.
  • Bradley Campbell
    Bradley Campbell over 2 years
  • heyom
    heyom over 2 years
    And how do you stop the timer from different class?
  • gruvw
    gruvw about 2 years
    This has the advantage over Future.delayed in that it can be canceled if stored in a variable!