cft

How To Use Images In Flutter — To The Point

A guide on showing how to work with images in Flutter.


user

Pinkesh Darji

3 years ago | 5 min read

There is hardly any app that doesn’t use the images at all because sometimes an image can convey complex things in an easy manner. So if you fell in love with Flutter and just getting started this article is for you.

👇 Things that we are going to cover in this article

  1. How to add images?
  2. How to load and show Images from the Internet?
  3. How to display a placeholder image when the image is loading?
  4. How to preload images?
  5. How to set the image as background?
  6. How to stretch/fit/scale an image?
  7. How to display any Image in Circle?

1) How to add and show images?

Step 1: Create an assets/images folder.

Step 2: Add the actual image in the folder we created.

Step 3: Add the assets folder in pubspec.yaml

Step 4: Showing the image using an Image.asset() widget.

Center(
child: Image.asset('assets/images/bike.png'),
)

2) How to load and show Image from the Internet

It's really easy. Just replace Image.asset() with Image.network() like this.

Center(
child: Image.network('https://picsum.photos/id/237/200/300'),
)

One Tip for you ⭐️

You can use the same widget to display the GIF.

Center(
child: Image.network(
'https://media.giphy.com/media/65LrvAMGU650TvPgs5/giphy.gif?raw=true'),
)

3) How to display a placeholder image when the image is loading.

Sometimes when you load an image, it takes little time to actually get visible. Its always a good option to show something interesting while the image is being loading just like a placeholder and then just FadeIn the actual image to improve the UX.

Good news: Flutter has covered the widget for that too! 😎

FadeInImage.assetNetwork(
placeholder: 'assets/images/placeholder.png', // Before image load
image: 'https://picsum.photos/id/237/200/300', // After image load
height: 200,
width: 300,
)

This allows us to show a placeholder image from local and display the actual image from the internet.

We can also use the GIF instead of the static image like this…

FadeInImage.assetNetwork(
placeholder: 'assets/images/loading.gif',
image: 'https://picsum.photos/id/237/200/300',
height: 200,
width: 300,
)

4) How to preload images?

We all hate to wait. Right?

When the user opens the app, The first few seconds are very crucial. It can decide the make or break of the app. No matter how well you coded it. So in terms of improving the initial performance of the app, you can preload the images as soon as the app loads.

Step 1: Create a class AppImages.

class AppImages {
static const String imagesPath = "assets/images/";
static const String bike = imagesPath + "bike.png";
}

Step 2: Create an Image widget from assets.

Image myImage;

@override
void initState() {
// TODO: implement initState
super.initState();
myImage = Image.asset(AppImages.bike);
}

Step 3: Calling a Function to prefetch image.

@override
void didChangeDependencies() {
super.didChangeDependencies();
precacheImage(myImage.image, context);
}

Calling the precacheImage(myImage.image, context) inside didChangeDependencies function. We should actually call it inside initState() to prefetch image as early as possible but initState() doesn’t have access to context and didChangeDependencies has.

The difference between initState() and didChangeDependencies()

However both of them are called before build is called. Only difference is that initState() is called before the state loads its dependencies and didChangeDependencies() is called a few moments after the state loads its dependencies. Hence it has the context.

Step 4: Display the image as we do normally.

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Image.asset(AppImages.bike)),
);
}

That’s it. You are done.

Note: You will better find the difference in the release mode.

5) How to set an image as a background?

The idea is to use a container as you would use normally and just set the decoration property of it.

============ BEFORE =================


Container(
height: 300,
width: 300,
child: Center(
child: Text(
'BIKE',
style: TextStyle(
fontSize: 95, color: Colors.black, fontWeight: FontWeight.bold),
)),
)

============ =AFTER ===================

Container(
height: 300,
width: 300,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bike.png"), fit: BoxFit.cover),
),
child: Center(
child: Text(
'BIKE',
style: TextStyle(
fontSize: 95, color: Colors.black, fontWeight: FontWeight.bold),
)),
)

6) How to stretch/fit/scale an image?

We will use the above example and will try to load the image from the internet to see how you can stretch/shrink/scale any image to fit according to your need.

Here is the starter code…

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 300,
width: 300,
decoration: BoxDecoration(
color: Colors.greenAccent,
image: DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300')),
),
),
),
);
}

and the output is…

Container size = 300w * 300h

Image size = 200w * 300h

And the default BoxFit property of the DecorationImage is BoxFit.scaleDown which aligns the image in the center and if required it can also shrink the image(Keeping it proportional) to make it fully visible. Hence we are seeing some empty space (Green colored part of the container) horizontally in the output.

BoxFit.scaleDown example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_scaleDown.png

Here are some other options you can try.

BoxFit.cover

As small as possible while still covering the entire container.

BoxFit.cover example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_cover.png

DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300'),
fit: BoxFit.cover)

BoxFit.fill

Fill the container by distorting the image’s aspect ratio.

BoxFit.fill example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_fill.png

DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300'),
fit: BoxFit.fill)

BoxFit.contain

As large as possible while still containing the image entirely in container.

BoxFit.contain example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_contain.png

Container(
height: 500,
width: 300,
decoration: BoxDecoration(
color: Colors.greenAccent,
image: DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300'),
fit: BoxFit.contain),
),
)

BoxFit.fitHeight

It tries to show the full height of the image, and does not care about the width even if the image gets clipped horizontally.

BoxFit.fitHeight example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_fitHeight.png

Container(
height: 300,
width: 100,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300'),
fit: BoxFit.fitHeight),
),
)

BoxFit.fitWidth

It tries to show the full width of the image, and does not care about the height even if the image gets clipped vertically.

BoxFit.fitWidth example from: https://flutter.github.io/assets-for-api-docs/assets/painting/box_fit_fitWidth.png

Container(
height: 100,
width: 300,
decoration: BoxDecoration(
color: Colors.greenAccent,
image: DecorationImage(
image: NetworkImage('https://picsum.photos/id/237/200/300'),
fit: BoxFit.fitWidth),
),
)

7) How to display any Image in Circle?

We may probably want to show the user’s profile image in a circle and there are various ways to do it. Here I will mention the simplest one.

From local

CircleAvatar(
backgroundImage: AssetImage("assets/images/bike.png"),
radius: 100,
)

From API (Internet)

Instead of AssetImage(“assets/images/bike.png”) Just use NetworkImage(“https://picsum.photos/id/237/200/300”)

CircleAvatar(
backgroundImage: NetworkImage("https://picsum.photos/id/237/200/300"),
radius: 100,
)

That’s it. I hope you have learned something new from this article.

Upvote


user
Created by

Pinkesh Darji

I love to solve problems using technology that improves user’s life on a major scale. Over the last several years, I have been developing and leading various mobile apps in different areas. More than just programming, I love to write technical articles. I have written many high-quality technical articles. I have worked with various startups to build their dream app. I have been involved in product development since my early days and know insights into it. I have provided my valuable input while taking some crucial decisions of the app by brainstorming with a design, QA team. For the last 2.5 years, I have been developing mobile apps and libraries using Google’s Flutter framework. I mentor junior Flutter developers and review their code. You will also find me talking on various Flutter topics in local meetups. LinkedIn: https://www.linkedin.com/in/pinkesh-darji-flutter/ Github: https://github.com/pinkeshdarji Twitter: https://twitter.com/PinkeshDarji


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles