'Store profile image in local storage and display it

I am building a profile page for my app in which I have a profile image section. I want to store the image that the user selects in the local storage and load it directly from there. I read a few other answers and articles, but couldn't really understand how to make it work.

I am using image_picker to select the image from camera and gallery with the following function and am storing the image path that I get in the firebase database.

 Future imageFromCamera() async {
    // Step 1: Retrieve image from picker
    final XFile? image =
        await ImagePicker().pickImage(source: ImageSource.camera);
    final File? file = File(image!.path);

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

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

// Step 4: Copy the file to a application document directory.
    final fileName = path.basename(file!.path);
    print(fileName);
    final File? localImage = await file.copy("${directory.path}/$fileName");
    print(localImage);

    FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;

    firebaseFirestore
        .collection("users")
        .doc(user?.uid)
        .update({'imgsrc': image.path});

    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString('profile_image', localImage!.path);
  }

I am using a CircleAvatar to display the image, and if the image path is null, I show the Icons.person icon.

Widget buildImage() {
    return CircleAvatar(
      backgroundColor: Color(0xffdcdbda),
      radius: 100,
      child: buildCircle(
        child: (imgPath != null)
            ? Image.file(
                File(imgPath!),
                height: 200,
                width: 200,
              )
            : Icon(
                Icons.person,
                size: 180,
                color: Colors.grey,
              ),
        all: 0,
        color: Color(0xffdcdbda),
      ),
    );
  }

I was using Firebase to store and display the image earlier, but it took a lot of time to load and change the image. I want a quick and efficient way to implement profile image. Any help would be appreciated!



Solution 1:[1]

The file's path is usable, no need to create a another file :

final pickedFile = await _picker.pickImage(
    source: ImageSource.gallery,
);
final path = pickedFile!.path;
// then 
Image.file(
    File(path),
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1