dart:await的执行机制:暂停当前函数,但不阻塞线程

一,代码:

  //每1秒打印一下当前数字
  void tick10() async {
    for (int i = 1; i <= 10; i++) {
      await Future.delayed(Duration(seconds: 1),(){
        print("tick"+i.toString());
      });
    }
  }


  void myclick() async{
    tick10();
    print("a");
    //await tells dart to wait till this completes.
    // If it's not used before a future,
    // then dart doesn't wait till the future is completed and executes the next tasks/code.
    await Future.delayed(Duration(seconds:
    5),(){
      print("await返回b");
    });
    print("c");
  }

二,执行结果:

I/flutter (17391): a
I/flutter (17391): tick1
I/flutter (17391): tick2
I/flutter (17391): tick3
I/flutter (17391): tick4
I/flutter (17391): await返回b
I/flutter (17391): c
I/flutter (17391): tick5
I/flutter (17391): tick6
I/flutter (17391): tick7
I/flutter (17391): tick8
I/flutter (17391): tick9
I/flutter (17391): tick10

 

posted @ 2026-03-08 10:44  刘宏缔的架构森林  阅读(1)  评论(0)    收藏  举报