Reputation: 3438
Short story:
I am trying to use .env
file in my Flutter Web project.
I used flutter_dotenv
before in Flutter mobile app but it is not working in Flutter web.
How can we use .env file in Flutter web?
Long Story:
For now, I am using dart file to save current constant values such as backend url.
Backend is in same domain like this => https://domain_for_webapp.com/api/
class Environment {
// API URL
static const String API_URL ='https://domain_for_webapp.com/api/';
...
But problem here is I have one more server to deploy same site https://another_domain_for_webapp.com/api/
So I tried to solve that by using relative url
class Environment {
// API URL
static const String API_URL ='/api/';
...
But Flutter web can't find correct full API url for each server.
To solve this I have been trying to use .env
like in normal web app.
But I can't use .env
in Flutter web.
Is there any proper solution for this problem?
Upvotes: 18
Views: 17128
Reputation: 504
This Article talks about creating environment for Flutter on the web.
Using the
flutter run --dart-define=<VARIABLE>
command.
.
Upvotes: 0
Reputation: 146
Like mentioned here, you can rename your .env file to something that doesn't start with a dot. I've changed my .env file to "dotenv".
Upvotes: 13
Reputation: 40443
Unfortunately, .env doesn't seem to work with web as you've noticed. Hopefully it'll get integrated eventually, but for now when I had the same issue I found that the recommended way of configuring the web involves using environment variables and the dart-define
parameter:
String urlBase = const String.fromEnvironment("url_base");
This way you can set up your run and build environment with different variables.
Unfortunately, this isn't quite as 'set and forget' as a .env file, so I like to put a guard like this on it so that you're made aware of it immediately when you try running:
if (urlBase == null) {
throw Exception("You must define url_base. This can be done "
"with the --dart-define arg to run or build");
}
If you're using an IDE you will need to pass in the parameters. For Visual Studio Code you can do this with a launch.json
file something like this:
"configurations": [
{
"name": "Flutter",
"request": "launch",
"type": "dart",
"args": [
"--dart-define",
"url_base=https://myurl.com/base"
]
}
]
And for IntelliJ/Android Studio you can do it in the run configuration:
In whatever you use for your build tooling, it's as simple as adding the additional parameter to the flutter build web
command, i.e. with docker:
RUN /usr/local/flutter/bin/flutter build web --dart-define url_base=$url_base
Upvotes: 17