After building a flutter web app with
flutter build web
I want to serve the app using a simple Django server. How can I do that?
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).