Run Code After Some Delay in Flutter?

Haris Bin Nasir Avatar

·

·

In this article, we’ll look at how to run code in flutter after a delay. I’ve compiled a list of all viable solutions to this problem. Sometimes, it’s very important in app development to execute code after some time. Hopefully, this article will help you solve that problem.

I’ll provide you all of the options for resolving this problem. Let’s get right to the point of this post.

How do you run code after a delay in Flutter?

There are two ways to go about it. Future.delayed is number one, and Timer is number two. We can use Future.delayed to run your function after a certain amount of time has passed. Future.delayed(const Duration(milliseconds: 500).

Using Future.delayed Function.

Delay code in Flutter using Future.delayed by 500 milliseconds.

Copied!
Future.delayed(const Duration(milliseconds: 500), () { //Code Here });

Creates a future that performs its calculation once a certain amount of time has passed.

After the specified time has elapsed, the computation will be carried out, and the future will be completed with the outcome of the computation.

If computation produces a future, this constructor’s future will be filled in with the value or error of that future.

Using Timer Object.

Copied!
Timer(Duration(seconds: 3), () { print(":) is printed after 3 seconds"); });
Copied!
Timer.periodic(Duration(seconds: 5), (timer) { print(DateTime.now()); });
Copied!
Timer(Duration(seconds: 0), () { print(":) is printed immediately"); });

A countdown timer that may be set to fire only once or several times.

The timer starts at the set duration and ticks down to zero. When the timer hits zero, the provided callback function is invoked. Use a periodic timer to count down the same interval over and over.

Negative durations are handled the same as zero durations. Consider using run if the duration is known to be zero.

Conclusion

I hope this article aids you in resolving your problem regarding running code after delay in Flutter. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *