How to host flutter web with django

After running the command, copy the build\web directory from the flutter project to your django project. Let's say you put it at the root and renamed it to flutter_web_app.

So we have,

djangoproject
| djangoproject
| settings.py
| urls.py
| ...
| flutter_web_app
| ...
| other apps

Now edit the base tag in flutter_web_app/index.html to give the application a prefix. Note that the prefix/base should start and end with a /.

<head>
...
<base href="/flutter_web_app/">...
</head>

Now, in your djangoproject/urls.py, match the prefix and serve your flutter application.

from django.urls import path
from django.views.static import serve
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FLUTTER_WEB_APP = os.path.join(BASE_DIR, 'flutter_web_app')
def flutter_redirect(request, resource):
return serve(request, resource, FLUTTER_WEB_APP)
urlpatterns = [
...
path('flutter_web_app/', lambda r: flutter_redirect(r, 'index.html')),
path('flutter_web_app/<path:resource>', flutter_redirect),
]

Running this locally, url 127.0.0.1/flutter_web_app will serve our flutter_web_app/index.html.

All the files required by the flutter application are prefixed with flutter_web_app. For eg. main.dart.js is requested with a GET to flutter_web_app/main.dart.js. We extract the path after the prefix as resource and serve the corresponding file from flutter_web_app directory (flutter_redirect function).

--

--

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