how to create a directory in flutter - flutter

I want to download images and save it to storage in a unique directory name using dio and path_provider.but i have an error:
I/flutter (15977): FileSystemException: Cannot open file,
path = '/data/user/0/com.manga.indonesia.manga.suka/app_flutter/sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia/0.jpg'
How can i make this sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia directory?
My code :
downloadChapter(chapter) async {
Response res;
Dio dio = new Dio();
var dir = await getApplicationDocumentsDirectory();
try {
res = await dio
.get('http://0.0.0.0:8080/api/MangaSuka/kchapters/' + chapter);
var contentChapter = res.data['content'].where((a) {
return a != null;
}).toList();
for (var i = 0; i < contentChapter.length; i++) {
await dio.download(contentChapter[i], "${dir.path}/${chapter}/$i.jpg",
onProgress: (rec, total) {
print("Rec: $rec , Total: $total");
});
};
return print(contentChapter);
} catch (e) {
return print(e);
}
}

It is well explained in flutter documentation:
import 'dart:io';
void main() {
new Directory('sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
}
However, in many situations, like creating one directory, perhaps the async (default) version of Directory.create will not be time saving and could perhaps result in race condition. In that case, using the sync version of the command would be more appropriate:
new Directory('sensei-wa-koi-o-oshie-rarenai-chapter-7-bahasa-indonesia').createSync()
// ... following sequential code
Of note, many dart::io methods have *Sync versions.

import 'package:path_provider_ex/path_provider_ex.dart';
import 'dart:io';
import 'package:simple_permissions/simple_permissions.dart';
//packages
// simple_permissions: ^0.1.9
// path_provider_ex:
//Android mainfest
// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
// <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
main(){
List<StorageInfo> _storageInfo = [];
#override
void initState() {
super.initState();
initPlatformState();
Timer(Duration(seconds: 2), () {
createFolder();
});
}
createFolder() async {
PermissionStatus permissionResult =
await SimplePermissions.requestPermission(
Permission.WriteExternalStorage);
if (permissionResult == PermissionStatus.authorized) {
// Directory _appFile = Directory(_storageInfo[0].rootDir + '/MyTestFOlder');
// _appFile.create();
new Directory(_storageInfo[0].rootDir + '/MyCreatedFolder').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
// File ourTempFile = File(_appFile.path);
// print(ourTempFile.path);
// ourTempFile.create();
// code of read or write file in external storage (SD card)
}
}
}

Create several directories using recursive: true
import 'dart:io';
...
var directory = await Directory('dir/subdir').create(recursive: true);
Check out the official information.

Related

Record Audio and upload file to firebase storage Flutter Web

I am using the flutter_sound package to record and play audio. On Flutter Web, on stopping the recording the recorder returns a path/URL of this type: blob:http://localhost:63986/b60f31ce-b94d-48c8-8a4a-2d939effe6d8
I want to upload the audio recording to Firebase Storage but dart.io can't be used for flutter-web so can't use the File method. Even after searching, I didn't find a way to achieve it. I don't know how to proceed. How can I write the audio to file and upload it to firebase?
My Code:
import 'dart:html' as html;
import 'dart:io' as io;
final recorder = FlutterSoundRecorder();
final player = FlutterSoundPlayer();
String fileName;
#override
void initState() {
super.initState();
initRecorder();
}
#override
void dispose() {
recorder.closeRecorder();
player.closePlayer();
super.dispose();
}
Future<void> initRecorder() async {
if (!kIsWeb) {
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission form mic first!')),
);
}
}
await recorder.openRecorder();
await player.openPlayer();
recorder.setSubscriptionDuration(Duration(milliseconds: 500));
}
Future<void> record() async {
fileName = DateTime.now().toString();
await recorder.startRecorder(toFile: fileName);
}
Future<void> stop() async {
path = await recorder.stopRecorder();
if (kIsWeb) {
if (path == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission for mic first!')),
);
} else {
// Get File from path and upload it to Firebase
print(path);
// not working for Web
// final audioFile = io.File(path);
// html.File() doesn't take path/Url as parameter but
// File(List<Object> fileBits, String fileName,[Map? options])
/*
await FirebaseStorage.instance
.ref()
.child('users/uploads/$fileName.mp3')
.putData(file!.bytes!);*/
}
} else if (!kIsWeb) {
if (path == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Grant Permission for mic first!')),
);
} else {
//final audioFile = io.File(path);
// await FirebaseStorage.instance
// .ref()
// .child('users/uploads/$fileName.mp3')
// .putFile(audioFile);
}
}
}
I've been working on this for days, and I finally figured it out!
When you call startRecorder(toFile: audioLocation), audioLocation will be the location of the file after you call stopRecorder(), stored in html.window.sessionStorage (html as in import 'dart:html' as html;).
So you need to add import 'package:http/http.dart' as http;, create a fileName (whatever you want the file to be called in Firebase Storage), and then insert the following piece of code.
var ref = await storage.ref().child('path/to/file/$fileName');
Uri blobUri = Uri.parse(html.window.sessionStorage[audioFile]!);
http.Response response = await http.get(blobUri);
await ref.putData(response.bodyBytes, SettableMetadata(contentType: 'video/mp4'));
This might not be the best way, but it is the way I finally got it to work! Good luck!!

Flutter - How to save and play a recorded audio file?

I, for the life of me, can't figure this out. All I am trying to do is record an audio (as in a sound/voice recorder) and later be able to play it.
Recorder class:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
//String _pathToAudio = '/sdcard/myAudio.aac';
String _fileName = 'myAudio.aac';
String _path = "/storage/emulated/0";
class Recorder {
FlutterSoundRecorder? _recorder;
bool _isRecorderInitialized = false;
bool get isRecording => _recorder!.isRecording;
Future init() async {
_recorder = FlutterSoundRecorder();
//final directory = "/sdcard/downloads/";
//Directory? extStorageDir = await getExternalStorageDirectory();
//String _path = directory.path;
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw RecordingPermissionException('Recording permission required.');
}
await _recorder!.openAudioSession();
_isRecorderInitialized = true;
}
void _writeFileToStorage() async {
File audiofile = File('$_path/$_fileName');
Uint8List bytes = await audiofile.readAsBytes();
audiofile.writeAsBytes(bytes);
}
void dispose() {
_recorder!.closeAudioSession();
_recorder = null;
_isRecorderInitialized = false;
}
Future record() async {
if (!_isRecorderInitialized) {
return;
}
print('recording....');
await _recorder!.startRecorder(
toFile: '$_fileName',
//codec: Codec.aacMP4,
);
}
Future stop() async {
if (!_isRecorderInitialized) {
return;
}
await _recorder!.stopRecorder();
_writeFileToStorage();
print('stopped....');
}
Future toggleRecording() async {
if (_recorder!.isStopped) {
await record();
} else {
await stop();
}
}
}
Currently the error I am getting is "Cannot open file, path = '/storage/emulated/0/myAudio.aac' (OS Error: No such file or directory, errno = 2)".
I am using flutter_sound
Try initializing your file path by using path_provider.
Add these 2 lines to the beginning of your init function.
final directory = await getApplicationDocumentsDirectory();
_path = directory.path; // instead of "/storage/emulated/0"
Not sure how you're trying to access and play that file but on my end it at least cleared the error.
String _fileName = 'Recording_';
String _fileExtension = '.aac';
String _directoryPath = '/storage/emulated/0/SoundRecorder';
This is what I have currently and it's working.
void _createFile() async {
var _completeFileName = await generateFileName();
File(_directoryPath + '/' + _completeFileName)
.create(recursive: true)
.then((File file) async {
//write to file
Uint8List bytes = await file.readAsBytes();
file.writeAsBytes(bytes);
print(file.path);
});
}
void _createDirectory() async {
bool isDirectoryCreated = await Directory(_directoryPath).exists();
if (!isDirectoryCreated) {
Directory(_directoryPath).create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
}
}
void _writeFileToStorage() async {
_createDirectory();
_createFile();
}

Mock getExternalStorageDirectory on Flutter

I´m trying mock the function getExternalStorageDirectory, but alway return the error:
"UnsupportedError (Unsupported operation: Functionality only available on Android)"
I´m using the method setMockMethodCallHandler to mock it, but the erro occurs before the method be called.
test method
test('empty listReportModel', () async {
TestWidgetsFlutterBinding.ensureInitialized();
final directory = await Directory.systemTemp.createTemp();
const MethodChannel channel =
MethodChannel('plugins.flutter.io/path_provider');
channel.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getExternalStorageDirectory') {
return directory.path;
}
return ".";
});
when(Modular.get<IDailyGainsController>().listDailyGains())
.thenAnswer((_) => Future.value(listDailyGainsModel));
when(Modular.get<IReportsController>().listReports())
.thenAnswer((_) => Future.value(new List<ReportsModel>()));
var configurationController = Modular.get<IConfigurationController>();
var response = await configurationController.createBackup();
expect(response.filePath, null);
});
method
Future<CreateBackupResponse> createBackup() async {
CreateBackupResponse response = new CreateBackupResponse();
var dailyGains = await exportDailyGainsToCSV();
var reports = await exportReportsToCSV();
final Directory directory = await getApplicationDocumentsDirectory();
final Directory externalDirectory = await getExternalStorageDirectory();
if (dailyGains.filePath != null && reports.filePath != null) {
File dailyGainsFile = File(dailyGains.filePath);
File reportsFile = File(reports.filePath);
var encoder = ZipFileEncoder();
encoder.create(externalDirectory.path + "/" + 'backup.zip');
encoder.addFile(dailyGainsFile);
encoder.addFile(reportsFile);
encoder.close();
await _removeFile(dailyGainsFile.path);
await _removeFile(reportsFile.path);
response.filePath = directory.path + "/" + 'backup.zip';
}
return response;
}
As in pub.dev stated:
path_provider now uses a PlatformInterface, meaning that not all
platforms share the a single PlatformChannel-based implementation.
With that change, tests should be updated to mock PathProviderPlatform
rather than PlatformChannel.
That means somewhere in your test directory you create the following mock class:
import 'package:mockito/mockito.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
const String kTemporaryPath = 'temporaryPath';
const String kApplicationSupportPath = 'applicationSupportPath';
const String kDownloadsPath = 'downloadsPath';
const String kLibraryPath = 'libraryPath';
const String kApplicationDocumentsPath = 'applicationDocumentsPath';
const String kExternalCachePath = 'externalCachePath';
const String kExternalStoragePath = 'externalStoragePath';
class MockPathProviderPlatform extends Mock
with MockPlatformInterfaceMixin
implements PathProviderPlatform {
Future<String> getTemporaryPath() async {
return kTemporaryPath;
}
Future<String> getApplicationSupportPath() async {
return kApplicationSupportPath;
}
Future<String> getLibraryPath() async {
return kLibraryPath;
}
Future<String> getApplicationDocumentsPath() async {
return kApplicationDocumentsPath;
}
Future<String> getExternalStoragePath() async {
return kExternalStoragePath;
}
Future<List<String>> getExternalCachePaths() async {
return <String>[kExternalCachePath];
}
Future<List<String>> getExternalStoragePaths({
StorageDirectory type,
}) async {
return <String>[kExternalStoragePath];
}
Future<String> getDownloadsPath() async {
return kDownloadsPath;
}
}
And build your tests the following way:
void main() {
group('PathProvider', () {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
PathProviderPlatform.instance = MockPathProviderPlatform();
// This is required because we manually register the Linux path provider when on the Linux platform.
// Will be removed when automatic registration of dart plugins is implemented.
// See this issue https://github.com/flutter/flutter/issues/52267 for details
disablePathProviderPlatformOverride = true;
});
test('getTemporaryDirectory', () async {
Directory result = await getTemporaryDirectory();
expect(result.path, kTemporaryPath);
});
}
}
Here you can check out the complete example.

Flutter how to backup and restore sqflite database?

I'm using sqflite for my flutter project and now, I want to backup and then restore it. I searched for this issue but can't find a result. Is there any way to do it?
You can use this solution, it performs the backup of your bank with encryption or not, it's up to you, in addition to migrating from one version of the bank to another when, for example, the user is updating the application and the bank is a old version. I hope I helped, sorry for the writing because I don't speak English.
Dependencies
dependencies:
encrypt: ^4.1.0
path: ^1.7.0
sqflite: ^1.3.1
Class
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:convert' as convert;
import 'package:encrypt/encrypt.dart' as encrypt ;
class DatabaseRepository {
Database _db;
static const SECRET_KEY = "2021_PRIVATE_KEY_ENCRYPT_2021";
static const DATABASE_VERSION = 1;
List<String> tables =[
];
Future<Database> get db async
{
if(_db != null)
{
return _db;
}
else
{
_db = await initDb(DATABASE_VERSION);
return _db;
}
}
Future<String> _databasePath() async
{
String databasesPath = await getDatabasesPath();
return join(databasesPath, "database.db");
}
Future<Database> initDb(int version) async
{
String path = await _databasePath();
return await openDatabase(path, version:version, onCreate: onCreate,onUpgrade: onUpgrade);
}
Future deleteDB() async
{
String path = await _databasePath();
await deleteDatabase(path);
}
FutureOr onCreate(Database db, int newerVersion) => this._onCreates[newerVersion](db);
Map<int,Function> _onCreates = {
1:(Database db) async {
print("DATABASE CREATE v1");
},
2:(Database db) async{
print("DATABASE CREATE v2");
},
3:(Database db) async{
print("DATABASE CREATE v3");
},
};
FutureOr<void> onUpgrade(Database db , int oldVersion, int newVersion ) async
{
for (var migration = oldVersion; migration < newVersion; migration++)
{
this._onUpgrades["from_version_${migration}_to_version_${migration+1}"](db);
}
}
Map<String,Function> _onUpgrades = {
'from_version_1_to_version_2':(Database db) async {
print('from_version_1_to_version_2');
},
'from_version_2_to_version_3':(Database db) async {
print('from_version_2_to_version_3');
},
};
Future clearAllTables() async
{
try
{
var dbs = await this.db;
for (String table in [
])
{
await dbs.delete(table);
await dbs.rawQuery("DELETE FROM sqlite_sequence where name='$table'");
}
print('------ CLEAR ALL TABLE');
}
catch(e){}
}
Future<String>generateBackup({bool isEncrypted = false}) async {
print('GENERATE BACKUP');
var dbs = await this.db;
List data =[];
List<Map<String,dynamic>> listMaps=[];
for (var i = 0; i < tables.length; i++)
{
listMaps = await dbs.query(tables[i]);
data.add(listMaps);
}
List backups=[tables,data];
String json = convert.jsonEncode(backups);
if(isEncrypted)
{
var key = encrypt.Key.fromUtf8(SECRET_KEY);
var iv = encrypt.IV.fromLength(16);
var encrypter = encrypt.Encrypter(encrypt.AES(key));
var encrypted = encrypter.encrypt(json, iv: iv);
return encrypted.base64;
}
else
{
return json;
}
}
Future<void>restoreBackup(String backup,{ bool isEncrypted = false}) async {
var dbs = await this.db;
Batch batch = dbs.batch();
var key = encrypt.Key.fromUtf8(SECRET_KEY);
var iv = encrypt.IV.fromLength(16);
var encrypter = encrypt.Encrypter(encrypt.AES(key));
List json = convert.jsonDecode(isEncrypted ? encrypter.decrypt64(backup,iv:iv):backup);
for (var i = 0; i < json[0].length; i++)
{
for (var k = 0; k < json[1][i].length; k++)
{
batch.insert(json[0][i],json[1][i][k]);
}
}
await batch.commit(continueOnError:false,noResult:true);
print('RESTORE BACKUP');
}
}
Use:
final DatabaseRepository databaseRepository = new DatabaseRepository();
String backup = await databaseRepository.generateBackup(isEncrypted: true);
await databaseRepository.clearAllTables();
await databaseRepository.restoreBackup(backup,isEncrypted: true);
For complete details, go to link
ElevatedButton(
onPressed: () async {
final dbFolder = await getDatabasesPath();
File source1 = File('$dbFolder/doggie_database.db');
Directory copyTo =
Directory("storage/emulated/0/Sqlite Backup");
if ((await copyTo.exists())) {
// print("Path exist");
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
} else {
print("not exist");
if (await Permission.storage.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
await copyTo.create();
} else {
print('Please give permission');
}
}
String newPath = "${copyTo.path}/doggie_database.db";
await source1.copy(newPath);
setState(() {
message = 'Successfully Copied DB';
});
},
child: const Text('Copy DB'),
),
ElevatedButton(
onPressed: () async {
var databasesPath = await getDatabasesPath();
var dbPath = join(databasesPath, 'doggie_database.db');
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
File source = File(result.files.single.path!);
await source.copy(dbPath);
setState(() {
message = 'Successfully Restored DB';
});
} else {
// User canceled the picker
}
},
child: const Text('Restore DB'),
),
dependencies:
sqflite: ^2.0.0+3
path_provider: ^2.0.11
permission_handler: ^10.0.0
Export ( back up)
To export SQFLite database , I came across some errors , some of the error are
FileSystemException: Cannot open file, path
error: permission denied, errno = 13
etc........
I want to export my Database into Download folder that is ,
this is my Database path /data/user/0/com.example.reminder_app/databases/notes.db , it's a application directory path so my aim is to export notes.db file into this path
/storage/emulated/0/Download/
Expanding dBToCopy functions , this function will give path of Database
Future<File> dBToCopy() async {
final db = await instance.database;
final dbPath = await getDatabasesPath();
var afile = File(dbPath);
return afile;
}
full code bellow
dbExportToDownloadFolder() async {
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
Directory documentsDirectory =
Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
File b =
File("/data/user/0/com.example.reminder_app/databases/notes.db");
if ( await Permission.storage.request().isGranted &&
await Permission.accessMediaLocation.request().isGranted &&
await Permission.manageExternalStorage.request().isGranted )
{
File a = await b.copy(newPath);
} else {
print("No Permission Granted");
}
}
Note
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
OutPut print
lllllllllllllllllll /data/user/0/com.example.reminder_app/databases
this result file not contain the notes.db file , only contain this path
/data/user/0/com.example.reminder_app/databases
To get the DatabaseFile
File b = File("/data/user/0/com.example.reminder_app/databases/notes.db");
or
File b = File("${result.path}"+"/notes.db");
so using the file b we can copy the file to Download folder file that is abcde.db
To do that create a file in Download , that is abcde.db
Directory documentsDirectory = Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
and using the copy method , to copy one file to another file
File a = await b.copy(newPath);
Note
If you are getting permission denied errors and OS errors please add all permission in manifest , and using permission_handler allow all permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
after the copying , A new file created in Download folder that is abcde.db
Improt (restore)
To improt abcde.db file from Download to databases folder file that is notes.db
importDataBaseFile () async {
String recoveryPath =
"/data/user/0/com.example.noteapp/databases/notedb.db";
Directory backupPath = Directory("storage/emulated/0/Download/");
String newPath = join("${backupPath.absolute.path}" + 'abcde.db');
File backupFile = File(newPath);
backupFile.copy(recoveryPath);
NotesDatabase.instance.readAllNotes();
},
Expanding function readAllNotes ()
Future<List<Note>> readAllNotes() async {
final db = await instance.database;
final orderBy = '${NoteFields.time} ASC';
final result = await db.query(tableNotes, orderBy: orderBy);
return result.map((json) => Note.fromJson(json)).toList();
}
so importing operation is performs reversing the export operation .
use a FilePicker to pick Database file instead
Improt from file picker ( restore from file picker )
dependencies:
sqflite: ^2.0.0+3
path_provider: ^2.0.11
permission_handler: ^10.0.0
file_picker: ^5.0.1
full code :
importDataBaseFile () async {
bool? clear = await FilePicker.platform.clearTemporaryFiles();
print(clear);
FilePickerResult? result =
await FilePicker.platform.pickFiles();
String recoveryPath =
"/data/user/0/com.example.reminder_app/databases/notes.db";
String newPath = "${result!.files.single.path}";
File backupFile = File(newPath);
backupFile.copy(recoveryPath);
refreshNotes();
}
Note
this is the demo example so , you can add encryptions and choose different path to store the back up , it according to you
You can use this Guide to make your restore.
https://github.com/tekartik/sqflite/blob/master/sqflite/doc/opening_asset_db.md
With this, you can download from somewhere your .db and change with the phone version.
To backup, you can change some lines in exemple above.

Create Folder When Installing Application

How to create folder in device storage to save files?
This is the code to download file into device :
import 'package:flutter_downloader/flutter_downloader.dart';
onTap: () async { //ListTile attribute
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
final taskId = await FlutterDownloader.enqueue(
url: 'http://myapp/${attach[index]}',
savedDir: '/sdcard/myapp',
showNotification: true, // show download progress in status bar (for Android)
clickToOpenDownloadedFile: true, // click on notification to open downloaded file (for Android)
);
},
You can create directory when app is launched.
In the initState() method of your first screen do the logic.
Ex.
createDir() async {
Directory baseDir = await getExternalStorageDirectory(); //only for Android
// Directory baseDir = await getApplicationDocumentsDirectory(); //works for both iOS and Android
String dirToBeCreated = "<your_dir_name>";
String finalDir = join(baseDir, dirToBeCreated);
var dir = Directory(finalDir);
bool dirExists = await dir.exists();
if(!dirExists){
dir.create(/*recursive=true*/); //pass recursive as true if directory is recursive
}
//Now you can use this directory for saving file, etc.
//In case you are using external storage, make sure you have storage permissions.
}
#override
initState(){
createDir(); //call your method here
super.initState();
}
You need to import these libraries:
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
From what I saw is, you are not using appDocDir and appDocPath anywhere, cause you are saving files in /sdcard/myapp.
Please check if you are asking and granting the storage permission and also there is no way to store files in sdcard like you are doing. Either make use of predefined directories like (Document, Pictures etc.) or use device root directory that starts with storage/emulated/0
//add in pubspec.yaml
path_provider:
//import this
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
//create Variable
String directory = (await getApplicationDocumentsDirectory()).path;
//initstate to create directory at launch time
#override
void initState() {
// TODO: implement initState
super.initState();
createFolder();
}
//call this method from init state to create folder if the folder is not exists
void createFolder() async {
if (await io.Directory(directory + "/yourDirectoryName").exists() != true) {
print("Directory not exist");
new io.Directory(directory + "/your DirectoryName").createSync(recursive: true);
//do your work
} else {
print("Directoryexist");
//do your work
}
}
Here is the Sample Codefor Creating a folder in Users internal storage Hope it Helps You
import 'dart:io' as Io;
Future _downloadImage() async {
try {
// request runtime permission
final permissionHandler = PermissionHandler();
final status = await permissionHandler
.checkPermissionStatus(PermissionGroup.storage);
if (status != PermissionStatus.granted) {
final requestRes = await permissionHandler
.requestPermissions([PermissionGroup.storage]);
if (requestRes[PermissionGroup.storage] != PermissionStatus.granted) {
_showSnackBar('Permission denined. Go to setting to granted!');
return _done();
}
}
}
var testdir =
await new Io.Directory('/storage/emulated/0/MyApp').create(recursive: true);
final filePath =
path.join(testdir.path, Filename + '.png');
print(filePath);
final file = File(filePath);
if (file.existsSync()) {
file.deleteSync();
}
//save image to storage
var request = await HttpClient().getUrl(Uri.parse(imageUrl));
var response = await request.close();
final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
final saveFileResult =
saveImage({'filePath': filePath, 'bytes': bytes});
_showSnackBar(
saveFileResult
? 'Image downloaded successfully'
: 'Failed to download image',
);
} on PlatformException catch (e) {
_showSnackBar(e.message);
} catch (e, s) {
_showSnackBar('An error occurred');
debugPrint('Download image: $e, $s');
}
return _done();
}
First you need to import
1) import 'dart:io';
Second you need to create directory for the specified path in your async/await function
2) For example:
await new Directory('/storage/emulated/0/yourFolder').create(recursive: true);