image - 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;
});
解决方案
你可以在下面这样做。
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,
),
),
推荐阅读
- ios - 沿着 BezierPath 移动 UILabel 一段时间
- cordova-plugins - iOS12.1.2 Phonegap 中创建的应用程序中的键盘问题
- javascript - 如何在 Angular JS 中调用 java FTP 上传文件
- python - python:用户输入以分号作为分隔符加载csv
- r - SQLDF 在来自 R 的 PostgreSQL 查询上失败
- json - 在 jq 中取消嵌套对象时,如何避免在管道中的每个阶段重述标签?
- django - 带有 ModelChoiceField 的 Django ModelForm 似乎不适用于参数
- pyomo - 如何在 Pyomo 的目标函数中添加一个额外的项?
- javascript - uikit modal.find 不是函数
- knex.js - 什么样的粒度更适合迁移?