how to rename a pickedfile from image_picker in flutter?

I want to rename the image name which is a pickedfile type when i'm uploading that image to the server. when it's uploading image name automatically changes like this scaled_image_picker825656736600296027.jpg

getting image code :-

  void takePhoto(ImageSource source) async {
    final pickedFile = await _picker.getImage(
      source: source,
      imageQuality: 20,
    );
    setState(() {
      _imageFile = pickedFile;
    });
  }

uploading code is :-

void UploadImage() async {
    var request = http.MultipartRequest('POST', Uri.parse(URLs.image));
    request.fields['CompanyCode']=  "${widget.CompanyCode}";
    request.fields['empCode'] ='$user_id';
    request.fields['documentType']="POD";
    if (_imageFile != null && widget.image == null) {
      print('Original path: ${_imageFile.path}');
      String dir = path.dirname(_imageFile.path);
      String newPath = path.join(dir, widget.docketno + '-${DateTime.now()}.jpg');
      print('NewPath: ${newPath}');
       _imageFile.renameSync(newPath); // renameSync is showing error
      request.files
          .add(await http.MultipartFile.fromPath('file',_imageFile.path));
    }
    else if(_imageFile ==null && widget.image != null){
      print('AddingUserProfilePic ${widget.image.path}');
      request.files.add(await http.MultipartFile.fromPath('file', widget.image.path));
    }
    var response = await request.send();
    var responseBody = await http.Response.fromStream(response);
    myData = json.decode(responseBody.body);
    print('Status code is : ${response.statusCode}  && ${response}');
    if (response.statusCode == 200) {
      responseResult = myData['filePath'];
      print('the filepath is ' + responseResult.substring(60));
      image_path = responseResult.substring(60);
      Fluttertoast.showToast(msg: 'Uploaded Successfully');
      Navigator.push(context, MaterialPageRoute(builder: (context) => delivered(CompanyCode : widget.CompanyCode,docketno :widget.docketno,Year: widget.Year,
          drsno:widget.drsno,challan: widget.challan , package :widget.package , response : image_path)));
      // Navigator.popUntil(context, (route) {
      //   return count++ == 2;
      // });
    } else {
      Fluttertoast.showToast(msg: 'Upload Failed');
    }
  }

renameSync is showing the error that The method 'renameSync' isn't defined for the type 'PickedFile'. so how can i rename my image file????

1 answer

  • answered 2020-11-25 07:26 zhpoo

    PickedFile is not File, it's just a result object of picked file.

    You can use it's path to create a File and use File's renameSync:

    File(_imageFile.path).renameSync(newPath);