create folder and save file flutter
// add DIO, path_provider.
/*download file from link */
String fileName = 'task_${task.TaskNo}_${e.ImgNo}${e.FileExt}';
Directory? _directory =await getExternalStorageDirectory();
String _filePath = '${_directory!.path}/$fileName';
print("file path" +_filePath);
await Dio().downloadUri(
Uri.parse(attachmentUrl),_filePath);
//Create directory and save file
Future<bool> saveFile(String filePath, BuildContext context) async {
Directory storageDir;
try {
File f = File(filePath);
String savedPath;
storageDir = (await getExternalStorageDirectory())!;
String newPath = '';
List<String> folders = storageDir.path.split('/');
for (int x = 1; x < folders.length; x++) {
String folder = folders[x];
if (folder != 'Android') {
newPath += '/' + folder;
} else {
break;
}
}
newPath = newPath + '/MyTask';
storageDir = Directory(newPath);
if (!await storageDir.exists()) {
await storageDir.create(recursive: true);
}
if (await storageDir.exists()) {
//List<int> bytesSync = widget.pickedImage.readAsBytesSync();
String baseFileName = f.path.split('/').last;
File savedFile = File(storageDir.path + "/$baseFileName");
savedPath = storageDir.path + "/$baseFileName";
savedFile.writeAsBytesSync(f.readAsBytesSync());
if (savedPath != null) {
print("File Saved..!");
} else {
print( 'Could not save file. Please Try again');
}
return true;
}
} catch (e) {
print(e);
}
return false;
}