本文介绍了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
)和(在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
来生成编码的String,则可以通过创建一个直接将字符串与编码的String相互转换的编解码器来避免两次convert调用.
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字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!