In this lesson we'll cover: adding images using Image
, working with image assets in Flutter and controlling image size and layout using BoxConstraints
.
Check out the tourismandco repo's step/step03
branch for the code we'll cover in this lesson.
StatelessWidget
that accepts a parameter of a file path to an asset.assets/images
..jpg
file located at assets/images
in the step/step03
branch of this repo and copy it to our new directory.# pubspec.yaml
flutter:
# ...
assets:
- assets/images/
# ...
/
at the end of the path.ImageBanner
WidgetImage
widget.asset()
is what's called a "named constructor".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,
));
}
}
BoxConstraints
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),
]),
);
}
}
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.