0

I'm trying to create folder after installing app. for example like this question

Create Folder When Installing Application

i follow two solution

https://stackoverflow.com/a/54848857

https://stackoverflow.com/a/55349516

I'm trying to download Image and save it after create folder. I'm Using getApplicationDocumentDirectory to create folder but the folder is Missing on device. But if i check in path directory from code is Exist. If i change to getExternalStorageDirectory the folder is exist but inside Android/data/packages_name/files/my_folder this is not what i want Event the folder exist my image download not visible on gallery.

Note : i Use real device and i don't have SD card. I want to make folder in Internal Storage.

Here my code

@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));
  }
Arteesy
  • 71
  • 2
  • 10

0 Answers0