Dart - 编码和解码 base64 字符串 [英] Dart - Encode and decode base64 string
本文介绍了Dart - 编码和解码 base64 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何原生转换 string -> base64 和 base64 -> string
How to native convert string -> base64 and base64 -> string
我只找到了这个 字节到 base64string
想要这样:
String Base64String.encode();
String Base64String.decode();
还是从其他语言移植更容易?
or ported from another language is easier?
推荐答案
您可以使用 BASE64 编解码器(在 Dart 2 中更名为 base64
)和 LATIN1 编解码器(在 Dart 2 中重命名为 latin1
)来自转换库.
You can use the BASE64 codec (renamed base64
in Dart 2) and the LATIN1 codec (renamed latin1
in Dart 2) from convert library.
var stringToEncode = 'Dart is awesome';
// encoding
var bytesInLatin1 = LATIN1.encode(stringToEncode);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var base64encoded = BASE64.encode(bytesInLatin1);
// RGFydCBpcyBhd2Vzb21l
// decoding
var bytesInLatin1_decoded = BASE64.decode(base64encoded);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var initialValue = LATIN1.decode(bytesInLatin1_decoded);
// Dart is awesome
如果您总是使用 LATIN1
来生成编码字符串,您可以通过创建编解码器来直接将字符串转换为编码字符串,从而避免 2 个转换调用.
If you always use LATIN1
to generate the encoded String you can avoid the 2 convert calls by creating a codec to directly convert a String to/from an encoded String.
var codec = LATIN1.fuse(BASE64);
print(codec.encode('Dart is awesome'));
// RGFydCBpcyBhd2Vzb21l
print(codec.decode('RGFydCBpcyBhd2Vzb21l'));
// Dart is awesome
这篇关于Dart - 编码和解码 base64 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文