首页 > 解决方案 > 管理飞镖中的异常

问题描述

我正在尝试从互联网上获取图像,并显示个人资料照片。如果显示图片时出现错误(可能该位置不存在),我想显示一个股票图标。

我的代码:

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;
}
}

但是,即使使用 try-catch 块,我也会遇到异常,并且我的图标没有显示。为什么会这样?

════════ 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)
════════════════════════════════════════════════════════════════════════════════════════════════════

标签: flutterexceptiondart

解决方案


请注意,有一行写着“图像资源服务捕获的异常”:该异常已被捕获。

要检测错误,您需要使用ImageProvider.resolve获取ImageStream,然后使用ImageStream.addListener注册ImageStreamListener. ImageStreamListener允许您指定onError在图像加载失败时将调用的回调。


推荐阅读