Reputation: 580
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
});
Upvotes: 3
Views: 1444
Reputation: 421
You can use it like this:
Timer? timer;
void startTimerRandomly() {
var random = Random();
var randomDuration = Duration(seconds: random.nextInt(10));
timer?.cancel();
timer= Timer.periodic(
randomDuration,
(Timer timer) {
if (mounted) {
startTimerRandomly();
} else {
if (mounted) {
}
}
},
);
}
Upvotes: 1
Reputation: 126664
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
});
Upvotes: 5
Reputation: 3768
Use Dart's Random class:
int nextInt(int max)
Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.
So, in your code:
import 'dart:math';
Future.delayed(Duration(milliseconds: Random().nextInt(3000)), () {
// code will be here
});
will run the code after a random time between 0 and 3000 milliseconds.
Upvotes: 1