Dart| Flutter How to encode and decode a string base64 with example

Sometimes, need to send the string data in base64, So we need to know how to send encode a string and decode a string.

There are multiple ways we can do it. Dart provides an inbuilt dart:convert library to encode and decode various objects in UTF8 formats.

How to encode a string in base64 format in dart

dart:convert library provides a base64 class.

This example converts the string into an encoded base64 string.

  • First string literal is created
  • Convert String to Bytes using the utf8.encode() method
  • use base64.encode() method to convert base64 string

here is an example code to encode a string in base64 format.

import 'dart:convert';

main() {
  final str = "Welcome to my site";
  final strBytes = utf8.encode(str);
  final base64String = base64.encode(strBytes);
  print(base64String);
}

Output:

V2VsY29tZSB0byBteSBzaXRl

How to parse and decode base64 string into String in dart

This example converts a base64 string into a readable string with an example.

base64.decode() convert the base64 string into bytes. utf8.decode() convert bytes to normal string

Here is an example code

import 'dart:convert';

main() {
  final str = "Welcome to my site";
  final strBytes = utf8.encode(str);
  final base64String = base64.encode(strBytes);
  print(base64String); //V2VsY29tZSB0byBteSBzaXRl

  var decodeBytes = base64.decode(base64String);
  var decodeString = utf8.decode(decodeBytes);
  print(decodeString); //Welcome to my site
}

Output:

V2VsY29tZSB0byBteSBzaXRl
Welcome to my site