Why does this function block flutter's ui?

Viewed 315

FLUTTER: WEB

Hello I would like when I click on a button that the function bellow is executed in a non-blocking way and it does not freeze the ui, the problem is by wrapping it in a Future, it freezes the ui, and I even used async_task but it does not work...

List<int> _compressFiles(List<Uint8List> data) {
   BZip2Encoder zec = BZip2Encoder();
   Archive archive = new Archive();
   for (var i = 0; i < data.length; i++) {
     archive.addFile(ArchiveFile(i.toString(), data[i].elementSizeInBytes, data[i]));
   }
   List<int> tar_data = TarEncoder().encode(archive);
   List<int> tar_bz2 = BZip2Encoder().encode(tar_data);
   return tar_bz2;
}

(This code is using the archive lib https://pub.dev/packages/archive).

onPressed function:

onPressed: () { 
   //this freeze the ui for 3-4s
   List<Uint8List> l = [];
   for (var i in list) {
      l.add(i.image);
   }
   compressFiles(l).then(...);

}
2 Answers

You can try making your function async but there are chances that your UI might be stuck.

How it works is there is an eventloop which loops through eventqueue and microtask queue to check if something is there to process. If there is it will process it while the application is waiting. This can cause the UI to not respond when some function hasn't returned from completion.

In your scenario, as it involves compression and encoding, you should use 3rd party plugin or use isolates to load off the task from main isolate.

declare your function with the async keyword.

Future<List<int>> _compressFiles(List<Uint8List> data) async{}
Related