'Image is null after its picked by using image_picker package and saved on local memory (flutter)

Description: I'm using (image_picker: ^0.8.5+3) package to pick the images from gallery and camera and then upload them on backend server (django by using django rest framework)

Issue: Image is getting null outside picker function, even though state has been set by using setSatet(() {}) method

Failed Solutions: I tried to save the image locally before uploading the image on the backend, But image still shown null once its used or referenced outside picker function

Note: backend API's works fine and i can upload images by using postman

picker function:

  // Get image from gallery and store it locally
  Future<File?> _getFromGallery() async {
    PickedFile? image = await ImagePicker.platform.pickImage(source: ImageSource.gallery);
    if (image == null) {
      return null;
    }

    final File file = File(image.path);
    final Directory directory = await getApplicationDocumentsDirectory();
    final imagepath = directory.path;
    final String fileName = path.basename(image.path);

    File newImage = await file.copy('$imagepath/$fileName');
    setState(() {
      _imagelocal = newImage;
      print('image.path1');
      print(_imagelocal!.path);
    });
  }

Uploading image function:

_uploadimage() async {
      Map<String,String> header = {
        "Content-Type":"application/octet-stream)"
      };
      print("uploaded image invoked");
      var request = http.MultipartRequest('POST', Uri.parse('http://192.168.1.15:8000/api/uploadimage'));
      
      // request.files.add(await http.MultipartFile('image',http.ByteStream(image.openRead()).cast(),await image.length(),filename:image.name, contentType: MediaType('image', 'jpg')));
      request.files.add(await http.MultipartFile('LoadModelImage',http.ByteStream(_imagelocal!.openRead()).cast(),await _imagelocal!.length(),));
      request.headers.addAll(header);
      //for completeing the request
      var response =await request.send();

      //for getting and decoding the response into json format
      var responsed = await http.Response.fromStream(response);
      final responseData = json.decode(responsed.body);


      if (response.statusCode==201) {
        print("SUCCESS");
        print(responseData);
      }
      else {
        print("ERROR");
      }

    }


Sources

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

Source: Stack Overflow

Solution Source