如何在base64中编码Dart字符串? [英] How do I encode a Dart string in base64?
问题描述
我正在使用需要以base64编码的数据的API。如何在base64中编码一个简单的字符串?
I'm working with an API that requires data encoded in base64. How can I encode a simple string in base64?
推荐答案
它需要几个步骤, 。
Dart在 package:crypto library, CryptoUtils.bytesToBase64
,它接受一个字节列表, 。为了从Dart字符串中获取字节列表,可以使用 UTF8.encode() .org / apidocs / channels / stable / dartdoc-viewer / dart:convert.Utf8Codec#id_encoderel =nofollow noreferrer> dart:convert library。
Dart has a function in the package:crypto library, CryptoUtils.bytesToBase64
, which takes a list of bytes to encode as base64. In order to get the list of bytes from a Dart string, you can use the UTF8.encode()
function in the dart:convert library.
所有在一起,这看起来像:
All together, this looks like:
import 'dart:convert';
import 'package:crypto/crypto.dart';
main() {
var str = "Hello world";
var bytes = UTF8.encode(str);
var base64 = CryptoUtils.bytesToBase64(bytes);
print(base64);
}
在浏览器中,那么你有更容易的选择使用浏览器的内置 btoa
函数。上面的代码片断成为:
If you're working inside the browser, then you have the easier option of using the browser's built in btoa
function. The above code snippet becomes:
import 'dart:html';
main() {
var str = "Hello world";
var base64 = window.btoa(str);
print(base64);
}
这篇关于如何在base64中编码Dart字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!