POST a camera image to your API with Flutter and Dio.
May, 01 2020
Sign up for the Thingio beta
Thingio is a new IoT automation platform. Easily configure your projects to send text messages, emails, and more. No need to know cloud programming.
Dio is an HTTP client for flutter which is a useful way of sending form data to your back-end API. In this case, we're using form data to send an image from the phone camera to be processed on our backend.
Start a clean flutter project and install the following packages via pubspec.yaml (double check official docs for latest versions):
On the very top of your main.dart file add the required imports:
Now, using the template app, let’s gut the
_incrementCounter function and replace it with our own routine. We want to open up the camera and send the picture off to our server.
Rename declaration and call of
_choose and delete the original contents as shown below. Notice that
_choose is now an async function. We want to make sure we’re waiting for the data to return from the server before moving on.
Now let’s update _choose to take a picture and assign that picture to a File type variable — this will require the
Notice the call to
_upload(). Let’s fill that in next. Make sure to assign a variable for the end point of the call. This is the URL where your API request will be made. In my case, I am running a local server so my end point is
Here is where the actual form data is populated and posted. This requires the use of the
dart:convert import to parse the json response.
Here you may need to change the code based on what your response looks like after posting the image. My response contains a list:
histogram_counts, and a string:
Now clicking the floating “+” button will prompt the camera to open and post the image to your local server.
Now go do some cool machine learning stuff on the back-end! Checkout the full code for this tutorial on github.