flutter - 管理飞镖中的异常
问题描述
我正在尝试从互联网上获取图像,并显示个人资料照片。如果显示图片时出现错误(可能该位置不存在),我想显示一个股票图标。
我的代码:
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)
════════════════════════════════════════════════════════════════════════════════════════════════════
解决方案
请注意,有一行写着“图像资源服务捕获的异常”:该异常已被捕获。
要检测错误,您需要使用ImageProvider.resolve
获取ImageStream
,然后使用ImageStream.addListener
注册ImageStreamListener
. ImageStreamListener
允许您指定onError
在图像加载失败时将调用的回调。
推荐阅读
- elasticsearch - 弹性搜索查询优先级
- wordpress - Wordpress 错误消息:编译较少文件时出现问题。对无效类型的操作
- c# - 如何在 Listview 中创建几列?
- c++ - 在 Windows 上构建 webkit 时找不到 CoreFoundation/CoreFoundation.h
- javascript - 如何在反应中拆分地图数组中的值
- javascript - 带有 gsap 的事件监听器
- swift - 登录屏幕 SWIF5 后返回上一个 viewController
- reactjs - chart.js 注释插件 - 多行注释
- kubernetes - 到 Geth pod 的 NodePort 在 k8s 上不起作用
- python - 在 Linux 上从 Bs4 解码数据