[英]How to encode and decode Base64 and Base64Url in Flutter / Dart
I want to encode the following string in Base64Url in Flutter and decode it in on a Dart server.我想在 Flutter 的 Base64Url 中对以下字符串进行编码,并在 Dart 服务器上对其进行解码。
"username:password"
How do I do that?我怎么做? And how do I do it in Base64?
我如何在 Base64 中做到这一点?
The dart:convert
library contains an encoder and decoder for Base64 and Base64Url. dart:convert
库包含 Base64 和 Base64Url 的编码器和解码器。 However, they encode and decode Lists of integers, so for strings you also need to encode and decode in UTF-8.但是,它们对整数列表进行编码和解码,因此对于字符串,您还需要以 UTF-8 进行编码和解码。 Rather than doing these two encodings separately, you can combine them with
fuse
.您可以将它们与
fuse
结合起来,而不是分别进行这两种编码。
You need to have the following import:您需要具有以下导入:
import 'dart:convert';
String credentials = "username:password";
Codec<String, String> stringToBase64 = utf8.fuse(base64);
String encoded = stringToBase64.encode(credentials); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64.decode(encoded); // username:password
Note that this is equivalent to:请注意,这等效于:
String encoded = base64.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64.decode(encoded)); // username:password
String credentials = "username:password";
Codec<String, String> stringToBase64Url = utf8.fuse(base64Url);
String encoded = stringToBase64Url.encode(credentials); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64Url.decode(encoded); // username:password
Again, this is equivalent to:同样,这相当于:
String encoded = base64Url.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64Url.decode(encoded)); // username:password
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.