How to load images with image.file

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


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/

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,
            ),
          ),
        ),
      ),
    );
  }
}

Tags:

Dart

Flutter