【问题标题】:Is that async function call in initState() method always be called after build() method in Flutter?是否总是在 Flutter 中的 build() 方法之后调用 initState() 方法中的异步函数调用?
【发布时间】:2020-01-08 05:00:55
【问题描述】:

我有一个测试代码如下:

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 次,每次构建的顺序始终相同。由于异步编程,我想知道“这个顺序是否总是保持每次运行?”

【问题讨论】:

    标签: asynchronous flutter dart async-await


    【解决方案1】:

    Flutter 或者我应该说 Dart 是单线程编程,它在事件循环机制中工作。 因此,每次 dart 看到没有 await 关键字的异步函数时,它都会将其放入事件循环中,并且在所有当前进程完成后,它会返回并恢复该异步函数。如果您之前在 print('Async function5'); 中使用了 await 关键字,它会检查事件循环并按顺序恢复之前的事件堆栈,它们是针对延迟添加的。

    Check for more details

    在那里你可以找到它如何工作的所有细节。另外,别忘了看看这个视频

    Flutter dev video and how Isolates introduced

    【讨论】:

    • 不错的答案。谢谢你的建议。
    猜你喜欢
    • 2020-07-15
    • 2018-05-15
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2021-07-07
    相关资源
    最近更新 更多