How to include images in your Flutter app

This is a repost of an answer I wrote on Stack Overflow.

I originally wrote this answer when I was learning how to add images to my Flutter project. Check out the documentation, but in case you need a little more step-by-step help, keep reading.

assets/images folder
  • This should be located in the root of your project, in the same folder as your pubspec.yaml file.
  • In Android Studio you can right click in the Project view
  • You don’t have to call it assets or images. You don't even need to make images a subfolder. Whatever name you use, though, is what you will register in the pubspec.yaml file.
  • You can just copy your image into assets/images. The relative path of lake.jpg, for example, would be assets/images/lake.jpg.
  • Open the pubspec.yaml file that is in the root of your project.
  • Add an assets subsection to the flutter section like this:
flutter:   
assets:
- assets/images/lake.jpg
  • If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /):
flutter:
assets:
- assets/images/
  • Get the asset in an Image widget with Image.asset('assets/images/lake.jpg').
  • The entire main.dart file is here:
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Image from assets"),
),
body: Image.asset('assets/images/lake.jpg'), // <-- image
),
);
}
}

When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.

Running the app now you should have something like this:

  • See the documentation for how to do things like provide alternate images for different densities.

A Flutter and Dart developer. Follow me on Twitter @suragch1 to get updates of new articles.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store