0

这在其他语言中很常见。 setTimeout(fn, 0)在 JavaScript 和DispatchQueue.main.async() {}Swift 中。

如何最好地在 Flutter 中做到这一点?

我用过Future.delayed(Duration.zero).then(fn),但我不喜欢它,因为像 JSsetTimeout和 swifts 不同DispatchQueue.main.async() {},它并没有真正表达意图,只有行为。有没有办法做到这一点,这是在 Flutter 中做到这一点的正确方法。

4

2 回答 2

2

利用addPostFrameCallback

WidgetsBinding.instance
          .addPostFrameCallback((timestamp) {
        print("I'm running after the frame was built");
    });

这将导致您的回调函数在颤振完成当前帧构建后立即运行。

请注意,回调只会运行一次,如果您想为每个构建重新安排它,请在构建函数的开头设置回调。

@override
Widget build(BuildContext context) {
    WidgetsBinding.instance
          .addPostFrameCallback((timestamp) {
        print("I'm running after the frame was built");
    });

    return Container();
}
于 2021-01-21T16:13:19.527 回答
2

您也可以使用Timerfrom flutter。例子

Timer(Duration(seconds: 1), () {
      print('hai');
});

Duration为您提供选项seconds,milliseconds,days,hours,minutes

您也setInterval可以使用Timer

Timer.periodic(Duration(seconds: 1), (Timer timer) {
      print('hai');
});

但请记住,cancel打开计时器dispose。这样可以避免你打到记忆中

Timer timer;
timer = Timer(Duration(seconds: 1), () {
      print('hai');
});

void dispose() {
 timer.cancel();
}
于 2021-01-21T16:13:29.240 回答