Home > database >  How can I save a image upload via gallery/camera permanently in my application?
How can I save a image upload via gallery/camera permanently in my application?

Time:11-13

I am trying to save image upload from the camera or gallery permanently, I am using image_picker, and each time I choose a picture for a pfp and click onto a different tab its gone, it only save it temporarily. this is my code below:

import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
// camera
Future getCameraImage() async{
  // getting the image
  final image = await ImagePicker().pickImage(source: ImageSource.camera);
  if(image == null) return;
//  final imageTemporary = File(image.path);
final imagePerm = await saveImagePermanently(image.path);
 setState(() {
   this.image = imagePerm;
 });
}
// image picker/ gallery
File? image;
 Future getImage() async{
  final image = await ImagePicker().pickImage(source: ImageSource.gallery);
 if(image == null) return;
 final imageTemporary = File(image.path);
 setState(() {
   this.image = imageTemporary;
 });
 }

I have tried a few different methods but run into the same error.

CodePudding user response:

Follow these steps:

  // Step 1: Retrieve image from picker 
final File image = await ImagePicker.pickImage(source: imageSource);

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

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

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

CodePudding user response:

the StatefulWidget have a lifecycle when navigating between screens in your bottom nav, you're killing the state of widgets that aren't shown on the screen.

so changing to other screens that the one where you pick an image, the File? image; which should have the image file is killed, so when you come back to that screen, that widget is rebuild again which will cause that it's just null and it lost the previous value.

the solution for this is to set that variable on the global scope it's never re-initialized to null, like:

File? image;

class YourStateFulWidget extends StateFulWidget {

 /* all your widget and State object code*/    
  • Related