我已经获取网络图像并使用三元运算符,我可以显示网络图像,但无法显示网络图像无效的默认资产图像也如此-
我是颤振新手
image: NetworkImage(products[index]
.productImageList[0]
)!= null
? NetworkImage(
products[index].productImageList[0])
:Image.asset("assets/defimg.jpg"),
fit: BoxFit.fitHeight ),
它在索引 0 上显示网络图像,但不会加载网络图像无效或为空的资产图像并抛出此错误 -
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
When the exception was thrown, this was the stack:
#0 _futurize (dart:ui/painting.dart:5230:5)
#1 ImageDescriptor.encoded (dart:ui/painting.dart:5098:12)
#2 instantiateImageCodec (dart:ui/painting.dart:1998:60)
<asynchronous suspension>
在此之后我尝试了 try/catch -我的 try catch 代码是 --
child: Builder(builder: (BuildContext context) {
try {
return Center(
child: Image.network(
products[index]
.productImageList[0],
fit: BoxFit.contain,
),
);
} catch (e) {
print("Got exception ${e.toString()}");
return Image.asset("assets/defimg.jpg", fit: BoxFit.contain);
}
}),
给我与上面相同的错误..
图像响应来自列表“productImageList”中的 api,如下所示 --
"sellingPrice": "4000",
"productImageList": [
"https://www.xyzz.com/postadsimages/img/23682201.jpg"
],
"createdDate": 1607754473000,
Image.network 可以让您处理网络请求的加载和错误状态,但不是您尝试的方式。
我会给你一个应该做什么的例子:
// Just to DRY
final Image noImage = Image.asset("assets/defimg.jpg");
final imageUrl = products[index].productImageList[0];
// Now, in the widget's image property of your first example:
image: (imageUrl != null) // Only use the network image if the url is not null
? Image.network(
imageUrl,
loadingBuilder: (context, child, loadingProgress) =>
(loadingProgress == null) ? child : CircularProgressIndicator(),
errorBuilder: (context, error, stackTrace) => noImage,
)
: noImage;
通过这种方式,您可以处理无效图像数据异常,并在仍在获取网络图像时显示另一张图像。
PS:如果你想在加载资源后有淡入淡出的效果,也可以使用FadeInImage.assetNetwork。
您可以使用cachedNetworkImage代替图像网络。
CachedNetworkImage(
imageUrl:
"https://store4.gofile.io/download/361b6d89-e4a7-4444-a725-a32bdbfefba6/WhatsApp%20Image%202021-11-03%20at%209.38.00%20PM.jpeg",
height: 25.h,
width: 100.w,
fit: BoxFit.fill,
)
或
CachedNetworkImage(
imageUrl: imageURL,
fit: BoxFit.fill,
placeholder: (context, url) => Padding(
padding: EdgeInsets.all(18.0),
child: CircularProgressIndicator(
strokeWidth: 2, color: MyColors.primary),
),
errorWidget: (context, url, error) =>
Icon(Icons.person, color: MyColors.grey),
)
不要使用“CachedNetworkImageProvider”,尝试使用“CachedNetworkImage”来代替