簡體   English   中英

為什么在等待 flutter 中的等待 function 之前調用語句

[英]why statement is getting called before await function in flutter

我創建了一個用於學習異步和等待的演示

這里發生了在等待 function 之前執行了一條語句。

據我說

output 應該是A秒Z優先

但它的給予

output:AZ第二優先

這是我的編碼

class _MyHomePageState extends State<MyHomePage> {
  first() {
    Future.delayed(Duration(seconds: 10), () {
      print('first');
    });
  }

  second() {
    Future.delayed(Duration(seconds: 1), () {
      print('second');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Async demo'),
      ),
      body: Center(
        child: Container(
          color: Colors.white,
          child: TextButton(
            child: Text('Click Me'),
            onPressed: () async {
              print('A');
              first();
              await second();
              print('Z');
            },
          ),
        ),
      ),
    );
  }
}

您應該在first()second() function 中也使用異步等待Future.delayed()

像這樣使用。

    first() async  {
        await Future.delayed(Duration(seconds: 10), () {
          print('first');
        });
      }

    second() async   {
        await Future.delayed(Duration(seconds: 1), () {
      print('second');
    });
  }

此代碼運行良好。根據您的說法 output “A second Z First”

class HomePage extends StatelessWidget {
  first() async {
    await Future.delayed(Duration(seconds: 10), () {
      print('first');
    });
  }

  second() async {
    await Future.delayed(Duration(seconds: 1), () {
      print('second');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Async demo'),
      ),
      body: Center(
        child: Container(
          color: Colors.white,
          child: TextButton(
            child: Text('Click Me'),
            onPressed: () async {
              print('A');
              first();
              await second();
              print('Z');
            },
          ),
        ),
      ),
    );
  }
}

這是 output:

  Performing hot restart...
    Waiting for connection from debug service on Chrome...
    Restarted application in 397ms.
    A
    second
    Z
    first

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM