美文网首页
关于 Flutter for循环中使用await无效的问题

关于 Flutter for循环中使用await无效的问题

作者: 天上飘的是浮云 | 来源:发表于2022-04-18 10:39 被阅读0次

之前也碰到过,在Flutter中for循环中用wait并不生效,外层并不会等待所有for循环中wait事件,貌似找到过方案,后面也没记录,时间久了又忘了,这次记录下。给你,给我留下印记~

一、错误示范

一开始我用的items.forEach来进行for循环,并在里面使用wait关键值阻塞,外部调用也是用了wait关键字,但是外部的wait并不起作用,不会等待里面for循环wait全部执行完再做操作。
如下代码

  void onUploadImages() async {
    await onStoreAndUploadImages();
    NavigatorUtil.pop(context,true);
  }
  
  Future<void> onStoreAndUploadImages() async {
    List<int> items = _itemRotateQuarterTurns.keys.toList();
    //并不会等待所有的子项都执行完
    items.forEach((element) async { 
      await generateAndStoreImage(element);
    });
  }

二、正确示范

后面将forEach改为for循环就解决了,置于为什么还没去查证,后期有时间将会查证下,更新在本文中~

  Future<void> onStoreAndUploadImages() async {
    List<int> items = _itemRotateQuarterTurns.keys.toList();
    for(int i = 0; i < items.length; i++){
      await generateAndStoreImage(i);
    }
  }

相关文章

网友评论

      本文标题:关于 Flutter for循环中使用await无效的问题

      本文链接:https://www.haomeiwen.com/subject/xoxdertx.html