1

Hello i am developing app lock on flutter which move your gallery photo to application directory folder with help of file_picker plugin.And i have successfully copied gallery photo to my application directory but issue that i wanna delete orginal image from phone photo gallery.Image is not deleting as filepicker.path is returning cache image path not the original path of selected image.here is my code below

  Future<void> pickImage() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.image,

      );

      if (result != null && result.files.isNotEmpty) {
        final appDir = await getApplicationDocumentsDirectory();
        final imagesDir = Directory('${appDir.path}/images');

        if (!await imagesDir.exists()) {
          await imagesDir.create(recursive: true);
          print('Created directory: $imagesDir');
        }

        for (var file in result.files) {
          final fileName = file.name;
          final filePath = file.path;
          final newPath = '${imagesDir.path}/$fileName';


          // Move the image file to the images directory
          final File sourceFile = File(filePath!);
          final File destinationFile = await sourceFile.copy(newPath);

          print('Moved image: ${destinationFile.path}');

          await sourceFile.delete();
          print('Deleted image: $filePath');
        }

        refreshScreen();
      }
    } catch (e) {
      print('Error picking images: $e');
    }
  }
joshua
  • 177
  • 1
  • 2
  • 14

1 Answers1

0

WORKING SOLUTION ✨

If you're using file_picker, I'm sure you have access to path attribute from returned XFile object.

This simple deletes the file, based on path passed to the function

Future<void> deleteFileBasedOnPath(String imagePath) async {
  final FileManager fileManager = FileManager();
  final bool isDeleted = await fileManager.deleteFile(imagePath);

  if (isDeleted) {
    // Image successfully deleted, Handle event

  } else {
    // Failed to delete image, Handle event
  }
}

Then update your method like so:

  • Instead of calling await sourceFile.delete();
  • Call deleteFileBasedOnPath(filePath);

That's it, that's all ✅

Happy coding ‍♂️‍♂️‍♂️

Baimam Boukar
  • 908
  • 5
  • 20