Base64 encoding and decoding in Dart (and Flutter)

Last updated on November 11, 2020 A Goodman Loading... Post a comment

To encode or decode Base64 in Dart, you can use dart:convert:

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

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

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x