Flutter – How to show an image

In this post, we will see how to show an image in a Flutter application.

First of all, we open Android Studio and we create a new Flutter application called showdog:


Then, we create a folder in the project called images and we put inside a picture of our dog (this is my wonderful dog!):


Finally, we open the file main.dart and we write this code:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        // entire page
        backgroundColor: Colors.green,
        appBar: AppBar(
          centerTitle: true, // we align the title in the center
          title: Text('Dorian'), // name of our dog
          backgroundColor: Colors.greenAccent
        ),
        body:
        Center(
          child: Image(
            image: AssetImage('images/dorian.jpg')
          ),
        ),
      ),
    ),
  );
}


Now, if we run the application this will be the output:


It doesn’t work!
Fortunately, the solution is very simple.
In fact, we have just to tell Flutter where the images are.
In order to do this, we open the file called pubspec.yaml and modify the assets section:

 # To add assets to your application, add an assets section, like this:
  assets:
    - images/

In this way, we are specifying that all assets are in the folder images.


Now, if we run the application, this will be the output: