【问题标题】:FadeInImage.assetNetwork requires absolute path. Relative path for placeholder is not working. (in flutter)FadeInImage.assetNetwork 需要绝对路径。占位符的相对路径不起作用。 (颤抖中)
【发布时间】:2021-09-06 15:30:12
【问题描述】:

我正在通过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 图像。

这是完整的屏幕截图:

【问题讨论】:

  • 其实问题出在相对路径上。相对路径应为:assets/images/food-placeholder.png。谢谢大家的回答:)

标签: flutter dart relative-path placeholder absolute-path


【解决方案1】:

对于相对路径,创建这样的路径

 'assets/images/food-placeholder.png'

并确保您已像这样在 pubspec.yaml 中的资产中添加了图像路径

assets:
- assets/images/

【讨论】:

  • 您在pubspec.yaml 中的输入将不起作用,因为您没有在路径中指定资产文件夹。
  • @kishandhankecha 你是对的。我已经更新了答案。
  • 非常感谢!我在写文件路径时犯了一个错误。顺便说一句,我已经在 pubspec.yaml 文件中添加了资产。问题出在相对路径中。
  • 嘿@bilal,如果 url 坏了,你能帮我吗,然后我也想显示占位符图像。我怎样才能做到这一点?在此先感谢:)
  • @AayushShah 就像占位符一样,也为imageError提供图像。
【解决方案2】:

您必须在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

【讨论】:

  • 感谢您的回答!顺便说一句,问题出在相对路径中。
猜你喜欢
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 2013-07-06
  • 2016-04-11
  • 2018-06-04
  • 1970-01-01
  • 2012-01-11
  • 2010-09-15
相关资源
最近更新 更多