如何在Flutter中经过一些随机/动态延迟后运行代码



我想运行一个具有一些随机/动态延迟的函数。CCD_ 1在这方面可以起到帮助作用,但它与CCD_ 2一样需要时间。我无法将表达式或非const值作为时间传递。有什么方法可以使它参数化或随机化吗?因此,每次通话的延迟都会有所不同。

Future.delayed(const Duration(milliseconds: needRandomNumberHere), () {
// code will be here
});

您可以使用任何变量,就像这里显示的其他变量一样。

在这种情况下,您误解了const
在飞镖中没有强制const方式-它始终是可选的。您只能通过声明const来强制自己使用它。

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

正如您所知,const是可选的。

这意味着以下操作会很好:

Future.delayed(Duration(milliseconds: Random().nextInt(420)), () {
// code will be here
});

使用Dart的随机类:

int nextInt(int max(

生成一个非负随机整数,均匀分布在从0(包括0(到max(不包括0(的范围内。

因此,在您的代码中:

import 'dart:math';
Future.delayed(Duration(milliseconds: Random().nextInt(3000)), () {
// code will be here
});

将在0到3000毫秒之间的随机时间后运行代码。

您可以这样使用它:

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) {

}
}
},
);

}

请看一看如何在dart中生成随机数。您可以做的是生成一个随机数,然后将其传递给milliseconds字段,甚至是Future.delayed0中的seconds

最新更新