问题描述
项目中在写入包时遇到一个字节溢出的问题
在输入文字内容或者符号内容时收到了提示报错
Unhandled Exception: RangeError (index): Index out of range: index should be less than 256: 65308
原因分析:
在输入字符串是使用了codeUnits 而codeUnits在Dart中是一个不可修改的UTF-16编码组列表
/// An unmodifiable list of the UTF-16 code units of this string.
List<int> get codeUnits;
如果输入内容为文字或者符号 (文字符号的字节为2,emoji为3) 得到的值是utf-16编码组 而写入时是以utf-8 所以导致溢出
List<int> createData() {
List<int> pkgData = [];
pkgData.add(type);
pkgData.addAll(data.codeUnits);
return pkgData;
}
解决方案:
使用utf8.encode()方法把输入内容转换为utf8编码组
List<int> createData() {
List<int> pkgData = [];
pkgData.add(type);
// pkgData.addAll(data.codeUnits);
pkgData.addAll(utf8.encode(data));
return pkgData;
}