how to show default image if image from firebase is null in flutter?

Viewed 1030

I'm using this below code to show avatar image from firebase. If image data from firebase is null the app will be error. My question is how to put default image like person.jpg from my asset folder to this code?

Stack(
              children: [
                CircleAvatar(
                  backgroundColor: kDarkGreenColor.withOpacity(0.5),
                  radius: 60.0,
                  backgroundImage:
                      NetworkImage(snapshot.data.data()['userimage']),
                ),
                Positioned(
                    top: 90.0,
                    left: 90.0,
                    child: Icon(FontAwesomeIcons.plusCircle,
                        color: kWhiteColor))
              ],
            ),
2 Answers

Using the ?? and another URL, you can easily do this.

Something like:

NetworkImage(snapshot.data.data()['userimage'] ?? "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png"),

You have multiple solutions:

  1. Add a simple condition with another url:
Stack(
  children: [
    CircleAvatar(
      backgroundColor: kDarkGreenColor.withOpacity(0.5),
      radius: 60.0,
      backgroundImage:
          NetworkImage(snapshot.data.data()['userimage'] ?? 'image_url_when_its_null'),
    ),
    Positioned(
        top: 90.0,
        left: 90.0,
        child: Icon(FontAwesomeIcons.plusCircle,
            color: kWhiteColor))
  ],
),
  1. Add a condition to shown a custom asset image:
Stack(
  children: [
    CircleAvatar(
      backgroundColor: kDarkGreenColor.withOpacity(0.5),
      radius: 60.0,
      backgroundImage: 
       snapshot.data.data()['userimage'] != null 
         ? NetworkImage(snapshot.data.data()['userimage'])
         : AssetImage('path/to/asset'),
    ),
    Positioned(
        top: 90.0,
        left: 90.0,
        child: Icon(FontAwesomeIcons.plusCircle,
            color: kWhiteColor))
  ],
),
Related