This guide was originally published on SRF Developer. Check out the blog for visual examples.
An app without images is boring.
In Flutter, showing an image is easy, but managing assets and handling loading errors can be tricky. Today, we master the two most common ways to display images: Network (Internet) and Asset (Local).
🌐 1. Image.network (The Easy Way)
If you have a URL, you can display an image in one line of code.
Image.network(
'[https://picsum.photos/250?image=9](https://picsum.photos/250?image=9)',
width: 300,
height: 200,
fit: BoxFit.cover, // Fills the box without distorting
)
📁 2. Image.asset (The Local Way)
To use images stored inside your app (like a logo), you must declare them in the pubspec.yaml file first.
⚠️ Warning: Indentation Matters!
The pubspec.yaml file is very strict. Two spaces means two spaces.
assets:
- assets/images/logo.png
Then, use the widget:
Image.asset('assets/images/logo.png')
🛡️ 3. Handling Errors (Crucial)
What if the user is offline? You don't want your app to show a crash. Use the errorBuilder.
Image.network(
'[https://broken-link.com/image.png](https://broken-link.com/image.png)',
errorBuilder: (context, error, stackTrace) {
return Icon(Icons.error, color: Colors.red, size: 50);
},
)
Conclusion
Use Image.network for dynamic content and Image.asset for icons/logos.
Want to learn how to cache these images so they load instantly next time? Check out the full Flutter Course on SRF Developer.
Top comments (0)