【问题标题】:FormatException Uint8List convert to string with dartFormatException Uint8List 使用 dart 转换为字符串
【发布时间】:2019-12-28 20:00:40
【问题描述】:

我正在尝试使用 Dart(在 Flutter 项目中)将 Uint8List 转换为字符串。 我正在使用 Flutter Android USB 串行插件 (https://github.com/altera2015/usbserial)

数据来自 USB 设备,并作为流从库中返回。

如果输出为字符串,则如下所示:

[255,0,0,0,255....]

当我尝试时:

String newTag = ascii.decode(asyncSnapshot.data);

我得到了错误:

FormatException:Invalid value in input: 255

我不知道如何解决这个问题,我的结果应该是:

"352206000079439"

【问题讨论】:

  • 为什么需要将任意字节存储为String
  • 我正在使用来自连接到手机的 USB 设备(串行)的数据。该设备将数据发送到我的颤振应用程序。数据类型为 Uint8List。我需要检索该值。
  • 这并不能解释为什么你需要它作为 String 而不是保持它作为 Uint8List
  • 该字符串在数据库中被引用。这些值来自我使用 RFID 阅读器读取的电子标签。阅读器读取标签,发送值。它使用这个值来查询数据库。
  • Dart Strings 应该存储有效的 UTF-16。试图将任意数据存储为String 是自找麻烦。如果您需要将String 用作数据库的键,那么您将需要执行其他操作,例如将您的数据编码String(例如base64)并使用编码的代替。

标签: flutter dart


【解决方案1】:

如果数据已压缩为 blob 类型。

Uint8List bytes = Uint8List.fromList(tcp_socket_blob_data);
var inflated = zlib.decode(bytes);
var data = utf8.decode(inflated);

更多:flutter/dart: How to decompress/inflate zlib binary string in flutter

【讨论】:

    【解决方案2】:

    试试这个;

    List<int> list = 'someData'.codeUnits;
    Uint8List bytes = Uint8List.fromList(list);
    String string = String.fromCharCodes(bytes);
    

    【讨论】:

    • 我测试了你的代码,我得到一个字符串:“ŸŸŸŸŸŸŸŸ”。但我应该得到的是“352206000079439”
    猜你喜欢
    • 2022-10-05
    • 1970-01-01
    • 2020-03-16
    • 2020-08-25
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多