How to run code after some delay in Flutter?

前端 未结 10 1511
無奈伤痛
無奈伤痛 2020-12-23 00:24

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\'

相关标签:
10条回答
  • 2020-12-23 00:38

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

    0 讨论(0)
  • 2020-12-23 00:41

    Just leaving here the snippet everyone is looking for:

    Future.delayed(Duration(milliseconds: 100), () {
      // Do something
    });
    
    0 讨论(0)
  • 2020-12-23 00:47

    Figured it out

    0 讨论(0)
  • 2020-12-23 00:50

    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");
    });
    
    0 讨论(0)
  • 2020-12-23 00:51
    import 'dart:async';   
    Timer timer;
    
    void autoPress(){
      timer = new Timer(const Duration(seconds:2),(){
        print("This line will print after two seconds");
     });
    }
    
    autoPress();
    
    0 讨论(0)
  • 2020-12-23 00:53

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

    0 讨论(0)
提交回复
热议问题