Joel G Mathew
Joel G Mathew

Reputation: 8061

Managing exception in dart

I'm trying to fetch an image from the internet, and display a profile photo. If there is an error while displaying the pic (maybe it doesnt exist at that location), I want to display a stock icon.

My code:

class AvatarWidget extends StatelessWidget {
const AvatarWidget({
    Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
    return ClipOval(
    child: CircleAvatar(
        child: ProfilePicWidget(),
        radius: 70,
        backgroundColor: Colors.grey,
    ),
    );
}
}

class ProfilePicWidget extends StatelessWidget {
const ProfilePicWidget({
    Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
    Widget profilePic;
    try {
    profilePic = Image(
        image: NetworkImage(profileLink),
    );
    } catch (e) {
    profilePic = Icon(FontAwesomeIcons.userCircle);
    }
    return profilePic;
}
}

However even with a try-catch block, I'm getting an exception, and my icon isnt displaying. Why is it so?

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 404, http://google.com/data/data/media/2020/05/01/images_1_4CDIfHK.thumbnail.jpeg

When the exception was thrown, this was the stack: 
#0      NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:97:9)
<asynchronous suspension>
#1      NetworkImage.load (package:flutter/src/painting/_network_image_io.dart:49:14)
#2      ImageProvider.resolveStreamForKey.<anonymous closure> (package:flutter/src/painting/image_provider.dart:501:13)
#3      ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:359:22)
...
Image provider: NetworkImage("http://google.com/data/data/media/2020/05/01/images_1_4CDIfHK.thumbnail.jpeg", scale: 1.0)
Image key: NetworkImage("http://google.com/data/data/media/2020/05/01/images_1_4CDIfHK.thumbnail.jpeg", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════

Upvotes: 0

Views: 263

Answers (2)

jamesdlin
jamesdlin

Reputation: 89955

Note that there's a line that says "Exception caught by image resource service": the exception was already caught.

To detect the error, you will need to use ImageProvider.resolve to obtain the ImageStream and then use ImageStream.addListener to register an ImageStreamListener. The ImageStreamListener allows you to specify an onError callback that will be invoked if the image fails to load.

Upvotes: 1

Windsor_Elliot
Windsor_Elliot

Reputation: 96

it's because NetworkImage catch and show the error before your try catch, if you want to catch the get Image error, you should directely get the data of image with a get request not with the NetworkImage

Upvotes: 0

Related Questions