【发布时间】:2020-05-01 06:44:00
【问题描述】:
我正在尝试从互联网上获取一张图片,并显示一张个人资料照片。如果显示图片时出现错误(可能该位置不存在),我想显示一个股票图标。
我的代码:
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)
════════════════════════════════════════════════════════════════════════════════════════════════════
【问题讨论】:
-
如果您转到您提供给 NetworkImage 小部件的 url,它不会打开。尝试使用有效的网址。
-
我没有发布原始网址。假设 url 不起作用,并且发生错误.. 我试图捕捉错误,但它不起作用。我的问题是为什么我的错误处理不起作用