1

I want a fallback asset image if the asset image I'm trying to access can't be loaded.

If this code: Image(image: AssetImage('images/myImage.png')) throws an error, I would like to display a fallback, for example Image(image: AssetImage('images/fallbackImage.png'))'.

I read through this article on medium but that didn't work for me. With the custom Asset Bundle, not even the existing images got loaded.

MendelG
  • 14,885
  • 4
  • 25
  • 52
Boothosh81
  • 387
  • 1
  • 5
  • 24

1 Answers1

3

You can use the errorBuilder property:

A builder function that is called if an error occurs during image loading.

In your case (null safe):

Image(
      image: AssetImage('path/to/image.jpg'),
      errorBuilder:
          (BuildContext context, Object exception, StackTrace? stackTrace) {
        return Image(
            image: AssetImage('path/to/fallback.jpg'));
      },
    )

Here is a complete example taken straight from the documentation:


import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: Scaffold(
        body: Center(
          child: MyStatelessWidget(),
        ),
      ),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Image.network(
        'https://example.does.not.exist/image.jpg',
        errorBuilder:
            (BuildContext context, Object exception, StackTrace? stackTrace) {
          // Appropriate logging or analytics, e.g.
          // myAnalytics.recordError(
          //   'An error occurred loading "https://example.does.not.exist/image.jpg"',
          //   exception,
          //   stackTrace,
          // );
          return const Text('ð¢');
        },
      ),
    );
  }
}
MendelG
  • 14,885
  • 4
  • 25
  • 52