Ram*_*aha 10 try-catch conditional-operator networkimageview flutter-dependencies flutter-layout
我已经获取网络图像并使用三元运算符,我可以在其中显示网络图像,但无法显示默认资产图像,其中网络图像在网格中默认图像无效,也如此-
\n我是颤振新手
\n image: NetworkImage(products[index]\n .productImageList[0]\n )!= null\n ? NetworkImage(\n products[index].productImageList[0])\n :Image.asset("assets/defimg.jpg"),\n fit: BoxFit.fitHeight ),\nRun Code Online (Sandbox Code Playgroud)\n它在索引 0 上显示网络图像,但不会加载网络图像无效或为空的资产图像并抛出此错误 -
\n\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90 Exception caught by image resource service \xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\nThe following _Exception was thrown resolving an image codec:\nException: Invalid image data\n\nWhen the exception was thrown, this was the stack: \n#0 _futurize (dart:ui/painting.dart:5230:5)\n#1 ImageDescriptor.encoded (dart:ui/painting.dart:5098:12)\n#2 instantiateImageCodec (dart:ui/painting.dart:1998:60)\n<asynchronous suspension>\nRun Code Online (Sandbox Code Playgroud)\n之后我尝试了 try/catch -我的 try catch 代码是 --
\nchild: Builder(builder: (BuildContext context) {\n try {\n return Center(\n child: Image.network(\n products[index]\n .productImageList[0],\n fit: BoxFit.contain,\n ),\n );\n } catch (e) {\n print("Got exception ${e.toString()}");\n return Image.asset("assets/defimg.jpg", fit: BoxFit.contain);\n }\n }),\n\nRun Code Online (Sandbox Code Playgroud)\n给我与上面相同的错误..
\n图像响应来自列表“productImageList”中的 api,如下所示 --
\n "sellingPrice": "4000",\n "productImageList": [\n "https://www.xyzz.com/postadsimages/img/23682201.jpg"\n ],\n "createdDate": 1607754473000,\n\nRun Code Online (Sandbox Code Playgroud)\n
小智 10
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;
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以处理无效图像数据异常,并在仍在获取网络图像时显示另一张图像。
PS:如果您想在加载资源后获得淡入淡出效果,也可以使用FadeInImage.assetNetwork 。