Jop V. Jop V. - 2 months ago 7
Dart Question

How to compress a string using GZip or similar in Dart?

I want to compress a string in Dart (in the browser). I tried this:

import 'package:archive/archive.dart';

[...]

List<int> stringBytes = UTF8.encode(myString);
List<int> gzipBytes = new GZipEncoder().encode(stringBytes);
String compressedString = UTF8.decode(gzipBytes, allowMalformed: true);


Obviously
UTF8.decode
is not intended for this and it doesn't work (file is unreadable).

What is the right way to compress a string in Dart?

Answer

The compressed list of bytes is probably not a valid UTF8 sequence instead you could encode it in base64.

import 'dart:convert';
import 'package:archive/archive.dart';

main() {
  String myString = 'myString';
  List<int> stringBytes = UTF8.encode(myString);
  List<int> gzipBytes = new GZipEncoder().encode(stringBytes);
  String compressedString = BASE64.encode(gzipBytes);

  print(compressedString);
}
Comments