[Flutter] 填坑:await、forEach、Image.file三者结合的奇妙巨坑

问题是这样出现的,一个实时聊天app,在性能较差的手机上,一次性发送多张图片,Image.file组件加载居然有明显的延迟!

具体表现为先出现一个空白区域,然后图片才会在空白区域慢慢渲染出来

而且我寻遍百度谷歌都没有人遇到相同的问题,难道这个bug只有我遇到了?

首先来看下面两段代码:

分别在forEach循环和for循环中执行await会有什么区别呢?

代码1(forEach):

import 'dart:async';
import 'dart:io';

void main() async {
  Completer<int> completer;
  print('main begin');
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((element) async {
    var t = await test(element);
    print('t:$t,index:$element');
  });
  print('main end');
}

Future<int> test(int i) async {
  print('test-$i begin');
  await sleep(Duration(seconds: 1));
  print('test-$i end');
  return 1;
} 

输出:

main begin
test-1 begin
test-2 begin
test-3 begin
test-4 begin
test-5 begin
test-6 begin
test-7 begin
test-8 begin
test-9 begin
test-10 begin
main end
test-1 end
t:1,index:1
test-2 end
t:1,index:2
test-3 end
t:1,index:3
test-4 end
t:1,index:4
test-5 end
t:1,index:5
test-6 end
t:1,index:6
test-7 end
t:1,index:7
test-8 end
t:1,index:8
test-9 end
t:1,index:9
test-10 end
t:1,index:10 

代码2(for):

import 'dart:async';
import 'dart:io';

void main() async {
  Completer<int> completer;
  print('main 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值