{

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 base64 class.

This example converts the string into an encoded base64 string.

  • First string literal is created
  • Convert String to Bytes using 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example