riciloma
riciloma

Reputation: 1836

How can I create a zip file from a Json in Dart?

I've downloaded the Dart archive package, but the documentation is kinda empty. I've got an object that I need to serialize in a File format, and compress it in a zip.

This is what I've managed to write so far, but it doesn't work.

  static Future<List<int>> convertMeetingsListToZip(List<Meeting> list) async {
    return File('meetings.zip')
        .writeAsString(jsonEncode(list))
        .then((File encodedFile) {
      Archive archive = new Archive();
      archive.addFile(new ArchiveFile(
          encodedFile.path, encodedFile.lengthSync(), encodedFile));
      return ZipEncoder().encode(archive);
    });
  }

Could you please help me out?

Upvotes: 0

Views: 830

Answers (1)

riciloma
riciloma

Reputation: 1836

Nevermind, I made it. Here's how:

static List<int> convertListToZip(List<dynamic> list) {
   String jsonEncoded = jsonEncode(list);
   List<int> utf8encoded = utf8.encode(jsonEncoded);
   ArchiveFile jsonFile =
       new ArchiveFile("filename.json", utf8encoded.length, utf8encoded);
   Archive zipArchive = new Archive();
   zipArchive.addFile(jsonFile);
   List<int> zipInBytes = new ZipEncoder().encode(zipArchive);
   return zipInBytes;
}

The gist was to encode the file in bytes (with utf8.encode) before wrapping it in an archive and encode it.

Upvotes: 1

Related Questions