且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flutter如何将图像文件保存到图库中的新文件夹?

更新时间:2021-12-22 22:28:54

您需要将图像保存到外部存储目录中,以便在图库中显示图像. 无需获取临时目录,而是获取外部存储目录.

You need to save the image into external storage directory for showing the image on gallery. Instead of getting temporary directory, obtain external storage directory.

final directory = await getExternalStorageDirectory();

您需要在android/app/src/main文件夹的AndroidManifest.xml文件上提供权限

You need to provide the permission on AndroidManifest.xml file of your android/app/src/main folder

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

然后假设您要创建一个名为MyImages的文件夹并将新图像添加到该文件夹​​中,

then let's say that you want to create a folder named MyImages and add the new image to that folder,

final myImagePath = '${directory.path}/MyImages' ;
final myImgDir = await new Directory(myImagePath).create();

然后将文件写入路径.

var kompresimg = new File("$myImagePath/image_$baru$rand.jpg")
  ..writeAsBytesSync(img.encodeJpg(gambarKecilx, quality: 95));

要获取文件数量,只需将文件获取到列表中并检查列表的长度

for getting the number of files, just obtain the files to a list and check the length of the list

var listOfFiles = await myImgDir.list(recursive: true).toList();
var count = countList.length;