{

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: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example