Unhandled Exception: FormatException: Unexpected extension byte (at offset 5)
Asked Answered
G

1

6

The Json response has an gzip encoded string.

 var dataList = [
    {"Data": "compressedata"},
    {"Data": "compressedData"}
  ];

I tried so many methods to decompress the string but could not get the expected results. The final way tried was

  List<int> res = base64.decode(base64.normalize(zipText));

  print(utf8.decode(res));

where zipText is the String from json, which throws error

Unhandled Exception: FormatException: Unexpected extension byte (at offset 5)

Another way

  Uint8List compressed = base64.decode(zipText);
  var gzipBytes = new GZipDecoder().decodeBytes(compressed);
  print(gzipBytes);

Throws error

Unhandled Exception: FormatException: Invalid GZip Signature flutter

Any help is really appreciated.

Gantline answered 17/1, 2021 at 15:33 Comment(3)
follow this link: #39735645Raffinose
Does this answer your question? How to compress a string using GZip or similar in Dart?Agora
I have tried that , after so much of search i couldnot solve the issue and asked a question. Those link came when i serched initally itsel.but it also throws errror Unhandled Exception: FormatException: Invalid GZip Signature flutterGantline
P
2

Base from the errors thrown, it looks like the issue came from the String that you're trying to decode. Were the data from the json response properly parsed to String? You may want to consider verifying if the "compressedData" from the json response is valid and can be decoded using gzip.

If the value on zipText does access data from dataList - which is a List<Map<String, String>>. Make sure that you're able to access the "compressedData" by var zipText = '${_dataList[index]['Data']}';

Aside from that, you'd also need to decode the value from GZipDecoder().decodeBytes(Uint8List) to String.

decode(String zipText) {
  // if the sample data is a List<Map<String, String>>
  // you need to use the key to access
  // the compressed data from the List item
  // zipText = '${_dataList[0]['Data']}';
  Uint8List compressed = base64.decode(zipText);
  var gzipBytes = new GZipDecoder().decodeBytes(compressed);

  // Decode List<int> to String
  var stringDecoded = utf8.decode(gzipBytes);
  debugPrint('decoded: $stringDecoded');

  setState(() {
    _textEditingControllerEncode.text = stringDecoded;
  });
}

Here's a simple sandbox that you can play with. The decode(String) method in this sample uses the code snippet you've provided.

import 'dart:convert';
import 'dart:typed_data';

import 'package:archive/archive.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formEncodeKey = GlobalKey<FormState>();
  final _formDecodeKey = GlobalKey<FormState>();
  final _textEditingControllerEncode = TextEditingController();
  final _textEditingControllerDecode = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            Expanded(
              child: Form(
                key: _formEncodeKey,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      controller: _textEditingControllerEncode,
                      decoration: InputDecoration(
                          hintText: 'Enter some text to Encode'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter some text to Encode';
                        }
                        return null;
                      },
                    ),
                    ElevatedButton(
                      onPressed: () {
                        if (_formEncodeKey.currentState!.validate()) {
                          encode(_textEditingControllerEncode.value.text);
                        }
                      },
                      child: Text('Encode'),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Form(
                key: _formDecodeKey,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      controller: _textEditingControllerDecode,
                      decoration: InputDecoration(
                          hintText: 'Enter some text to Decode'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter some text to Decode';
                        }
                        return null;
                      },
                    ),
                    ElevatedButton(
                      onPressed: () {
                        if (_formDecodeKey.currentState!.validate()) {
                          decode(_textEditingControllerDecode.value.text);
                        }
                      },
                      child: Text('Decode'),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  var _dataList = [
    {"Data": "H4sIABqe5GAA//NIzcnJVyjPL8pJUQQAlRmFGwwAAAA="}, // Hello world!
    {"Data": "H4sIABuk5GAA/3PLKS0pSS1SKMpPzi5WBADZNee+DgAAAA=="} // Flutter rocks!
  ];

  encode(String zipText) {
    var stringBytes = utf8.encode(zipText);
    var gzipBytes = GZipEncoder().encode(stringBytes);
    var stringEncoded = base64.encode(gzipBytes!);
    debugPrint('encoded: $stringEncoded');

    setState(() {
      _textEditingControllerEncode.clear();
      _textEditingControllerDecode.text = stringEncoded;
    });
  }

  decode(String zipText) {
    // if the sample data is a List<Map<String, String>>
    // you need to use the key to access
    // the compressed data from the List item
    // zipText = '${_dataList[0]['Data']}';
    Uint8List compressed = base64.decode(zipText);
    var gzipBytes = new GZipDecoder().decodeBytes(compressed);

    // Decode List<int> to String
    var stringDecoded = utf8.decode(gzipBytes);
    debugPrint('decoded: $stringDecoded');

    setState(() {
      _textEditingControllerEncode.text = stringDecoded;
      _textEditingControllerDecode.clear();
    });
  }
}

Demo

Prosthodontist answered 6/7, 2021 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.