Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

Compress Text Feed to Binary

See more Compression Examples

This example receives incoming text data in chunks, compresses as a stream, and accumulates the compressed binary data.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final bdCompressed = CkBinData();

  final compress = CkCompression();
  compress.algorithm = 'deflate';
  compress.charset = 'utf-8';

  final sbUncompressedChunk = CkStringBuilder();

  compress.firstChunk = true;
  compress.lastChunk = false;

  for (var i = 0; i <= 24; i++) {
    if (i == 24) {
      compress.lastChunk = true;
    }

    sbUncompressedChunk.clear();
    sbUncompressedChunk.appendInt(i);
    sbUncompressedChunk.append(': This is a line of data to be compressed...\r\n');

    compress.compressSb(sbUncompressedChunk, bdCompressed);

    compress.firstChunk = false;
  }

  // Show the compressed data in hex format:
  print('The hex encoded compressed text:');
  print(bdCompressed.getEncoded('hex'));

  // Now decompress in one call.  It is important to set both FirstChunk and LastChunk = true
  final bdDecompressed = CkBinData();
  compress.firstChunk = true;
  compress.lastChunk = true;
  try {
    compress.decompressBd2(bdCompressed, bdDecompressed);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final originalText = bdDecompressed.getString('utf-8');
  print(originalText);
}