问题描述
我通过 FadeInImage.assetNetwork
显示图像,这需要两个成员:image
和 placeholder
。
ClipRRect( //forcing image to rounded corners
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15),topRight: Radius.circular(15),),child: FadeInImage.assetNetwork(
image: imageUrl,placeholder: '/Users/aayush/Documents/Flutter/Apps/meals_app/assets/images/food-placeholder.png',//here full path is necessary. relative path is not working.
// placeholder: '../../assets/images/food-placeholder.png',//this relative path is not working.
height: 250,width: double.infinity,fit: BoxFit.cover,//will resize and crop the image
),
这是我的文件夹结构:
目前我在 lib/widgets/meal_item.dart
,占位符图像位于 assets/images/food-placeholder.png
。
所以,我的相对路径将是: ../../assets/images/food-placeholder.png
。
当我尝试在此处使用相对路径时的错误消息:
════════ Exception caught by image resource service ════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: ../../assets/images/food-placeholder.png
When the exception was thrown,this was the stack
#0 PlatformAssetBundle.load
package:Flutter/…/services/asset_bundle.dart:224
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync
package:Flutter/…/painting/image_provider.dart:672
<asynchronous suspension>
Image provider: Assetimage(bundle: null,name: "../../assets/images/food-placeholder.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#df521(),name: "../../assets/images/food-placeholder.png",scale: 1.0)
我尝试了很多次,但它不仅在这个小部件中有效。相对路径在其他小部件中完美运行。 请为此提供解决方案或建议,以便我可以显示占位符图像,直到获取 url 图像为止。
解决方法
您必须在 Pubspec.yaml
文件中指定图像位置。
这就是您向 Flutter 项目添加资产的方式。
- 之后,您可以使用如下图像:
FadeInImage.assetNetwork(
image: imageUrl,placeholder: 'assets/images/food-placeholder.png',height: 250,width: double.infinity,fit: BoxFit.cover,),
将图像路径添加到发布规范后,您必须停止当前正在运行的会话,然后重建或重新运行应用程序。
- 试试这个命令。
flutter clean
flutter pub get
flutter run
,
对于相对路径,像这样创建路径
'assets/images/food-placeholder.png'
并确保您像这样在 pubspec.yaml 中的资产中添加了图像路径
assets:
- assets/images/