Creating API and REST with image picker (Flutter)

Viewed 714

Hi I want to make when you select image from galery using image picker it will send it via REST to API. I'm looking up how to do so and I still don't get it, I tried different methods but always millions of errors occur. So if anyone knows whats my best (easiest) approach to send image as multipart data to API it would mean the world. My goal is to connect flutters front end with pythons backend.

This is mine code so far:

class _MyHomePageState extends State<MyHomePage> {
  Future <File> file;

  void openGatePhoto() async {
    // ignore: deprecated_member_use
  this.setState(() {
     file =  ImagePicker.pickImage(source: ImageSource.gallery);
    });



    showDialog(
        context: context,
        builder: (context) => CustomDialogOpen(
              title: "Gates are open",
              description:
                  "Licence plate numbers have been successfully stored in the database",
            ));
  }

What this code does is takes picture from gallery and after you select it, it displays this popup message. Thanks in advance :D

1 Answers

First lets pick an image

` final pickedFile = await picker.getImage(source: ImageSource.camera);

then ifpickedFile !=null` we can upload to your rest api then if success we can show the dialog

you can use something like flutter bloc to better manage this

`
Response response;
var dio = Dio();
getAndUploadImage(){
final pickedFile = await picker.getImage(source: ImageSource.camera);
  if (pickedFile != null) {
//upload to your api
//i'll use [dio][1] here 
var file=File(pickedFile.path);
var formData = FormData.fromMap({
  'name': 'Jonh ',
  "myfile": await MultipartFile.fromFile(
          file.path,
          filename: file.path,
        ),

     });
var response = await dio.post('myUrl', data: formData);
if(response.statusCode==200){
showDialog(
        context: context,
        builder: (context) => CustomDialogOpen(
              title: "Gates are open",
              description:
                  "Licence plate numbers have been successfully stored in the database",
            ));
}
}else{
..
}
}
Related