Kinda Code
Home/Dart/Base64 encoding and decoding in Dart (and Flutter)

Base64 encoding and decoding in Dart (and Flutter)

Last updated: February 14, 2023

What are the points?

To encode or decode Base64 in Dart, you can import and use the dart:convert library:

import 'dart:convert';

For base64 decoding, use one of these 2 methods:

  • String base64.encode(List<int> bytes)
  • String base64Encode(List<int> bytes)

For base64 decoding, use one of the following methods:

  • Uint8List base64.decode(String input)
  • Uint8List base64Decode(String input)

If you want to base64-encode a string, you need to convert it to Uint8List by using utf8.encode(), like this:

Uint8List bytes = utf8.encode(String input);
base64.encode(bytes);

Example

The code:

// kindacode.com
// main.dart
import 'dart:convert';

void main(){
  // base64 encoding a string
  var encoded1 = base64.encode(utf8.encode('I like dogs'));
  print('Encoded 1: $encoded1');
  
  // base64 encoding bytes
  var encoded2 = base64.encode([65, 32, 103, 111, 111, 100, 32, 100, 97, 121, 32, 105, 115, 32, 97, 32, 100, 97, 121, 32, 119, 105, 116, 104, 111, 117, 116, 32, 115, 110, 111, 119]);
  print('Encoded 2: $encoded2');
  
  // base64 decoding
  var decoded = base64.decode('QSBnb29kIGRheSBpcyBhIGRheSB3aXRob3V0IHNub3c=');
  print('Decoded: $decoded');
  // Converting the decoded result to string
  print(utf8.decode(decoded)); 
}

Output:

Encoded 1: SSBsaWtlIGRvZ3M=
Encoded 2: QSBnb29kIGRheSBpcyBhIGRheSB3aXRob3V0IHNub3c=
Decoded: [65, 32, 103, 111, 111, 100, 32, 100, 97, 121, 32, 105, 115, 32, 97, 32, 100, 97, 121, 32, 119, 105, 116, 104, 111, 117, 116, 32, 115, 110, 111, 119]
A good day is a day without snow

More about base64 encoding & decoding

Base64 encoding and decoding are commonly used to convert binary data (such as images, audio, and video) into text-based data (such as ASCII characters), and vice versa. The process of base64 encoding represents binary data as text characters that can be easily transmitted and stored in text-based systems, such as databases or file systems. Base64 decoding is the reverse process, converting the text-based representation back into binary data.

Base64 encoding and decoding are often used in web applications to transmit binary data over HTTP or to encode binary data within URLs. They are also used for encryption and secure storage of binary data in applications where text-based storage is required.

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Related Articles