Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Image 如何在Flatter中将图像从资产保存到内部存储?_Image_File_Flutter_Dart - Fatal编程技术网

Image 如何在Flatter中将图像从资产保存到内部存储?

Image 如何在Flatter中将图像从资产保存到内部存储?,image,file,flutter,dart,Image,File,Flutter,Dart,我正在尝试将映像从资产保存到内部存储。但是,我无法将图像从资产加载到文件。以下是我所做的: onTap: () async { final String documentPath = (await getApplicationDocumentsDirectory()).path; String imgPath = (galleryItems[currentIndex].assetName).substring(7); File image = await getImageFil

我正在尝试将映像从资产保存到内部存储。但是,我无法将图像从资产加载到文件。以下是我所做的:

onTap: () async {
  
  final String documentPath = (await getApplicationDocumentsDirectory()).path;
  String imgPath = (galleryItems[currentIndex].assetName).substring(7);
  File image = await getImageFileFromAssets(imgPath);

  print(image.path);
}
我使用
substring(7)
来消除
assets/
as,我的assetName是
assets/images/foo.jpg

Future<File> getImageFileFromAssets(String path) async {
  final byteData = await rootBundle.load('assets/$path');

  final file =
      await File('${(await getApplicationDocumentsDirectory()).path}/$path')
          .create(recursive: true);
  await file.writeAsBytes(byteData.buffer
      .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}
以下是一些真正帮助我的链接:

特别感谢@David的帮助。若你们是来解决类似问题的,请看评论以了解整个场景


因此,我接受@David的回答。

您试图在不存在的路径中创建一个文件对象。您正在使用资产路径,即相对于颤振项目根的路径。但是,该路径在设备的documents文件夹中不存在,因此无法在那里创建文件。该文件在资产文件夹中也不存在,因为您正在预先设置文档路径

要解决您的问题,您应该将
assetName
传递到
rootBundle.load()
,而不使用文档路径,然后打开
文件()
,比如
$documentPath/foo.jpg

编辑: 要创建文件,您仍然需要调用
file.create
,因此您需要运行:

final file = await File('$documentPath/images/foo.jpg').create(recursive: true);

然后,我得到了
FileSystemException的异常:无法打开文件,path='/data/user/0/com.example.pig\u salang/app\u flatter/images/foo.jpg'(操作系统错误:没有这样的文件或目录,errno=2)
Yes,这是因为您添加了
images
文件夹。我的具体意思是只创建
foo.jpg
,否则您必须按照文档中的说明创建目录:对不起,我的错误,忘记实际创建文件了。然后您可以只使用
recursive
属性,而不是在单独的步骤中创建目录。我已经编辑了我的答案。好的。。。我来看看。你为什么给它一个外部目录?执行
rootBundle.load('assets/somefolder/somefile.png')
当您访问与应用程序绑定的资产时,您必须在rootassets中查找它现在错误必须已更改?请张贴不,现在没有任何错误。您期望出现什么错误???它抛出异常
FileSystemException:cannotopenfile,path='/data/user/0/com.example.pig\u salang/app\u flatter/images/foo.jpg'(操作系统错误:没有这样的文件或目录,errno=2)
如果我删除
。创建(递归:true)
。那么您需要将文件写入根存储中的一个文件夹,使用该设备的任何人都可以使用该文件夹?或者您只需要在设备的内部存储中找到一个安全的位置?在根存储中。。。因此,该用户可以将文件从资源中获取到库中
.create()
已删除。我不再清楚问题出在哪里,但如果希望用户可以访问该文件,则应使用
getExternalStorageDirectory
final file = await File('$documentPath/images/foo.jpg').create(recursive: true);