Use Flutter to send a http Post-Request (containing an image) to a Flask API

You may already know how to choose an image from the gallery/camera (e.g. using image_picker library). You fill a global variable like File image; with the result of that picker. This could be as easy as:

import 'dart:io';
import 'package:image_picker/image_picker.dart';
class _MyHomePageState extends State<MyHomePage> {
  File image;
  final picker = ImagePicker();

  pickImageFromGallery(ImageSource source) async {
    final image = await picker.getImage(source: source);

    setState(() {
      this.image = File(image.path);

(Change the ImageSource source to match your desire: camera or gallery)

Then you can upload that file to your api. Using http library:

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

class _MyHomePageState extends State<MyHomePage> {
    var request = http.MultipartRequest(
    Map<String, String> headers = {"Content-type": "multipart/form-data"};
        filename: "filename",
        contentType: MediaType('image', 'jpeg'),
    print("request: " + request.toString());
    request.send().then((value) => print(value.statusCode));

For each one of these libraries, you have to add them as dependency inside pubspec.yaml in your flutter project:

cupertino_icons: ^0.1.3
http: ^0.12.2
image_picker: ^0.6.7

I have done similar work with Django and Flutter. I used image_picker to select image and used dio to upload image.

This is upload function:

  _upLoadImage(File image) async {
    setState(() {
      loadingdone = false;
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = FormData.fromMap({
        "img": await MultipartFile.fromFile(path,filename: name)

    Dio dio = new Dio();
    var respone = await<String>("", data: formData);
    if (respone.statusCode == 200) {
          msg: 'Done!',
          gravity: ToastGravity.BOTTOM,
          textColor: Colors.grey);
      setState(() {
          _label = jsonDecode(['label'];
          _score = jsonDecode(['score'];
          loadingdone = true;

Run upload function after select image:

  Future getImage() async {
    var image = await ImagePicker.pickImage(source:;
    setState(() {
      _image = image;