如何在颤振的一些延迟后运行代码?

我想在我的小部件构建后,在一定的延迟后执行一个函数。颤振的惯用方法是什么?

我想要达到的目标: 我想从默认的FlutterLogo小部件开始,然后在一段时间后更改其style属性。< / p >
300816 次浏览

算出来了😎

class AnimatedFlutterLogo extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}


class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
Timer _timer;
FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;


_AnimatedFlutterLogoState() {
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
_logoStyle = FlutterLogoStyle.horizontal;
});
});
}


@override
void dispose() {
super.dispose();
_timer.cancel();
}


@override
Widget build(BuildContext context) {
return new FlutterLogo(
size: 200.0,
textColor: Palette.white,
style: _logoStyle,
);
}
}

你可以在一段时间后使用Future.delayed来运行你的代码。例如:

Future.delayed(const Duration(milliseconds: 500), () {


// Here you can write your code


setState(() {
// Here you can write your code for open new view
});


});

在setState函数中,你可以编写与应用程序UI相关的代码,例如刷新屏幕数据,更改标签文本等。

只是在上面的答案上增加了更多的描述

计时器功能也适用于以下持续时间:

const Duration(
{int days = 0,
int hours = 0,
int minutes = 0,
int seconds = 0,
int milliseconds = 0,
int microseconds = 0})

例子:

  Timer(Duration(seconds: 3), () {
print("print after every 3 seconds");
});

倒计时后触发动作

Timer(Duration(seconds: 3), () {
print("Yeah, this line is printed after 3 seconds");
});

重复的行为

Timer.periodic(Duration(seconds: 5), (timer) {
print(DateTime.now());
});

立即触发定时器

Timer(Duration(seconds: 0), () {
print("Yeah, this line is printed immediately");
});
import 'dart:async';
Timer timer;


void autoPress(){
timer = new Timer(const Duration(seconds:2),(){
print("This line will print after two seconds");
});
}


autoPress();

Future.delayed(Duration(seconds: 3) , your_function)

(在老q上添加响应,因为这是谷歌上的顶部结果)

我尝试在一个集团内的回调中产生一个新的状态,它没有工作。try with Timer和Future.delayed。

然而,奏效的是……

await Future.delayed(const Duration(milliseconds: 500));


yield newState;

等待一个空的未来,然后运行该函数。

Synchronously

Future.delayed(Duration(milliseconds: 1000), () {
// Your code
});

Asynchronously

await Future.delayed(const Duration(milliseconds: 1000));

这里只留下大家都在寻找的片段:

Future.delayed(Duration(milliseconds: 100), () {
// Do something
});

一个快速的方法是使用Future.delayed,如下所示:

Future.delayed(Duration(seconds: 10), (){
print("Wait for 10 seconds");
});

或者你可以像这样将持续时间更改为milliseconds:

Future.delayed(Duration(milliseconds: 3000), () {
print("Wait for 3000 milliseconds");
});