Open In App

Flutter – Load Images with image.file

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to show file images in Flutter. There is an image widget available in Flutter. In that, you may have to use Image.network, Image.asset, Image.memory. But have you used Image.file? Maybe you have used it. If not then Let’s learn about this. Sometimes we have to show images stored in our device to the Flutter application. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Select an image from the device

So how you will get the file from your device? If you know about this you are good to go if not read this article for getting images from the camera, and gallery of your device. Refer to this How to Select Multiple Images From image_picker in Flutter? From this you have got the file but how you will show it in your app?

Step 3: Show it in the application

Let’s discuss the syntax of the widget. There are two ways to show an image both are using the same widget just minor changes are there

Syntax:

Widget fileImage=   Image.file(file_you_want_to _show); 

 // you can replace file_you_want_to _show by variable name of your file

or

Syntax: 

Widget fileImage= Image(image: FileImage(file_you_want_to),);

Both the Syntax is similar in some way. We have selected the images from the device from the previous article. Now just we want to show the image. Here is the code for that.

Dart




GridView.builder(
                   // length of file you have selected
                 itemCount: selectedImages.length, 
                 gridDelegate:
                 const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3),
                        itemBuilder: (BuildContext context, int index) {
                          return Center(
                              // If it is web then you have use Image.network 
                              // Image.file will not work
                              child: kIsWeb 
                                  ? Image.network(
                                      selectedImages[index].path,
                                      // Height of image selected
                                        height: 100,
                                      // Width of image selected
                                      width: 100,
                                      // fit image in its width and height
                                      fit: BoxFit.fill,
                                      // set the alignment of image
                                      alignment: Alignment.center, 
                                                
                                    )
                                  : Image.file(selectedImages[index], 
                                      // Height of image selected
                                      height: 100,
                                      // width of image selected
                                      width: 100,
                                      // fit image in its width and height
                                      fit: BoxFit.fill, 
                                      // set the alignment of image
                                      alignment: Alignment.center,                                               
                            ));
                        },
                      )


Property of Image included in code

  1. height: To give height to the image. It takes double as its value. It gives the image the vertical length
  2. width: To give width to the image. It also takes double as its value. It gives the image of the horizontal length
  3. fit: This property is used to fit the image according to our needs.
  4. color: This is used to give color to your image.
  5. alignment: To align the image  

Note: This will only apply to android and ios for the web you have to use image.network

Full Source Code

Dart




import 'dart:io';
  
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.green),
      home: const MultipleImageSelector(),
      debugShowCheckedModeBanner: false,
    );
  }
}
  
class MultipleImageSelector extends StatefulWidget {
  const MultipleImageSelector({super.key});
  
  @override
  State<MultipleImageSelector> createState() => _MultipleImageSelectorState();
}
  
class _MultipleImageSelectorState extends State<MultipleImageSelector> {
  List<File> selectedImages = [];
  final picker = ImagePicker();
  @override
  Widget build(BuildContext context) {
    // display image selected from gallery
  
    return Scaffold(
      appBar: AppBar(
        title: const Text('File image select'),
        backgroundColor: Colors.green,
        actions: const [],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.green)),
              child: const Text('Select File Image'),
              onPressed: () {
                getImages();
              },
            ),
            const Padding(
              padding: EdgeInsets.symmetric(vertical: 18.0),
              child: Text(
                "GFG",
                textScaleFactor: 3,
                style: TextStyle(color: Colors.green),
              ),
            ),
            Expanded(
              child: SizedBox(
                width: 300.0,
                child: selectedImages.isEmpty
                    ? const Center(child: Text('Sorry nothing selected!!'))
                    : GridView.builder(
                        itemCount: selectedImages
                            .length, 
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3),
                        itemBuilder: (BuildContext context, int index) {
                          return Center(
                              child:
                                  kIsWeb 
                                      ? Image.network(
                                          selectedImages[index].path,
                                          height:
                                              100, 
                                          width: 100, 
                                          fit: BoxFit
                                              .fill, 
                                          alignment: Alignment
                                              .center, 
                                        )
                                      : Image.file(
                                          selectedImages[index],
                                          height:
                                              100, 
                                          width: 100, 
                                          fit: BoxFit
                                              .fill, 
                                          alignment: Alignment
                                              .center, 
                                ));
                        },
                  ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Future getImages() async {
    final pickedFile = await picker.pickMultiImage(
        requestFullMetadata: true,
        imageQuality: 100,
        maxHeight: 1000,
        maxWidth: 1000);
    List<XFile> xfilePick = pickedFile;
  
    setState(
      () {
        if (xfilePick.isNotEmpty) {
          for (var i = 0; i < xfilePick.length; i++) {
            selectedImages.add(File(xfilePick[i].path));
          }
        } else {
          ScaffoldMessenger.of(context).showSnackBar(// is this context <<<
              const SnackBar(content: Text('Nothing is selected')));
        }
      },
    );
  }
}


Output:

Here you can see the video of how we have selected the image and shown in the application.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads