我正在尝试在安装应用程序后创建文件夹。 例如这样的问题
Create Folder When Installing Application
我遵循两种解决方案
https://stackoverflow.com/a/54848857
https://stackoverflow.com/a/55349516
我正在尝试下载图像并在创建文件夹后将其保存。我正在使用getApplicationDocumentDirectory
创建文件夹,但是该文件夹在设备上丢失。但是,如果我从代码中检查路径目录是否存在。如果我更改为getExternalStorageDirectory
,则该文件夹存在,但在Android / data / packages_name / files / my_folder内,这不是我想要的。如果该文件夹存在,则我的图像下载在图库中不可见。
注意:我使用真实设备,但没有SD卡。 我想在内部存储中创建文件夹。
这是我的代码
@override
void initState() {
super.initState();
_createFolder();
createDir();
}
// SOLUTION ONE
createDir() async {
final url =
'https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
io.Directory baseDir =
await dirPath.getExternalStorageDirectory(); //only for Android
// Directory baseDir = await getApplicationDocumentsDirectory(); //works for both iOS and Android
String dirToBeCreated = "MY FOLDER";
// I add ../../../../../ so that my folder is out of my packages.
String finalDir = p.join(baseDir.path + '../../../../../', dirToBeCreated);
var dir = io.Directory(finalDir);
bool dirExists = await dir.exists();
if (!dirExists) {
dir.create(
recursive: true); //pass recursive as true if directory is recursive
}
if (dirExists) {
io.File file = await cm.DefaultCacheManager().getSingleFile(url);
im.Image image = im.decodeImage(file.readAsBytesSync());
io.File('$finalDir/${DateTime.now().toIso8601String()}.png')
..writeAsBytesSync(im.encodePng(image));
}
print(finalDir);
print(dirExists);
//Now you can use this directory for saving file, etc.
//In case you are using external storage, make sure you have storage permissions.
}
// SOLUTION TWO
void _createFolder() async {
final url =
'https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
String directory =
(await dirPath.getApplicationDocumentsDirectory()).path;
String path = '$directory/FOLDER TWO';
if (await io.Directory(path).exists() != true) {
print("Directory not exist");
io.Directory(path).createSync(
recursive: true,
);
//do your work
} else {
print("Directoryexist");
}
io.File file = await cm.DefaultCacheManager().getSingleFile(url);
im.Image image = im.decodeImage(file.readAsBytesSync());
io.File('$path/${DateTime.now().toIso8601String()}.png')
..writeAsBytesSync(im.encodePng(image));
}