FadeInImage.assetNetwork 需要绝对路径。占位符的相对路径不起作用。 (颤抖)

FadeInImage.assetNetwork requires absolute path. Relative path for placeholder is not working. (in flutter)

我正在通过 FadeInImage.assetNetwork 显示图像,这需要两个成员:imageplaceholder

    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/