How to run code after some delay in Flutter?

前端 未结 10 1512
無奈伤痛
無奈伤痛 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条回答
  • Future.delayed(Duration(seconds: 3) , your_function)

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

    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.

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

    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");
      });
    
    0 讨论(0)
  • 2020-12-23 01:02

    You can do it in two ways 1 is Future.delayed and 2 is Timer

    Using Timer

    Timer is a class that represents a count-down timer that is configured to trigger an action once end of time is reached, and it can fire once or repeatedly.

    Make sure to import dart:async package to start of program to use Timer

    Timer(Duration(seconds: 5), () {
      print(" This line is execute after 5 seconds");
    });
    

    Using Future.delayed

    Future.delayed is creates a future that runs its computation after a delay.

    Make sure to import "dart:async"; package to start of program to use Future.delayed

    Future.delayed(Duration(seconds: 5), () {
       print(" This line is execute after 5 seconds");
    });
    
    0 讨论(0)
提交回复
热议问题