在Dart中管理异常 [英] 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.
我的代码:
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块,我也遇到了异常,并且我的图标没有显示.为什么会这样?
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)
════════════════════════════════════════════════════════════════════════════════════════════════════
推荐答案
请注意,有一行显示图像资源服务捕获了异常":该异常已被捕获.
Note that there's a line that says "Exception caught by image resource service": the exception was already caught.
要检测该错误,您将需要使用 ImageProvider.解决
以获得 ImageStream
,然后使用 ImageStream.addListener
来注册
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.
这篇关于在Dart中管理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!