Search code examples
flutterdartdio

Flutter dio how to upload image


i try to send image to machine learning model with fast api it works fine with postman but when i try with dio package it gives me error the type is File and i want it to be png or jpg to work with the model and the api

here is the code for selecting image

import 'dart:io';

import 'package:breastcancer1/network/remote/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerPage extends StatefulWidget {
  const ImagePickerPage({Key? key}) : super(key: key);

  @override
  _ImagePickerPageState createState() => _ImagePickerPageState();
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  File? imageFile;

  final picker = ImagePicker();

  Future<void> _pickImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      imageFile = pickedFile != null ? File(pickedFile.path) : null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (imageFile != null) ...[
              Container(
                  height: 100, width: 100, child: Image.file(imageFile!)),
              const SizedBox(height: 20),
            ],
            ElevatedButton(
              onPressed: _pickImage,
              child: const Text('Select Image'),
            ),
            MaterialButton(
              onPressed: () {
                if (imageFile != null) {
                  print({"is it nulll        ${imageFile}"});
                  DioHelper.postImage(url: 'predict', query: {'image': imageFile}).then((value) {
                    print(value.data['class']);
                    print({"is it nosos nulll${imageFile.runtimeType}"});

                  }).catchError((error) {
                    print(error.toString());
                    print('why');
                  });
                } else {
                  print('No image selected');
                }
              },
              child: Text('press'),
            )
          ],
        ),
      ),
    );
  }
}

and here is the dio code

import 'package:dio/dio.dart';

class DioHelper{
  static Dio? dio;
  static init(){
    dio=Dio(
      BaseOptions(
        baseUrl: 'http://192.168.1.5:8000/',
        receiveDataWhenStatusError: true
      )
    );
  }

  static Future<Response> postImage({
    required String url,
    required Map<String,dynamic> query,
  })
  async
  {
    return await dio!.post( url, queryParameters: query, );
  }
}

and here is the error I/flutter (21041): DioError [bad response]: The request returned an invalid status code of 422.

i tried to ask chat gpt but still nothing it works fine with postman


Solution

  •  MaterialButton(
                  onPressed: () async{
                    if ( PateintCubit.get(context).imageFile != null) {
                      FormData formData = FormData.fromMap({
                        'image': await MultipartFile.fromFile( PateintCubit.get(context).imageFile!.path),
                      });
                      print({"is it nulll        ${ PateintCubit.get(context).imageFile?.runtimeType}"});
                      DioHelper.postImage(url: 'predict', query: formData).then((value) {
                        print(value.data['class']);
                        print({"is it nosos nulll${ PateintCubit.get(context).imageFile.runtimeType}"});
    
                      }).catchError((error) {
                        print(error.toString());
                        print('why');
                      });
                    } else {
                      print('No image selected');
                    }
                  },
                  child: Text('press'),
                )
    

    what i did to solve it