是否总是在Flutter中的build()方法之后调用initState()方法中的异步函数调用?

时间:2020-01-08 05:00:55

标签: asynchronous flutter dart async-await

下面有一个测试代码:

class SplashPageState extends State<SplashPage> {
  Future<void> dummy() async {
      print('Async function1');
      Future.delayed(Duration.zero, () => print('Async function2'));
      print('Async function3');
      await Future.delayed(Duration.zero, () => print('Async function4'));
      print('Async function5');
  }

  @override
  void initState() {
    print('initState 1');
    super.initState();
    print('initState 2');
    Future.sync(() {
      print('Future sync');

    });
    print('initState 3');
    Future.delayed(Duration.zero, () {
      print('Future value');
    });
    print('initState 4');
    dummy();
    print('initState 5');
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      appBar: AppBar(
        title: Text('1'),
      ),
      body: Text('2'),
    );
  }
}

结果:

I/flutter (16218): initState 1
I/flutter (16218): initState 2
I/flutter (16218): Future sync
I/flutter (16218): initState 3
I/flutter (16218): initState 4
I/flutter (16218): Async function1
I/flutter (16218): Async function3
I/flutter (16218): initState 5
I/flutter (16218): build
I/flutter (16218): Future value
I/flutter (16218): Async function2
I/flutter (16218): Async function4
I/flutter (16218): Async function5

我对其进行了100次测试,并且每次构建的顺序都相同。由于异步编程,我想知道“此命令是否始终保持每次运行?”

1 个答案:

答案 0 :(得分:0)

Flutter还是我应该说Dart是单线程编程,它可以在事件循环机制中工作。 因此,每次dart看到不带await关键字的异步功能时,它就会自动进入并将其置于事件循环中,并且在所有当前进程完成后,它将返回并恢复该异步功能。如果您在print('Async function5');中像以前一样有await关键字,它将检查事件循环并按延迟顺序恢复先前添加的事件堆栈。

Check for more details

您可以在其中找到有关其工作方式的所有详细信息。另外,别忘了观看这些视频

Flutter dev video and how Isolates introduced