Baishun's Space

Flutter How To - extract zip file from bundle

By Baishun on Feb 25, 2024
flutter archive

Summary

Sometimes we need to add some zip files to our bundle and extract to application document directory when we need these datas of these files. Today we will talk about this.

Read Images In Assets

Let’s talk about what assets are for first.

For some images like icons or avatars, we love to put them in the assets folder and read it directory in our app just like this:

Image.asset('assets/images/loading-animation.gif')

And for a zip, we could also do the similar, but not very same, cause zip file could not be loaded directly, we need to use some plugins.

Note: to access files in assets folder, we need to give access from pubspec.yaml file

Unzip Zip From Assets

We need a plugin called archive

the code is pretty easy:

import 'package:archive/archive_io.dart';
import 'package:flutter/services.dart';

ByteData value = await rootBundle.load('assets/zip/zipfile.zip');
Uint8List wzzip =
    value.buffer.asUint8List(value.offsetInBytes, value.lengthInBytes);
InputStream ifs = InputStream(wzzip);
final archive = ZipDecoder().decodeBuffer(ifs);

await extractArchiveToDiskAsync(archive, offlineBiblePath);

Tips

  • do not add too much zip file to our bundle

  • if you check the manual of archive plugin, you will find there are different methods for different type of compressed files, like TarDecoder() is used to decode *.tar file and ZipDecoder() is used to decode *.zip file , so don’t mix them.

For business cooperation or you have any questions, please send email to : lecy.cc.app@gmail.com
© Copyright 2024 by Baishun Space. Built with ♥ by Lecy. Origin theme of this blog is from ixartz. Social Icons are copied from astro-social-share