Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 73 ยท Material, styling and assets

Fonts, Images and Assets

Declare assets and fonts in pubspec.yaml, show images with Image.asset and Image.network, handle loading and errors, use SVG and icons, and understand image caching.

An app is more than code. It has a logo, photos, icons, and maybe a brand font. In Flutter, anything that is not Dart code but ships with your app is an asset. Assets are bundled into the app at build time, and Flutter loads them by a path you declare.

This lesson covers the full path: listing assets in pubspec.yaml, showing bundled and network images, loading states and errors, resolution variants, custom fonts, vector graphics, icons, and how Flutter caches images. The project file itself is introduced in Setting up and running your first app.

Real vs stand-in. All Dart and YAML is real and read-only here, because the site cannot run Flutter or bundle assets. The live examples are JavaScript stand-ins: one resolves which image variant gets picked for a screen density, and one shows a size-limited image cache.

Assets in three steps

Put the file Inside your project, like assets/images/.
Declare it List the folder in pubspec.yaml.
Use it Image.asset with the same path.
1 / 2

Declaring assets in pubspec.yaml

Flutter only bundles what you list. Putting a file in a folder is not enough.

YAML
flutter:
  uses-material-design: true

  assets:
    - assets/images/logo.png
    - assets/images/photos/
    - assets/data/recipes.json
  • A path ending in / includes every file directly in that folder, not its subfolders. List each subfolder separately.
  • Indentation is part of YAML. A wrong indent gives a confusing error or silently ignores the entry.
  • After editing pubspec.yaml, run flutter pub get (the IDE usually does this on save), then do a full restart: hot reload does not reload the asset bundle.

You use the same path string in code, relative to the project root. There is no assets/ magic, the folder name is only a convention.

Showing images

DART
// A bundled image
Image.asset(
  'assets/images/logo.png',
  width: 120,
  height: 120,
  fit: BoxFit.contain,
  semanticLabel: 'Recipes app logo',
)

fit decides how the picture is squeezed into the box it is given (the size rules are in Constraints go down, sizes go up):

  • BoxFit.contain: whole image visible, may leave empty space.
  • BoxFit.cover: fills the box, may crop. The usual choice for photos.
  • BoxFit.fill: stretches and distorts. Rarely what you want.
  • BoxFit.fitWidth / fitHeight: match one dimension.

An image with no size and no constraints takes its natural pixel size, which can overflow the screen. Give it a width, or put it inside a sized parent such as SizedBox or AspectRatio.

Network images

DART
Image.network(
  'https://example.com/photos/pasta.jpg',
  width: double.infinity,
  height: 200,
  fit: BoxFit.cover,
  loadingBuilder: (context, child, progress) {
    if (progress == null) return child;          // finished
    final total = progress.expectedTotalBytes;
    return Center(
      child: CircularProgressIndicator(
        value: total == null ? null : progress.cumulativeBytesLoaded / total,
      ),
    );
  },
  errorBuilder: (context, error, stackTrace) {
    return const Center(child: Icon(Icons.broken_image, size: 48));
  },
)

Always provide an errorBuilder for network images. Networks fail, URLs break, and the default failure in a release build is an empty box. For a gentle fade-in, use FadeInImage or frameBuilder.

On Android, the INTERNET permission must be declared in the main AndroidManifest.xml; debug builds get it automatically, so a missing entry shows up only in release builds. Check it first if images load in debug but not in release. On the web, the image server must allow cross-origin use in some renderers.

Other sources

Image.memory(bytes) shows bytes you already have (for example from the camera or an API), Image.file(File) shows a file on disk (not on the web), and Image.asset covers everything bundled. For a decorative background, use DecorationImage in a BoxDecoration:

DART
Container(
  height: 180,
  decoration: const BoxDecoration(
    image: DecorationImage(
      image: AssetImage('assets/images/hero.jpg'),
      fit: BoxFit.cover,
    ),
  ),
)

Resolution-aware images

Phones have different pixel densities: a 2.0x screen packs two physical pixels per logical pixel. If you ship one small picture it looks blurry on dense screens; one huge picture wastes memory on others. Flutter supports variants in sibling folders named by scale:

TEXT
assets/images/logo.png        <- 1.0x (the main asset)
assets/images/2.0x/logo.png
assets/images/3.0x/logo.png

You declare and request only assets/images/logo.png. Flutter picks the variant closest to the device pixel ratio. Only the main file needs to be listed; the variants are found automatically.

JS Which variant gets picked?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line is the practical lesson: with only one file, every device uses it. On a dense screen it is scaled up and looks soft.

Custom fonts

Fonts follow the same pattern: files in your project, declared in pubspec.yaml.

YAML
flutter:
  fonts:
    - family: Merriweather
      fonts:
        - asset: assets/fonts/Merriweather-Regular.ttf
        - asset: assets/fonts/Merriweather-Bold.ttf
          weight: 700
        - asset: assets/fonts/Merriweather-Italic.ttf
          style: italic

Use the family by name:

DART
const Text(
  'Slow-cooked stew',
  style: TextStyle(fontFamily: 'Merriweather', fontWeight: FontWeight.w700),
)

To use a font everywhere, set fontFamily in ThemeData (Themes, colors and dark mode). Check each font's license before bundling it. The google_fonts package can download fonts at run time, which is quick for prototypes but needs the network on first use. For production, bundle the font files so text appears instantly and works offline.

The google_fonts package

google_fonts gives you hundreds of open-licensed families from fonts.google.com without writing a fonts: block. Each family is a method that returns a TextStyle:

DART
Text('Welcome', style: GoogleFonts.lora(fontSize: 28, fontWeight: FontWeight.w700));

// Whole app: apply a family to an entire text theme
ThemeData(
  textTheme: GoogleFonts.interTextTheme(Theme.of(context).textTheme),
)

On first use, the package downloads the font file, saves it on the device, and reuses the cached copy afterward. Text renders in a fallback font for a moment, then switches, and without a connection on the very first run it stays in the fallback. That is why production apps often turn off runtime fetching and bundle the files:

DART
void main() {
  GoogleFonts.config.allowRuntimeFetching = false;   // use only bundled files
  runApp(const MyApp());
}

Download the .ttf files and put them in an asset folder named in pubspec.yaml (for example assets/google_fonts/). The package finds them by file name, and the name must be Family-Variant.ttf, where the variant is the weight name, plus Italic for italic styles. A wrong name means a silent fallback to the network.

JS Which file name does google_fonts look for?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other points to weigh: bundling many weights adds megabytes, so ship only those you use; each font has its own license (most Google Fonts use the SIL Open Font License, which allows app use but check the font's page); runtime fetching sends a request to Google's servers, which matters for privacy rules in some regions; and await GoogleFonts.pendingFonts([...]) lets you wait for specific fonts before showing a screen that must not flicker.

Icons

You already used Icon(Icons.search). These come from the Material icon font bundled with the framework (enabled by uses-material-design: true). Release builds remove icons you do not use (icon tree shaking), which keeps the app small. Because of this, build icon data from a constant, not from a dynamic code point at run time.

DART
const Icon(Icons.favorite, color: Colors.red, size: 28, semanticLabel: 'Favorite')

For other icon sets, use a package such as font_awesome_flutter, or your own SVGs.

SVG and vector images

Flutter has no built-in SVG widget. The common choice is the flutter_svg package:

YAML
dependencies:
  flutter_svg: ^2.0.0
DART
import 'package:flutter_svg/flutter_svg.dart';

SvgPicture.asset(
  'assets/images/leaf.svg',
  width: 64,
  colorFilter: const ColorFilter.mode(Color(0xFF2E7D32), BlendMode.srcIn),
)

SVG stays crisp at any size and is tiny for simple shapes. It is parsed at run time, so very complex files with filters can be slow or only partly supported. For anything you draw yourself, see CustomPaint and Canvas.

Image caching and memory

Flutter keeps decoded images in an in-memory ImageCache (by default about 100 MB and 1000 images). The second time you show the same image, it comes from memory. Image.network caches only in memory for the current session; for a disk cache that survives restarts, use cached_network_image.

Big photos are the most common cause of memory trouble. A 4000x3000 photo decoded in full takes about 48 MB of RAM (4000 x 3000 x 4 bytes), even if you show it in a 100-pixel thumbnail. Tell Flutter to decode smaller:

DART
Image.network(
  url,
  width: 100,
  height: 100,
  cacheWidth: 200,      // decode at 200 px wide (2x of 100 for sharpness)
  fit: BoxFit.cover,
)

You can also warm the cache before a screen opens with precacheImage(const AssetImage('assets/images/hero.jpg'), context).

JS A size-limited image cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The big photo evicts everything, even itself, so it can never be reused. Decoding it at thumbnail size with cacheWidth would keep the cache useful.

Common mistakes

  • File exists but is not declared in pubspec.yaml: runtime error "Unable to load asset".
  • Wrong path or case. Paths are case-sensitive on Android and Linux even if your PC is not.
  • Folder entries do not include subfolders.
  • Skipping the full restart after changing assets or fonts.
  • No errorBuilder on network images, and huge images shown in tiny boxes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file is in assets/images/ but Image.asset throws 'Unable to load asset'. What is the most likely cause?

    Only declared assets are bundled. Add the path or the folder (ending in /) to pubspec.yaml and restart.
  2. 2. Which BoxFit fills the whole box and crops the overflow?

    cover scales the image until it fills the box, cropping what does not fit. fill would distort it instead.
  3. 3. Where do you put a 2.0x version of assets/images/logo.png?

    Variants sit in sibling folders named by scale, such as 2.0x and 3.0x. You still refer to the main path.
  4. 4. Why should network images have an errorBuilder?

    Networks and URLs fail. errorBuilder lets you show a placeholder or retry button.
  5. 5. What does cacheWidth on an Image do?

    cacheWidth asks Flutter to decode the image at that pixel width, so a big photo shown as a thumbnail does not hold its full decoded size in memory.

Summary

  • Declare every asset (or folder, ending in /) in pubspec.yaml, run flutter pub get, then fully restart.
  • Image.asset, Image.network, Image.memory and Image.file cover the sources; use fit and a size, and add loadingBuilder and errorBuilder for the network.
  • Scale folders (2.0x, 3.0x) give sharp images on dense screens.
  • Fonts are declared under flutter: fonts: and used through fontFamily; bundle fonts for production.
  • Use flutter_svg for SVG and Icons.* for the built-in icon font.
  • Flutter caches decoded images in memory; decode big pictures at display size with cacheWidth.

Next: Tabs: TabBar, TabBarView and PageView