In my flutter app, if the user is signing in for the first time, he will be directed to profile page where he gets to key in his personal details and upload his profile pic. now my issue is with the profile pic. First of all, Im using Image picker package.

Future pickImage(ImageSource source) async {
    try {
      final image = await ImagePicker().pickImage(
          source: source);
      if (image == null) return;

      final UserImage = File(image.path);
      setState(() => this.image = UserImage );
    }on PlatformException catch (e){
      Utils.showSnackBar(e.message);
    }

  }

But with this code alone, everytime the app gets restarted the image will be null. So I tried to upload the image to the Firebase Storage when the user picks an image and generate a url:

Future uploadImage () async {

    FirebaseStorage storage = FirebaseStorage.instance;

    Reference ref = storage.ref().child(userID.toString());
    UploadTask uploadTask = ref.putFile(image!);
    uploadTask.whenComplete(() async {
      url = await ref.getDownloadURL(); }
    ).catchError((onError){
      print(onError);
    });
    return url;
  }

But again every time I restart the app, the url will be null. What is the best way to save the image permenantly when the user signs in for the first time.

edit: I want to store the image locally so that the user doesnt need an internet connection to load the image everytime he open the app.

Your answers and responses are highly appreciated.


Solution 1: Ahmad hassan

  1. you need to get folder directory first

    Future<String> getStorageDirectory() async {
    
         if (Platform.isAndroid) {
    
           return (await getExternalStorageDirectory()).path;  
             } else {
    
               return (await getApplicationDocumentsDirectory()).path;
             }
           }
    

  1. Add image in path

     uploadImage() async{
      String dir= getStorageDirectory();
      File directory = new File("$dir");
      if (directory.exists() != true) {
         directory.create();
      }
      final image = await ImagePicker().pickImage(
       source: source);
      if (image == null) return;
    
     final userImage = File(image.path);
     var newFile = await userImage.writeAsBytes(/* image bytes*/);
     await newFile.create();
     }