如何 运行 在 Flutter 延迟一段时间后编码?

How to run code after some delay in Flutter?

我想在我的 Widget 构建后的一定延迟后执行一个函数。在 Flutter 中执行此操作的惯用方式是什么?

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

想通了

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函数中,您可以写一段与app相关的代码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");
  });

Trigger actions after countdown

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

Repeat actions

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

Trigger timer immediately

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 的响应,因为这是 google 上的最高结果)

我尝试在一个 bloc 中的回调中生成一个新状态,但没有成功。尝试使用计时器和 Future.delayed.

然而,起作用的是...

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

yield newState;

等待一个空的 future 然后 运行 之后的函数。

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");
});