Try it yourself with our free Base64 tool — runs entirely in your browser, no signup needed.

How to Base64 encode in Dart

How to Base64 encode in Dart

Base64 encoding is a widely used technique for converting binary data into a text format that can be easily transmitted or stored. In Dart, Base64 encoding is a crucial step in various applications, such as encoding images, encrypting data, or transmitting binary data over text-based protocols. In this guide, we will explore how to Base64 encode in Dart, covering the basics, handling edge cases, common mistakes, and performance tips.

Quick Example

Here is a minimal example that demonstrates how to Base64 encode a string in Dart:

import 'dart:convert';

void main() {
  String input = 'Hello, World!';
  String encoded = base64Encode(utf8.encode(input));
  print(encoded); // Output: SGVsbG8sIFdvcmxkIQ==
}

This code uses the base64 library, which is part of the Dart SDK, to encode the input string.

Step-by-Step Breakdown

Let's break down the code line by line:

  1. import 'dart:convert';: We import the dart:convert library, which provides the base64 and utf8 functions.
  2. void main() { ... }: We define the main function, which is the entry point of the program.
  3. String input = 'Hello, World!';: We define the input string that we want to encode.
  4. String encoded = base64Encode(utf8.encode(input));: We use the base64Encode function to encode the input string. However, base64Encode expects a Uint8List (a list of bytes) as input, so we use utf8.encode to convert the string to a Uint8List.
  5. print(encoded);: We print the encoded string to the console.

Handling Edge Cases

Here are some common edge cases that you should consider:

Empty/Null Input

If the input string is empty or null, the base64Encode function will throw an error. To handle this case, you can add a simple null check:

String input = '';
if (input != null && input.isNotEmpty) {
  String encoded = base64Encode(utf8.encode(input));
  print(encoded);
} else {
  print('Input is empty or null');
}

Invalid Input

If the input string contains invalid characters (e.g., non-ASCII characters), the utf8.encode function may throw an error. To handle this case, you can use the utf8.encodeAllowMalformed function, which replaces invalid characters with a replacement character:

String input = 'Hello, Sérgio!';
String encoded = base64Encode(utf8.encodeAllowMalformed(input));
print(encoded);

Large Input

If the input string is very large, the base64Encode function may throw an error or cause performance issues. To handle this case, you can use the base64Encode function with a chunkSize parameter, which allows you to encode the input in chunks:

String input = '... very large string ...';
int chunkSize = 1024;
List<String> chunks = [];
for (int i = 0; i < input.length; i += chunkSize) {
  String chunk = input.substring(i, i + chunkSize);
  String encodedChunk = base64Encode(utf8.encode(chunk));
  chunks.add(encodedChunk);
}
String encoded = chunks.join('');
print(encoded);

Unicode/Special Characters

If the input string contains Unicode or special characters, the utf8.encode function will encode them correctly. However, if you need to encode the input string in a specific encoding (e.g., UTF-16), you can use the utf16.encode function instead:

String input = 'Hello, Sérgio!';
String encoded = base64Encode(utf16.encode(input));
print(encoded);

Common Mistakes

Here are some common mistakes that developers make when Base64 encoding in Dart:

Mistake 1: Using the wrong encoding

// Wrong
String encoded = base64Encode(input.codeUnits);

// Correct
String encoded = base64Encode(utf8.encode(input));

Mistake 2: Not handling null input

// Wrong
String encoded = base64Encode(utf8.encode(input));

// Correct
if (input != null && input.isNotEmpty) {
  String encoded = base64Encode(utf8.encode(input));
  print(encoded);
} else {
  print('Input is empty or null');
}

Mistake 3: Not handling large input

// Wrong
String encoded = base64Encode(utf8.encode(input));

// Correct
int chunkSize = 1024;
List<String> chunks = [];
for (int i = 0; i < input.length; i += chunkSize) {
  String chunk = input.substring(i, i + chunkSize);
  String encodedChunk = base64Encode(utf8.encode(chunk));
  chunks.add(encodedChunk);
}
String encoded = chunks.join('');
print(encoded);

Performance Tips

Here are some performance tips for Base64 encoding in Dart:

  1. Use the base64Encode function with a chunkSize parameter to encode large input strings in chunks.
  2. Use the utf8.encode function with the allowMalformed parameter to handle invalid input characters.
  3. Avoid using the base64Encode function with a String input, as it will cause unnecessary conversions.

FAQ

Q: What is the difference between base64Encode and base64UrlEncode?

A: base64Encode encodes the input string using the standard Base64 alphabet, while base64UrlEncode encodes the input string using the URL-safe Base64 alphabet.

Q: How do I decode a Base64-encoded string in Dart?

A: You can use the base64Decode function to decode a Base64-encoded string.

Q: Can I use the base64Encode function with a List<int> input?

A: Yes, the base64Encode function can take a List<int> input, which represents a list of bytes.

Q: How do I handle non-ASCII characters in the input string?

A: You can use the utf8.encode function with the allowMalformed parameter to handle non-ASCII characters.

Q: Can I use the base64Encode function with a Stream input?

A: No, the base64Encode function does not support Stream inputs. You need to convert the Stream to a List<int> or a String before encoding.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp