Flutter Default Image Placeholder

Viewed 4550

In my data i have posts, but some having image urls and others have false value, while displaying i want to show the placeholder where value are false

Here is my code :

     child: FadeInImage(
  placeholder: AssetImage('assets/images/placeholder.png'),
  image: NetworkImage(posts[index].featuredImage.large ) == null ? 
   Image.asset('assets/images/placeholder.png') : NetworkImage(posts[index].featuredImage.large ),
  fit: BoxFit.cover,
),
2 Answers

You don't need to wrap the condition posts[index].featuredImage.large in a NetworkImage widget.

Just check if the string coming from the API is null, then set the default Image as Image.asset('assets/images/placeholder.png') and if it is not null set the Image as NetworkImage(posts[index].featuredImage.large ).

Try the code below:

FadeInImage(
          placeholder: AssetImage('assets/images/placeholder.png'),
          image: posts[index].featuredImage.large  == null ?
          Image.asset('assets/images/placeholder.png') : NetworkImage(posts[index].featuredImage.large ),
          fit: BoxFit.cover,
        ),

This how you can do it

child: post[index].url==false? Image.assets('assets/images/placeholder.png'): FadeInImage(
fit: BoxFit.cover,
  placeholder: AssetImage('assets/images/placeholder.png'),
  image: posts[index].featuredImage.large == null ? 
   Image.asset('assets/images/placeholder.png') : NetworkImage(posts[index].featuredImage.large ),
),

But there will be an issue here if your url is declared as String since false is not a String and comparing different data type is not a good idea . Then you will have to check RuntimeType

E.g: post[index].url is String//true if url is a String

Related