compressText static method

  1. @useResult
String? compressText(
  1. String? value
)

Compresses a string using gzip and encodes it as Base64.

This method first encodes the input string to UTF-8, then compresses it using gzip, and finally encodes the compressed bytes as a Base64 string.

Returns null if:

  • The input value is empty
  • Gzip is unavailable on the current platform (e.g., web)
  • An error occurs during compression

Example:

final compressed = Base64Utils.compressText('Hello, World!');
// compressed is a Base64-encoded gzipped string

See also:

  • decompressText to reverse this operation

Implementation

@useResult
static String? compressText(String? value) {
  if (value == null || value.isEmpty) {
    return null;
  }

  try {
    final List<int> encodedJson = utf8.encode(value);
    final List<int>? gzipJson = gzipEncode(encodedJson);
    if (gzipJson == null) {
      return null;
    }

    return base64.encode(gzipJson);
  } on FormatException catch (e, stackTrace) {
    // debugPrint is appropriate for utility packages (stripped in release builds, no external dependencies)
    // ignore: saropa_lints/avoid_print_error -- intentional diagnostic logging via debugPrint (stripped in release)
    debugPrint('Base64Utils.compressText failed: $e\n$stackTrace');

    return null;
  }
}