Serving Flutter Web Applications With Python-Flask | by Ajiri Gunn | Apr, 2022

There’ll be bugs preying in your each misstep so do effectively to not ignore the literature.

Serving Flutter internet apps on personal servers takes a little bit of effort. The problem is that if you launch the favored index.html file of a flutter internet construct, flutter renders your UI by working code within the predominant.dart.js and flutter_service_worker.js recordsdata — these recordsdata are someplace in your file tree.

Flutter additionally requires information from different asset recordsdata (photos, fonts, manifests and so on.) to correctly render your utility and people are elsewhere within the file tree. The problem is to serve these recordsdata to Flutter every time they’re requested over HTTP through the Flutter rendering course of.

The rationale simply acknowledged is why nothing often occurs if you launch the index.html file of a Flutter internet construct on a browser — there’s no API to serve the required recordsdata.

We might now be constructing a Flask undertaking that serves a Flutter internet utility with the required recordsdata as they’re requested by Flutter.

This text assumes that you’re accustomed to Flask and Flutter internet functions. You must be capable of observe alongside even in the event you’re solely a bit acquainted.

We might be following these 4 steps.

  1. Construct Flutter internet utility.
  2. Modify construct recordsdata for Flask API.
  3. Construct and configure Flask utility.
  4. Code REST API to serve Flutter functions.

In any case, make sure that your Flask app fulfils the necessities of steps 2 and 4.

Be happy to skip this step in the event you can generate and find your Flutter internet construct recordsdata.

My editor of selection is the good android studio. You may additionally use VSCode in fact. We’ll construct a Flutter utility so create one and name it flask_ui_app (or what you need — the drill). Don’t forget to allow internet help in the event you use the android studio.

Enabling internet help with android studio.

Within the occasion that you just create a undertaking with out internet help, you’ll be able to add it by way of terminal by coming into the next command.

> flutter create .

The place the terminal listing is about to the foundation of your present Flutter undertaking.

You must now see the net folder within the undertaking tree.

Net enabled flutter utility

Now run your Flutter internet utility to make sure it safely hundreds up the default counter utility.

Default flutter counter utility.

And now we will proceed to construct our launch recordsdata.

With the foundation folder of your command terminal set to that of the present Flutter undertaking, construct the net utility by coming into the next command.

> flutter construct internet --release -v

After the construct, you’ll find the net launch recordsdata within the path[project_root]/construct/internet/. We’ll be needing all of the recordsdata in that folder.

Net construct folder with launch recordsdata

This step requires solely that the index.html file within the internet construct folder be modified by changing the road:

<base href="/">

with

<base href="/internet/">

You’ll quickly see that ‘internet’ will be changed with one other time period reminiscent of ‘app’ so long as they correspond with the API routes.

It’s vital to repeat this step everytime you replace your Flutter internet construct.

When you’re already working with a Flask utility or you know the way to create a easy Flask app, you’ll be able to open up your Flask undertaking and skip this step.

Right here we will merely generate a Flask utility utilizing pip. To observe together with this step, you have to have Python, pip, and virtualenv put in in your system. You possibly can observe these guides in the event you should not have them put in.

Now create an empty undertaking folder and provides it a name- mine is flask_flutter_app. Navigate to the folder listing in your command terminal.

> cd [path to new project]

First, we’d be making a digital surroundings on this folder as is really helpful for Python tasks. You are able to do this by working the next command in your command terminal window.

> python -m venv env

Subsequent, we’ll activate the Python digital surroundings by working the next command within the terminal for Linux/mac customers.

> supply env/bin/activate

If on a home windows system, you’ll must run this as a substitute.

> .envScriptsactivate

Your terminal window ought to now point out that your digital surroundings is energetic.

(env)> 

Subsequent, we’ll set up Flask within the digital surroundings by working the next command.


(env)> pip set up flask

On to coding. We’ll be utilizing a Python file named app.py so create one within the undertaking root folder, open this file in your favourite code editor and paste the next setup code.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def say_hello():
return ('Good day world')

if __name__ == '__main__':
app.run()

The code snippet ought to look acquainted and it’s actually a really primary Flask utility.

We will check the app by working the next command within the terminal.

> flask run

At this level, the consequence ought to comprise one thing like this.


* Debug mode: off
* Working on http://127.0.0.1:5000/ (Press CTRL+C to give up)

And if launching the url http://127.0.0.1:5000/ in your browser exhibits a ‘howdy world’ textual content, then we’re good to go.

Now, the enjoyable begins. Very first thing to do is copy all of the recordsdata in your Flutter internet construct listing from step 1 to a brand new listing which we’d identify ‘templates’. Your Flask undertaking file tree ought to now appear to be this:

Flask Venture Construction

Flask takes particular notice of recordsdata within the templates listing. That listing is the place Flask would look when an API requests an internet web page from the Flask utility utilizing the built-in Flask methodology render_template.

Nonetheless, the default templates listing will be modified when instantiating the Flask app as proven within the following code snippet.

# Non-compulsory - not for this step
app = Flask(__name__, template_folder='internet')

All we now have to do is write API features that might return doc recordsdata within the Flutter internet construct folder utilizing the built-in Flask send_from_directory methodology.

First, add the next import statements to the highest of your app.py file.

from flask import Flask
from flask import send_from_directory
from flask import render_template

Subsequent, copy and paste this code into your Flask utility.

FLUTTER_WEB_APP = 'templates'

@app.route('/internet/')
def render_page_web():
return render_template('index.html')

@app.route('/internet/<path:identify>')
def return_flutter_doc(identify):

datalist = str(identify).cut up('/')
DIR_NAME = FLUTTER_WEB_APP

if len(datalist) > 1:
for i in vary(0, len(datalist) - 1):
DIR_NAME += '/' + datalist[i]

return send_from_directory(DIR_NAME, datalist[-1])

You’ll discover the render_page_web operate is connected to the internet route so the subsequent time you run your Flask utility, you’ll be capable of launch the Flutter app from the url [local_host]/internet .

I took my app a easy step additional and changed the house route with the identical rendering code — now the Flutter app is the house web page of my Flask utility.

@app.route('/')
def render_page():
return render_template('/index.html')

When you run the Flask app at this level, you’ll see the paperwork requested by Flutter after launching the index.html web page utilizing the [local_host]/internet url and the url sample for these requests.

Flask logs exhibiting flutter requests to fetch construct recordsdata.

You’ll discover that the trail to the requested recordsdata within the templates listing is embedded within the URL of the request. Therefore, the return_flutter_doc operate extracts the trail to the requested recordsdata from the request URL and serves the recordsdata from the templates folder over HTTP.

Discover all of the code on this GitHub Repository.

When you get the logic, it is best to be capable of conveniently serve your Flutter internet apps with any backend framework of your familiarity.

More Posts