Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Encode/Decode Path, File, Bytes and Base64 in Dart/Flutter

In this example, we are going to show you the basic handling of files in Dart and Flutter. We are going to decode or encode Path to file, file to Bytes, Bytes to Base64 String, or vice versa. 

How to Convert Path String to File:

import 'dart:io';
String imgpath = "data/0/image.jpg";
File imgfile = File(imagepath);

How to Get Path From File:

import 'dart:io';
String path = imgfile.path;

How to Convert File to Bytes:

import 'dart:io';
import 'dart:typed_data';
Uint8List imgbytes = await imagefile.readAsBytes();
//OR
Uint8List imgbytes1 = imagefile.readAsBytesSync();

How to Convert Bytes to File:

import 'dart:io';
import 'dart:typed_data';
File decodedimgfile = await File("image.jpg").writeAsBytes(imgbytes);

How to Encode Bytes to Base64

import 'dart:convert';
import 'dart:typed_data';
String bs4str = base64.encode(imgbytes);
//OR
String bs4str1 = base64Encode(imgbytes);

How to Decode Base64 to Bytes:

import 'dart:convert';
import 'dart:typed_data'; //for bytes Uint8List
Uint8List decodedbytes = base64.decode(bs4str);
//OR
Uint8List decodedbytes1 = base64Decode(bs4str);

Practical Use in Project (Encode Image File to Base64):

String imgpath = "data/0/image.jpg";
File imgfile = File(imagepath);
Uint8List imgbytes = await imagefile.readAsBytes();
String bs4str = base64.encode(imgbytes);

Decode Base64 to Image File

String bs4str = "/9j/4QejRXhpZgAASUkqAAgAAAAUACACBAABAA....";
Uint8List decodedbytes = base64.decode(bs4str);
File decodedimgfile = await File("image.jpg").writeAsBytes(decodedbytes);
String decodedpath = decodedimgfile.path;

In this way, you can handle files in Dart/Flutter.

No any Comments on this Article


Please Wait...