How to convert BASE64 string into Image with Flutter?

In flutter few scenarios we need to convert Base64 String to Image. How we can convert BASE64 string into Image with Flutter? We  can convert a Uint8List to a Flutter Image widget using the Image.memory constructor. 

With Base64Encoder(), Base64Codec() we can convert it to Image.

 

Below Example will show you how to convert Base64 String to Image in flutter

 

 

import 'package:flutter/material.dart';

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:typed_data';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  String _base64;

  @override
  void initState() {
    super.initState();
    (() async {
      http.Response response = await http.get(
        'https://thebhakti.com/wp-content/uploads/2019/01/mahakal.jpg',
      );
      if (mounted) {
        setState(() {
          _base64 = Base64Encoder().convert(response.bodyBytes);
        });
      }
    })();
  }

  @override
  Widget build(BuildContext context) {
    if (_base64 == null)
      return new Container();
    Uint8List bytes = Base64Codec().decode(_base64);
    return new Scaffold(
      appBar: new AppBar(title: new Text('Example App')),
      body: Image.memory(bytes,fit: BoxFit.cover,),


    );
  }
}

 

Base64 String to Image

Tags: Base64, Image, Flutter