我想运行一个带有一些随机/动态延迟的函数。Future.delayed可以提供帮助,但这需要时间const。我无法将表达式或非const值作为时间传递。有什么方法可以使其参数化或随机吗?所以每次调用的延迟都会不同。
Future.delayed(const Duration(milliseconds: needRandomNumberHere), () {
// code will be here
});
Run Code Online (Sandbox Code Playgroud)
您可以使用任何变量,就像其他人在这里所示的那样。
您在这方面误解了const。
没有办法强制使用 constDart - 它始终是可选的。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
});
Run Code Online (Sandbox Code Playgroud)
如您所知,const这是可选的。
这意味着以下内容可以正常工作:
Future.delayed(Duration(milliseconds: Random().nextInt(420)), () {
// code will be here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1255 次 |
| 最近记录: |