Search code examples
androiddartfluttersharedpreferencesuiimagepickercontroller

Save ImagePicker File path and Use it as Background


I'm working on a flutter app that allows user to set Background picture of their choice and "stays permanently till the user changes it".

Using Image.file(pickedImage) is temporarily, if the user leave the page, and returns back the image would have been dismissed.

I've implemented the image picker and I tried storing the image file in sharedpreferences but I was wrong ImagePicker returns Image File not Image File Path.

How do I get the picked image file path and use it as background?


Solution

  • When ImagePicker returns a file, it returns a File object as you noted. This file is external to the app, and possibly temporary (i.e. it could be moved/deleted/etc at any point) - it probably will persist for a while but you shouldn't rely on that.

    Instead, after the user has selected the image, you should copy it to your application's storage directory and then access it from there from then on.

    To do that, follow the instructions in the flutter reading/writing files documentation. But basically, what you want to be doing is getting the local directory using the getApplicationDocumentsDirectory method of the path_provider library, then calling file.copy(<path under application document directory>) with file being the file you received from the image picker and the path under the application document directory being whatever you want.

    i.e.

    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String bgPath = appDocDir.uri.resolve("background.jpg").path;
    File bgFile = await image.copy(bgPath);
    

    Once you have that file, what you want to do is save the bgFile's path to your SharedProperties (or theoretically you could just hardcode it and overwrite it every time a new image is loaded - up to you, although that approach might run into problems with the file switch). You would then load the bg file path from shared properties and use that.

    Hope that helps =).