首页 > 解决方案 > Flutter 使用图像文件加载图像资源

问题描述

我有一个页面允许用户发布一些东西,其中包括一张图片。当页面加载时,它会加载一个default.png图像,当用户单击它时,用户会被重定向到另一个页面,他们可以在其中拍照或从图库中选择。

这里的主要问题是,当my post an item page加载它时,它会查看Image.asset并查看为空。因此,Image.asset能够加载defaultImage,但是当用户选择图像或拍照时,返回的值是 aFile并且path附加到它使其成为 a String(如下所示)

child: Image.asset(
                    imageName1?.path ?? defaultImage,
                    fit: BoxFit.cover,
                  ),

所以,Image.asset无法加载这个File.path

这是我得到的错误:

Exception has occurred.
FlutterError (Unable to load asset: /data/user/0/com.flutter_project/cache/image_picker4920072427102948834.jpg)

我知道这Image.file适用于file.path......但我真的需要在某处做一个 if 语句以确保正确的图像显示吗?

有没有更简单的方法?

额外说明:当我在我的视觉工作室中进行刷新时(当我的应用程序正在运行时)图像实际加载(因为它应该)......非常奇怪......我的页面是stateful并且当我通过result(弹出的文件页)我做setstate一个imageName1

final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => PhotoPreviewPage()),
);

setState(() {
imageName1 = result;
});

标签: imagefileflutterpathassets

解决方案


你可以在下面这样做。

File imageName1;

并且一旦您从弹出的路线中获得了图像,并从导航器中获得了选定的图像结果。

final result = await Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => PhotoPreviewPage()),
);

setState(() {
  imageName1 = File(result.path);
});

在构建方法中。

(imageName1 == null)
    ? ClipOval(
       child: SizedBox(
       width: 120.0,
       height: 120.0,
       child: CachedNetworkImage(
         imageUrl: (widget.user.userImg != null) ? widget.user.userImg ?? '' : AssetImages.course,
         placeholder: (context, url) => Center(child: CircularProgressIndicator()),
         errorWidget: (context, url, error) => Image.asset(AssetImages.smallLoader),
         fit: BoxFit.fill,
        ),
      ),
     )
     : ClipOval(
         child: Image.file(
           imageName1,
           width: 120,
           height: 120,
           fit: BoxFit.cover,
         ),
       ),

推荐阅读