9.4 C
New York
Saturday, December 2, 2023

Base64 encoding and decoding in Dart (and Flutter)

To encode or decode Base64 in Dart, you can make use of 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:

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)); 
}

AdvertisementsOutput:

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

ThatÂ’s it. Further reading:

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

Related Articles

Latest Articles