This question already has an answer here:
- How to native convert string -> base64 and base64 -> string 4 answers
I'm working with an API that requires data encoded in base64. How can I encode a simple string in base64?
This question already has an answer here:
I'm working with an API that requires data encoded in base64. How can I encode a simple string in base64?
It requires a few steps, but encoding a string in base64 is pretty straightforward.
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);
}
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);
}
There is no need to use the crypto package since the core libraries provide built-in support for base64 encoding and decoding.
https://api.dartlang.org/1.14.2/dart-convert/BASE64-constant.html
import 'dart:convert';
main() {
var str = "Hello world";
var bytes = UTF8.encode(str);
var base64 = BASE64.encode(bytes);
print(base64);
}