How to Use Base64 Encoding in Flutter (With Practical Example)

Base64 in Flutter

Base64 is a method to convert binary data (like images or files) into a text string, making it easy to send via APIs, store in databases, or embed into JSON.

Example Use Case: Convert Image to Base64 in Flutter

Let’s walk through a real-world example where you:

  • Pick an image using image_picker
  • Convert it to a Base64 string
  • Optionally decode it back and show in Image.memory

Using Base64 in Flutter is essential for modern apps dealing with file uploads, especially for:

  • Signature pads
  • Photo ID verification
  • Offline-first apps

UI Code

import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class Base64Example extends StatefulWidget {
  @override
  _Base64ExampleState createState() => _Base64ExampleState();
}

class _Base64ExampleState extends State<Base64Example> {
  String? base64Image;
  Uint8List? decodedImageBytes;

  Future<void> pickAndEncodeImage() async {
    final picker = ImagePicker();
    final XFile? pickedImage = await picker.pickImage(source: ImageSource.gallery);

    if (pickedImage != null) {
      final bytes = await File(pickedImage.path).readAsBytes();

      // Encode to base64
      base64Image = base64Encode(bytes);

      // Optionally decode again to display
      decodedImageBytes = base64Decode(base64Image!);

      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Base64 Encode Example")),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            ElevatedButton.icon(
              onPressed: pickAndEncodeImage,
              icon: const Icon(Icons.image),
              label: const Text("Pick Image & Encode"),
            ),
            const SizedBox(height: 20),

            if (base64Image != null) ...[
              const Text(
                "Encoded Base64 String (First 100 chars):",
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              Text(
                base64Image!.substring(0, 100) + '...',
                style: const TextStyle(fontSize: 12, color: Colors.grey),
              ),
              const SizedBox(height: 20),
              const Text("Decoded Image:"),
              const SizedBox(height: 10),
              Image.memory(decodedImageBytes!, height: 200),
            ],
          ],
        ),
      ),
    );
  }
}

For API :

final bytes = await File(pickedFile.path).readAsBytes();
final base64Str = base64Encode(bytes);

//Add data URI prefix (make sure you use the right type: png, jpeg, etc.)
final base64WithHeader = “data:image/png;base64,$base64Str”;

{
  "imageData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...",
 
}

Another Example:

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.