首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >未处理的异常: FormatException:意外的扩展字节(偏移量为5)

未处理的异常: FormatException:意外的扩展字节(偏移量为5)
EN

Stack Overflow用户
提问于 2021-01-17 23:33:34
回答 1查看 5K关注 0票数 2

Json响应有一个gzip编码的字符串。

代码语言:javascript
运行
复制
 var dataList = [
    {"Data": "compressedata"},
    {"Data": "compressedData"}
  ];

我尝试了很多方法来解压缩字符串,但都没有得到预期的结果。尝试的最后一种方法是

代码语言:javascript
运行
复制
  List<int> res = base64.decode(base64.normalize(zipText));

  print(utf8.decode(res));

其中zipText是来自json的字符串,这将抛出错误

代码语言:javascript
运行
复制
Unhandled Exception: FormatException: Unexpected extension byte (at offset 5)

另一种方式

代码语言:javascript
运行
复制
  Uint8List compressed = base64.decode(zipText);
  var gzipBytes = new GZipDecoder().decodeBytes(compressed);
  print(gzipBytes);

抛出错误

代码语言:javascript
运行
复制
Unhandled Exception: FormatException: Invalid GZip Signature flutter

任何帮助都是非常感谢的。

EN

Stack Overflow用户

发布于 2021-07-07 02:52:36

从抛出的错误来看,问题似乎来自于您试图解码的字符串。来自json响应的数据是否正确解析为字符串?您可能需要考虑验证来自json响应的"compressedData“是否有效,以及是否可以使用gzip进行解码。

如果zipText上的值确实访问来自dataList的数据,则返回String>>。确保您能够通过var zipText = '${_dataList[index]['Data']}';访问"compressedData“

除此之外,您还需要将值从GZipDecoder().decodeBytes(Uint8List)解码为字符串。

代码语言:javascript
运行
复制
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;
  });
}

这是一个简单的沙盒,你可以使用它。此示例中的decode(String)方法使用您提供的代码片段。

代码语言:javascript
运行
复制
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();
    });
  }
}

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65762567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档