4

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)
   );
},

enter image description here

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Denis Ramdan
  • 1,763
  • 3
  • 18
  • 35

5 Answers5

8

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';
Raj Yadav
  • 9,677
  • 6
  • 35
  • 30
  • 2
    storage/emulated/0/Android/data/com. been created ....i want in sdcard as like as whatsapp, ... – kriss Nov 27 '19 at 12:23
3

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

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
3
//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
    }
  }
Jay Gadariya
  • 1,823
  • 7
  • 25
  • 1
    While this code may answer the question, providing additional context regarding _why_ and/or _how_ this code answers the question improves its long-term value. – lcnicolau Mar 26 '19 at 04:02
0

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();
 }
Hari
  • 3
  • 5
0

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);

Selva
  • 31
  • 2