如何在 Dart 中获取字符串的字节?

How to get bytes of a String in Dart?

如何在 dart 中读取 String 的字节? 在 Java 中可以通过 String 方法 getBytes().

See example

import 'dart:convert';

String foo = 'Hello world';
List<int> bytes = utf8.encode(foo);
print(bytes);

Output: [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

此外,如果你想转换回来:

String bar = utf8.decode(bytes);

有一个codeUnitsgetter那个returnsUTF-16

String foo = 'Hello world';
List<int> bytes = foo.codeUnits;
print(bytes);

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

runes returns Unicode 代码点

String foo = 'Hello world';
// Runes runes = foo.runes;
// or
Iterable<int> bytes = foo.runes;
print(bytes.toList());

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

对于可能经过 base64 编码的图像,请使用

Image.memory(base64.decode('base64EncodedImageString')),

导入函数
import 'dart:convert';