0

I'm using Flutter's CircleAvatar with a backgroundImage property to display a network image. However, I want to implement a fallback mechanism, so that if the network image fails to load , it should display a local image stored on my computer.

I believe using an if-else statement can solve this problem, but I'm struggling to figure out how to implement it properly. Could someone please guide me on how to achieve this behavior?

 drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
      const DrawerHeader(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        // child: Text('Drawer Header'),
        child: CircleAvatar(
          radius: 40,
          backgroundImage: NetworkImage('https://~~'),
        ),
      ),
Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
Hyun Kim
  • 5
  • 2

1 Answers1

0

Instead of NetworkImage, you can use Image.network, which has an errorBuilder property.

So, instaed of:

CircleAvatar(
          radius: 40,
          backgroundImage: NetworkImage('https://~~'),
        ),

Use:

CircleAvatar(
      child: Image.network(
        'https://placehold.co/600x400.png',
        errorBuilder: (context, error, stackTrace) {
          return  Image.asset('/assets/images/placeholder.png');
        },
      ),
    );

See also

MendelG
  • 14,885
  • 4
  • 25
  • 52