Base64 Encoding in Dart
Dart provides built-in support for base64 encoding/decoding.
import 'dart:convert';
void main() {
// Here's the string we'll encode/decode.
String data = "abc123!?\$*&()'-=@~";
// Dart supports both standard and URL-compatible base64.
// Here's how to encode using the standard encoder.
String sEnc = base64.encode(utf8.encode(data));
print(sEnc);
// Decoding may throw a FormatException, which you can catch
// if you don't already know the input to be well-formed.
try {
List<int> sDec = base64.decode(sEnc);
print(utf8.decode(sDec));
} catch (e) {
print('Error decoding: $e');
}
print('');
// This encodes/decodes using a URL-compatible base64 format.
String uEnc = base64Url.encode(utf8.encode(data));
print(uEnc);
try {
List<int> uDec = base64Url.decode(uEnc);
print(utf8.decode(uDec));
} catch (e) {
print('Error decoding: $e');
}
}
In Dart, we use the dart:convert
library which provides base64 encoding and decoding functionality. The base64
class is used for standard base64 encoding, while base64Url
is used for URL-compatible encoding.
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
), but they both decode to the original string as desired.
To run this Dart program, save it as base64_encoding.dart
and use the following command:
$ dart run base64_encoding.dart
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
Note that in Dart, we use utf8.encode()
to convert the string to a list of bytes before encoding, and utf8.decode()
to convert the decoded bytes back to a string. Also, Dart’s base64 decoding methods may throw a FormatException
if the input is not properly formatted, so it’s good practice to handle this potential exception.