Summary

In this lesson we'll cover: adding images using Image, working with image assets in Flutter and controlling image size and layout using BoxConstraints.

The Code for This Lesson

Check out the tourismandco repo's step/step03 branch for the code we'll cover in this lesson.

Adding an Image

  • Based on our screenshot, let's add a banner image to our screen.
  • To keep the code for our Location Detail screen, let's create a new StatelessWidget that accepts a parameter of a file path to an asset.
  • Note that typically, images should be loaded from a URL, so we'll do that in a later video.

Adding Image Assets to a Flutter Project

  • Create a new directory called assets/images.
  • Copy the asset .jpg file located at assets/images in the step/step03 branch of this repo and copy it to our new directory.
  • Finally, we need to update our Flutter configuration so it knows about the new directory:
# pubspec.yaml

flutter:

  # ...

  assets:
   - assets/images/

  # ...
  • Make sure you don't forget to include the trailing / at the end of the path.
  • Also be careful of the indentation or else Flutter won't be able to interpret this file. Each indentation should be 2 spaces. Checkout the yaml website for more information.

Implementing our ImageBanner Widget

  • We can use the Image widget.
  • asset() is what's called a "named constructor".
  • The fit parameter allows us to control how the image is resized based on the parent Container. Many of the options work the same way as CSS so it may be familiar to you.
// location_detail/image_banner.dart

import 'package:flutter/material.dart';

class ImageBanner extends StatelessWidget {
  final String _assetPath;

  ImageBanner(this._assetPath);

  @override
  Widget build(BuildContext context) {
    return Container(
        constraints: BoxConstraints.expand(height: 200.0),
        decoration: BoxDecoration(color: Colors.grey),
        child: Image.asset(
          _assetPath,
          fit: BoxFit.cover,
        ));
  }
}
  • We can specify a height using BoxConstraints

Using Our ImageBanner Widget

// location_detail/location_detail.dart

import 'package:flutter/material.dart';
import 'image_banner.dart';
import 'text_section.dart';

class LocationDetail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location Detail'),
      ),
      body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            ImageBanner("assets/images/kiyomizu-dera.jpg"),
            TextSection(Colors.red),
            TextSection(Colors.green),
            TextSection(Colors.blue),
          ]),
    );
  }
}

Conclusion

Working with images is pretty easy as you can see. Later we will use proper image URLs instead of actual files. Files aren't recommended as they can bloat the final app size.