If you need to configure eg. backend-api via variables / parameters in Flutter, most mention you should use: --dart-define / fromEnvironment
Unfortunately this method only works "locally" via eg run and build.
If you are trying to do the same it within Docker / k8s. (see my example below or grap the code from https://github.com/mklarsen/flutter4cicd ) then you will discover the flutter WebApp does NOT have any Environment variables, and this is despite the fact that the Docker container DOES have the variables.
If you are trying to do it within Docker. see the setup below - then you will find that the flutter WebApp does NOT have any Environment variables, and this is despite the fact that the Dockercontainer DOES have the variables.
So what to do then?, You can choose one of my suggestions below. I would of course like to hear if you have another solution.
Idea / workarounds:
- https://rebar-ahmad.medium.com/env-aware-flutter-apps-in-docker-b899d0deebfd
- https://pub.dev/packages/flutter_dotenv#-readme-tab-
- https://www.sandromaglione.com/techblog/how-to-use-environmental-variables-in-flutter
The above solutions will work / solved the job, but unfortunately not optimal, seen through my DevOps glasses. as I would prefer NOT to persist variables / secrets etc. in the Docker container.
(Of course, I don't know if I'm the only one with that view :-) )
This is my test code
Before you start copying/pasting code *Spoiler alert .-) * IT doesn't work, the variables is disappeared when you try to access the WebApp via Docker container.
#Dockerfile
FROM nginx:stable
ARG BACKEND_APIURL
ENV BACKEND_APIURL ${BACKEND_APIURL}
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
COPY ./build/web /usr/share/nginx/html
#nginx.conf
server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
#Builds.sh
flutter pub get
flutter config --enable-web
flutter build web -t lib/main.dart --release --dart-define BACKEND_APIURL=${BACKEND_APIURL}
docker build . -t flutter4devops
docker run --env "BACKEND_APIURL=somebackend.com" -p 80:80 flutter4devops
Note: you must of course have docker desktop and flutter sdk installed, etc. before you can try this project.
Grap the project from Github https://github.com/mklarsen/flutter4cicd
Best regards Martin