Flutter how to handle Image.network error (like 404 or wrong url)

痴心易碎 提交于 2020-12-25 07:00:15

问题


How to handle Image.network when the url is wrong or the destination leads to 404.

for example try

Image.network('https://image.tmdb.org/t/p/w92')

回答1:


I have handled the network image issue related to 404 by using an errorBuilder.

Image.network('Your image url...',
    errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
        return Text('Your error widget...');
    },
),

errorBuilder property




回答2:


UPDATE: Look at the new accurate way which uses an inbuilt method, answered by @Niraj Phutane here which requires no plugins.


old answer

I recommend using cached_network_image which gives an option to add a placeholder image and also an error widget in case of a 404 or 403.

CachedNetworkImage(
   imageUrl: "http://via.placeholder.com/350x150",
   placeholder: (context, url) => new CircularProgressIndicator(),
   errorWidget: (context, url, error) => new Icon(Icons.error),
),



回答3:


Instead of Network.image use NetworkImageWithRetry

https://pub.dartlang.org/documentation/flutter_image/latest/

Example:

var avatar = Image(
  image: NetworkImageWithRetry('http://example.com/avatars/123.jpg'),
);



回答4:


It's weird but you can't easily handle errors correctly with Image.Provider. Use this handy package: https://pub.dev/packages/flutter_advanced_networkimage

Then in you code:

backgroundImage: AdvancedNetworkImage(
                    "YOUR IMAGE URL", 
                    fallbackAssetImage: "YOUR DEAULT ASSERT IMAGE eg:assets/default.png"
                  )



回答5:


You can use ImageStream to handle errors.

class CustomProductImage extends StatelessWidget {
  final String image;

  const CustomProductImage({Key key, this.image}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return buildWidget(image);
  }
}

Widget buildWidget(String url) {

  Image image = Image.network(url, width: 50,height: 50,);

  final ImageStream stream = image.image.resolve(ImageConfiguration.empty);

  stream.addListener(ImageStreamListener((info, call) {
      //you can also handle image loading 
      //example: loading = false;//that's mean image is loaded
  },
      onError: (dynamic exception, StackTrace stackTrace) {
//    print('enter onError start');
//    print(exception);
//    print(stackTrace);
//    print('enter onError end');     
     
   }));

  return image;
}



回答6:


I use it like

String url =
    "https://images.unsplash.com/photo-15856192219-dd823a86ebc5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3334&q=80";
try {
    return CachedNetworkImage(
        useOldImageOnUrlChange: true,
        imageUrl: url,
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) {
            return Image(
                image: AssetImage(imageLocation),
            );
        },
    );
} catch (e) {
    return Image(
        image: AssetImage(imageLocation),
    );
}

Used catch just to be safe.

P.S: you may have to declare an instance of CachedNetworkImage




回答7:


I had the same problem, but, I solved it using the property 'imageErrorBuilder' of the FadeInImage class.

Here is a link about that: https://api.flutter.dev/flutter/widgets/Image/errorBuilder.html

The example was made for Image.network(), but it also work for FadeInImage.

Here's my code:

FadeInImage(
  imageErrorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
    print('Error Handler'); 
    return Container(
      width: 100.0,
      height: 100.0,
      child: Image.asset('assets/img/no_disponible.jpg'),
    );
  },
  placeholder: AssetImage('assets/img/loading.gif'), 
  image: NetworkImage(product.getImg()),
  fit: BoxFit.cover,
  height: 100.0,
  width: 100.0,
), 

The function of imageErrorBuilder will be execute for example, if the direction of the page doesn't exist.

I'm using Flutter 1.20.1



来源:https://stackoverflow.com/questions/52568872/flutter-how-to-handle-image-network-error-like-404-or-wrong-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!