56

I can't seem to simply load an image from the hard drive to the screen. Image.network seems straightforward. But I can't figure out how to use Image or Image.file. Image seems to require a stream, so I don't think that is what I am looking for.

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
    File file = new File("Someimage.jpeg");
    @override
    Widget build(BuildContext context) {
        return new MaterialApp(
            home: new Image.file(file),  //doesn't work, but no errors
        );
    }
}

I added Someimage to the pubspec.yaml file, but that doesn't work either:

assets:
    - Someimage.jpeg

Can someone give me an example of how this is done? Thanks.

12 Answers 12

136

The difference and relation between Image, ImageProvider:

Image:

Creates a widget that displays an image.

To show an image from the network or an asset bundle, consider using [new Image.network] and [new Image.asset] respectively.

So Image is a widget. Like <img> tag in html.

ImageProvider:

Identifies an image without committing to the precise final asset. This allows a set of images to be identified and for the precise image to later be resolved based on the environment, e.g. the device pixel ratio.

So ImageProvider is like the src attribute for an Image.

Now Image takes an argument image which is an ImageProvider. There are 4 ways of getting the ImageProvider

  • AssetImage:

    Use to load a pre-defined set of images that are packed along with the apk.

    e.g. To display Banner Images, some custom icons.

  • NetworkImage:

    Used to load dynamic images from the internet.

  • FileImage:

    Used to load images from the file system in the target device.

    e.g. To display a newly downloaded image.

  • MemoryImage:

    Used to load raw image from memory.

    e.g. To get the user's wallpaper and load it into a widget.

Now they are all ImageProviders. Anyone of them can be used as the image attribute to the Image widget. And the flutter community simplified the syntax by adding extended classes to the Image widget itself.

So

  • Image.asset(name) is essentially Image(image: AssetImage(name)),
  • Image.file(path) is essentially Image(image: FileImage(File(path))),
  • Image.network(url) is essentially Image(image: NetworkImage(url)),
  • Image.memory(list) is essentially Image(image: MemoryImage(list))

Now it should be clear that

  • The apk size increases with the number of asset images.

  • The loading time (what the user sees) for them would be generally in the order

    NetworkImage > FileImage > AssetImage > MemoryImage

2
  • 2
    You should make sure when you quote, to include, your citations Commented Jun 3, 2019 at 17:28
  • Is there any way to get image and save to file from FadeInImage.assetNetwork OR ImageProvider (FadeInImage.assetNetwork.image return ImageProvider)? Commented Jul 31, 2020 at 13:09
24

Here is an example of the use of Image.file. This would not be the recommended way, but the use case could be if you downloaded the image in your app via http and then wanted to display the image (e.g. the image is not stored in assets during install).

In your pubspec.yaml, add :

path_provider: ^0.2.2

Code :

import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

  Future<File> _getLocalFile(String filename) async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    File f = new File('$dir/$filename');
    return f;
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Flutter Demo',
        home: new FutureBuilder(
            future: _getLocalFile("flutter_assets/image.png"),
            builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
              return snapshot.data != null ? new Image.file(snapshot.data) : new Container();
            })
    );
  }
}

To simulate downloading the image you can push the image using adb :

adb push image.png /data/data/com.example.imagetest/app_flutter/flutter_assets/
20

Here is another example which uses a jpg as a background image. It also applies opacity to the image.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: new AppBar(
          title: new Text("test"),
        ),
        body: new Container(
          decoration: new BoxDecoration(
            image: new DecorationImage(
              colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.6), BlendMode.dstATop),
              image: new AssetImage("assets/images/keyboard.jpg"),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}
1
  • 2
    That definitely answers my question on how to display an image, but can image display be done with image.file? I can't find any use of image.file, so I don't know why it exists.
    – richalot
    Commented Apr 15, 2018 at 23:41
7
child: Image.file(
 File('DirectoryLocation/imageName.jpg'),
 height: 45.0,
 width: 45.0,
),
5

Replace

new Image.file(file)

with

FileImage(file)

and that should work for you.

3

Try this :

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return new MaterialApp(
                home: new ImageIcon(
                          new AssetImage(
                              "assets/images/image.png"),
                          size: 24.0,
                          color: Colors.white),
        );
    }
}

In pubspec.yaml, you need :

  assets:
    - assets/images/image.png
4
  • Thank you. This code is not working for me either. All I am seeing is a blank white box, and not the image. I removed the color property, but then all I got was a black box.
    – richalot
    Commented Apr 15, 2018 at 3:58
  • Is there any error in your Run window ? if the asset cannot be found you will get an error during runtime: "Unable to load asset"
    – Rockvole
    Commented Apr 15, 2018 at 4:54
  • That's the funny thing. I'm using IntelliJ, and I have no errors at all. I looked at the image, image location, names, and everything checks out too. Any other ideas? Sorry.
    – richalot
    Commented Apr 15, 2018 at 5:37
  • 1
    That works, but it seems only to work because it is one color to that image. Is there a way to get a full color image to render? And is image.file a useless method?
    – richalot
    Commented Apr 15, 2018 at 17:18
2

You can add Image.File as Container's child

Container(
     padding:
        EdgeInsets.zero,
         height: 150,
               width: 150,
               child: Image.file(File(filePath))
   )
1
  • I think it would be more helpful for beginners if you could mention what the file variable should contain. Like "the path to an image file located in the user's device". Commented Mar 2, 2020 at 10:32
1

Flutter contains assert section inside pubspec.yaml where it contains asserts of your application. eg:

assets:
    - data_repo/img/ic_launcher.png

1. With pubspec.yaml:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: LoadLocalImage()));
}

class LoadLocalImage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Load Local Image"),
      ),
      body: new Container(
        decoration: new BoxDecoration(
            image: new DecorationImage(
                image: new AssetImage('data_repo/img/ic_launcher.png'), fit: BoxFit.cover)),
      ),
    );
  }
}

2. With Image.asset:

import 'package:flutter/material.dart';

    void main() {
      runApp(new MaterialApp(home: LoadLocalImage()));
    }

    class LoadLocalImage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
            appBar: new AppBar(
              title: new Text("Load Local Image"),
            ),
            body: Image.asset(
              'data_repo/img/ic_launcher.png',
              fit: BoxFit.cover,
            ));
      }
    }

Folder Structure: enter image description here Output: enter image description here

Please refer below link for more description:

https://flutter.dev/docs/cookbook/images/network-image

0

if your image in the assets you can use the image.asset constructor

1
  • 2
    Could you please show me how this works? new Image.asset(file) doesn't work. new Image.asset("images/Someimage.jpeg") doesn't work. I really am trying, but I am obviously missing something basic.
    – richalot
    Commented Apr 15, 2018 at 1:14
0

use this package first:

import 'package:http/http.dart' show get;
import 'dart:io';

Image loadImageFromFile(String path) {
    File file = new File(path);
    Image img = Image.file(file);
}

void storeImageToFile(String path,String url) async {
    var response = await get(Url);
    File file = new File(path);
    file.create(recursive: true).then((val) async {
        if (await val.exists()) {
            await file.writeAsBytesSync(response.bodyBytes);
        }
    });
}
0

The assets in the pubspec.yaml must be uncommented.

The assets in the pubspec.yaml must be uncommented.
This will help to load the file image.asset as expected.

0

In case you are uploading an image using image_picker or something and want to render it from the FileImage(PATH) you get. You might need to use Image(image: FileImage(File(path))) format instead of Image.file(path). I was getting the following error when using Image.file(path):

The argument type 'ImageProvider<Object>' can't be assigned to the parameter type 'File'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.