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

南楼画角 提交于 2021-02-07 23:46:26

问题


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?


回答1:


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';

void main() {
  var myString = 'myString';
  var stringBytes = utf8.encode(myString);
  var gzipBytes = GZipEncoder().encode(stringBytes);
  var compressedString = base64.encode(gzipBytes);

  print(compressedString);
}


来源:https://stackoverflow.com/questions/39735145/how-to-compress-a-string-using-gzip-or-similar-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!