At this point, you have a course detail page with just a course title on it. As you can see, it needs a little work. You’re going to show the course image at the top of the course detail screen.
In order to make the code a little cleaner, you’re going to encapsulate the image you want to show into an image widget called ImageContainer. The ImageContainer will extract showing the image and grabbing the course image from the network using a NetworkImage.
This container is composed of a few other widgets which goes to show you how cool Flutter is. We’re creating new functionality by using existing widget combinations. In such perspective, you can think of Widgets like lego bricks that snap together in an infinite amount of ways.
To get started, open your project in progress or download the starter project for this episode. In the ui course_detail folder, Create a file called image_container.dart. Create a new StatelessWidget called ImageContainer
class ImageContainer extends StatelessWidget {
}
Make sure to import the material library by selecting the StatelessWidget and press Command-. on macOs or Control-. on windows. The class needs four properties, width, height, a color for showing a placeholder background, and the url of the image to load, which we’ll pass in as the Course artworkUrl.
final double? width;
final double? height;
final Color placeholder;
final String url;
Next replace the existing constructor with a constructor that initializes all of the fields.
const ImageContainer(
{Key? key,
this.width,
this.height,
this.placeholder = const Color(0xFFEEEEEE),
required this.url})
: super(key: key);
Now we need to update the build method for the widget, that will use a BoxDecoration, DecorationImage, and NetworkImage inside a Container widget. First, we’ll set the width and height of the container.
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
);
}
Next add a BoxDecoration. A BoxDecoration is a way to draw a box. It uses the placeholder color as a background, which will show while the image is downloading. The box is drawn in layers, and the colors the bottom most layer.
decoration: BoxDecoration(
color: placeholder,
image:
),
The image of a box shows on top of the color, and has alignment controlled by a DecorationImage.
image: url.contains('http')
? DecorationImage()
: null),
We can use the DecorationImage to control how the image fits inside the box, and here we use the default settings.
image: url.contains("http")
? DecorationImage(image: NetworkImage(url))
: null),
We do some error checking on the url to make sure it’s valid, and if so use a NetworkImage to grab the image from the url. Otherwise the background color is shown by setting the image on the box to null.
Ok, with your ImageContainer class in place, next up we’ll utilize the new class to complete the course details screen.