How to Save Image File in Flutter ? File selected using Image_picker plugin

Using await ImagePicker.pickImage(...), you are already on the right track because the function returns a File.

The File class has a copy method, which you can use to copy the file (which is already saved on disk by either the camera or by lying in gallery) and put it into your application documents directory:

// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);

// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;

// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');

setState(() {
  _image = newImage;
});

You should also note that you can get the path of the image file from ImagePicker using image.path, which will also contain the file ending that you might want to extract and you can save your image path by using newImage.path.


@creativecreatorormaybenot answer is really helpful but it missed one important part i.e retrieving the image for later use.

Saving Image

// Step 1: Retrieve image from picker 
final XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);

// Step 2: Check for valid file
if (image == null) return;

// Step 3: Get directory where we can duplicate selected file.
final String duplicateFilePath = await getApplicationDocumentsDirectory().path;

// Step 4: Copy the file to a application document directory. 
final var fileName = basename(file.path);
final File localImage = await image.saveTo('$duplicateFilePath/$fileName');

Tip: you can retrieve file name from original file using basename(file.path). Make sure you import 'package:path/path.dart';

Retrieving/Loading Image

// Step 1: Save image/file path as string either db or shared pref
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('test_image', localImage.path)

// Step 2: Loading image by using the path that we saved earlier. We can create a file using path 
//         and can use FileImage provider for loading image from file.
CircleAvatar(
          backgroundImage: FileImage(File(prefs.getString('test_image')),
          radius: 50,
          backgroundColor: Colors.white)

Tags:

Dart

Flutter