Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code after some random/dynamic delay in Flutter?

Tags:

flutter

dart

I would like to run a function with some random/dynamic delay. Future.delayed can help in this but it took time as const. I am unable to pass an expression or non const value as time. Is there any way to make it parameterise or random? So with each call delay will be different.

Future.delayed(const Duration(milliseconds: needRandomNumberHere), () {
    // code will be here
});
like image 233
Pankaj Anupam Avatar asked Dec 17 '25 19:12

Pankaj Anupam


1 Answers

You can just use any variable, like others have shown here.

You are misunderstanding the const in this context.
There is no way to force const in Dart - it is always optional. You can only force yourself to use const by declaring it that way.

Future.delayed(Duration(milliseconds: 42), () {
    // code will be here
});
// does the exact same as:
Future.delayed(const Duration(milliseconds: 42), () {
    // code will be here
});

As you can tell, const is optional.

This means that the following will just work fine:

Future.delayed(Duration(milliseconds: Random().nextInt(420)), () {
    // code will be here
});
like image 103
creativecreatorormaybenot Avatar answered Dec 20 '25 10:12

creativecreatorormaybenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!