【问题标题】:Flutter load image asset with image fileFlutter 使用图像文件加载图像资产
【发布时间】:2021-03-30 22:10:49
【问题描述】:

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

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

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;
});

【问题讨论】:

    标签: image file flutter path assets


    【解决方案1】:

    你可以在下面这样做。

    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,
             ),
           ),
    

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 2019-09-13
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2021-11-23
      • 2021-06-21
      • 2019-08-27
      相关资源
      最近更新 更多