Embedded web server in Flutter

Image for post
Image for post

Discover how to integrate a web server that allows uploading files in your app for Flutter (or server in Dart).

Motivation

But sometimes, there are projects where a mechanism is required to update the configuration or dynamic content without having direct access to the device (for example via WiFi).

In the case of iOS devices this is usually common in apps such as the VLC media player, where an embedded web server is created so that the user can easily upload its content (MKV, MP3, etc).

In our case, an app needed to be able to modify configuration files remotely.

Solution with http_server

The truth is that it is not well documented with examples but as you will see it is not complicated to put it into operation.

The first thing is to include the library as a dependency in our pubspec.yaml and run flutter packages get to update the dependencies.

dependencies: ... http_server: ^0.9.8+1

Then just include this code snippet in the root part of our main widget and call it from initState() for example.

Image for post
Image for post

The code is easy to understand.
The first thing that is done is to create a server in any interface of the system under port 8000.

Then to the stream server we apply a transformation to handle “POST” that preprocesses form and files.

The last part is the handler for the subscription to the stream.
Here by means of a switch the index of the end point of rise is handled directly. For the root page, the static HTML content of a file in assets is loaded (function_loadStatic) and it is used.

In the file upload part, it is expected that the file is in the “file” field and as an example of processing it is saved as “file”.

As you can see, in a few lines of code we have an embedded web server that accepts file uploads easily in Dart/Flutter.

Originally published at https://digitalilusion.com on March 13, 2019.

Written by

CTO @ Digitalilusion.com & DigitalSecured.net Beyond-Full-stack developer #go #python #kubernetes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store