首页 > 解决方案 > Flutter:从 URI 字符串或文件对象显示图像

问题描述

我正在使用 ImagePicker 从我的画廊中提取图像,如下所示:

ImageProvider backgroundImage;
String customImageFile;
File _image;

Future getImage() async {
  var image = await ImagePicker.pickImage(source: ImageSource.gallery);

  setState(() {
    _image = image;
  });

  customImageFile = _image.toString();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('customImageFile', customImageFile);
}

如您所见,我正在尝试将图像文件的 URI 存储到 SharedPreferences 中以保持持久性,并且我在我的应用程序中显示它,如下所示:

Container(
  decoration: BoxDecoration(
    color: Colors.blueAccent,
      image: DecorationImage(
        image: _image == null ? backgroundImage :  FileImage(_image),
        fit: BoxFit.fill,
      ),
    ),
),

问题是我似乎无法获得 customImageFile 的字符串值来正确加载图像。

编辑:实际上,我可能偶然发现了原因,直到我使用字符串的打印转储时才注意到这一点。实际的字符串是这样的:

File: '/storage/emulated/0/Download/images.jpeg'

而不仅仅是:

'/storage/emulated/0/Download/images.jpeg'

如果我可以在这里玩字符串,它可能会起作用。我无法在网上找到有关如何忽略字符串的前 6 个字符的任何内容。在 Java 和 Visual Basic 中很容易做到这一点,但我找不到方法。

更新:已设法将字符串减少为:

'/storage/emulated/0/Download/images.jpeg'

通过使用:

customImageFile = customImageFile.substring(6);

但它现在向我显示了这个错误:

Cannot open file, path = ''/storage/emulated/0/Download/images.jpeg'' (OS Error: No such file

所以我可以将子字符串值增加到 7 以删除第一个撇号,如何删除字符串的最后一个字符?

标签: imageflutter

解决方案


好的,所以我终于让它工作了,并将在这里为任何想要这样做的人提供完整的代码部分:

使用 ImagePicker 从图库中提取图像,并将 URI 保存到 SharedPreferences 以进行持久性:

ImageProvider backgroundImage;
String customImageFile;
File _image;

  Future getImage() async {
   var image = await ImagePicker.pickImage(source: ImageSource.gallery);

   setState(() {
     _image = image;
   });

   customImageFile = _image.toString();
   SharedPreferences prefs = await SharedPreferences.getInstance();
   prefs.setString('customImageFile', customImageFile);
}

如何在构建方法中显示图像,其中 backgroundImage 是您希望在用户选择自定义文件之前显示的占位符:

Container(
  decoration: BoxDecoration(
    color: Colors.blueAccent,
    image: DecorationImage(
      image: _image == null ? backgroundImage :  FileImage(_image),
      fit: BoxFit.fill,
    ),
  ),
),

现在 customImageFile 将不是一个合适的字符串值,以便从图库中再次找到此图像,因此我们需要编辑字符串以使其看起来像我们可以使用的东西。原始 customImageFile 字符串:

File: '/storage/emulated/0/Download/images.jpeg'

修复它:

customImageFile = customImageFile.substring(6);
customImageFile = customImageFile.replaceAll("'", "");

现在让我们的 String 看起来像这样:

/storage/emulated/0/Download/images.jpeg

这是我们现在可以利用之前的建议的东西,如下所示:

setState(() {
  _image =  File(customImageFile);
});

测试和工作正常。所以现在我们可以使用我们存储在 SharedPreferences 中的字符串在应用程序启动时加载之前选择的图像。我将 loadPreferences() 方法放入处理所有此类事情的 initState() 中,这是一种享受。

希望这对某人有所帮助,因为我在网上找不到任何关于此的内容。


推荐阅读