Adding Images

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

Adding Image Assets to a Flutter Project

# pubspec.yaml

flutter:
  
  # ...

  assets:
   - assets/images/

  # ...

Implementing our ImageBanner Widget

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

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.