1

I'm trying to store image (picked from ImagePicker) in shared preferences, so I can persist the data

This is what I did so far

Here is the code

  File? profileImage;

  void saveData(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);
  }

  Future pickProfile() async {
     final profileImagePicker = await ImagePicker().pickImage(source: ImageSource.gallery);

     final directoryPath = await getApplicationDocumentsDirectory();
     final path = directoryPath.path;
     final imageFile = await File(profileImagePicker!.path).copy('$path/image1.png');

     saveData('primaryProfile', imageFile.toString()); // Store it as a string, don't know if this is the right away


     setState(() {
       profileImage = imageFile;
     });
  }

  void getPrimaryProfile() async {
    final prefs = await SharedPreferences.getInstance();
    final value = prefs.getString('primaryProfile'); // How can I convert this to File object from String, so I can assign it to file object (profileImage)


  }

  //To display the image

  CircleAvatar(
            backgroundImage: profileImage != null ? FileImage(profileImage!) as ImageProvider : const AssetImage('assets/images/profile.png'),
            backgroundColor: Colors.black45
              ),
shakky
  • 434
  • 5
  • 20

1 Answers1

0

You can use base64 for this. Images are stored as binary files, which is a sequence of bytes. So what base64 does is that it converts your bytes into a long string that expresses this data. Its problem is that it takes more memory than the actual image. It can make the file size more than 25% of its size.

Shared Preferences also exist in java android and it is not advised to store images in shared preferences. Here is an android geek telling this. Maybe you would consider changing this part of your app's design.

For Flutter, base64 are there. And here is an example on how to use it.

Mohamed Akram
  • 416
  • 4
  • 12