{

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


How to Encode and decode a string in Dart and Flutter

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
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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart