Updated 28 April 2023
In the article, I will discuss, how to Implement placeholder images in the custom image widget.
For this, I will use FadeInImage widget to handle placeholder images. This FadeInImage widget, displays a placeholder image before requesting an image from the internet.
Check our Flutter app development page.
Let’s start with the implementation part.
Firstly, I create an ImageView widget that accepts the URL and build the FadeInImage widget.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import 'package:flutter/material.dart'; class ImageView extends StatelessWidget { final String? url; double height; double width; ImageView({Key? key, this.url,this.width = 0.0, this.height = 0.0}) : super(key: key); @override Widget build(BuildContext context) { print(url); return FadeInImage( placeholder: const AssetImage('assets/images/placeholder.png'), image: NetworkImage(url ?? ''), imageErrorBuilder:(context, error, stackTrace) { return Image.asset('assets/images/placeholder.png', width: width != 0.0 ? width : null, height: height != 0.0 ? height : null); }, fit: BoxFit.cover, width: width != 0.0 ? width : null,height: height != 0.0 ? height : null ); } } |
Here i have use 2 extra params that accept image height and width which manage image according to the given size.
You can also use the memoryNetwork to access transparent_image package.This package exports one constant: kTransparentImage which is a simple transparent image. To know more about transparent_image package please click here.
1 2 3 4 |
FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: 'image url', ); |
Now call this imageview widget in code where we want to show image.
1 |
ImageView(url:"image Url String",width:MediaQuery.of(context).size.width,height:MediaQuery.of(context).size.width) |
Here is the output:
Note: Make sure you added the asset to the project’s pubspec.yaml file.
1 2 3 |
flutter: assets: + - assets/ |
Reference links:
https://docs.flutter.dev/cookbook/images/fading-in-images
https://pub.dev/packages/transparent_image
In conclusion, I hope this code will help you better to understand implement the placeholder image with custom image widget flutter. If you feel any doubt or query please comment below.
Thanks for the read this blog and if you want to visit my other blog click here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.