4 ways to display image in flutter - image picker, image base64

0

There are four ways to display image in flutter :

1. Image network use URL 
2. Image assets display from locally 
3. Image memory (example image from base64 encoded) 
4. Image File (Pick image from app gallery)


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

void main() {
  runApp(const MaterialApp(
      debugShowCheckedModeBanner: false, home: DisplayImageDemo()));
}

class DisplayImageDemo extends StatefulWidget {
  const DisplayImageDemo({Key? key}) : super(key: key);

  @override
  State<DisplayImageDemo> createState() => _DisplayImageDemoState();
}

class _DisplayImageDemoState extends State<DisplayImageDemo> {
  File imageFile = File("");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _displayImage(),
    );
  }

  Widget _displayImage() {
    return imageFileWidget();
  }

  Image _displayImageNetwork() {
    return Image.network(
        "https://iconutopia.com/wp-content/uploads/2020/04/ghost-phone-wallpaper-iconutopia.jpg");
  }

  Image _diplayImageAsset() {
    return Image.asset("assets/images/wallpaper.jpg");
  }

  Image _diplayImageMemory() {
    String imageBase64Str =
        "{base64 encoded string}";
    return Image.memory(base64Decode(imageBase64Str));
  }

  Widget imageFileWidget() {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          ElevatedButton(
              onPressed: () => _pickImage(), child: Text("Pick Image")),
          ElevatedButton(
              style: ElevatedButton.styleFrom(primary: Colors.red),
              onPressed: () {
                setState(() {
                  imageFile = File("");
                });
              },
              child: Text("Clear Image")),
        ],
      ),
      if (imageFile.path.isNotEmpty) _displayImageFile(imageFile)
    ]);
  }

  _pickImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    setState(() {
      imageFile = File(image!.path);
    });
  }

  Image _displayImageFile(File getImage) {
    return Image.file(getImage);
  }
}

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

Random Posts