DEV Community

01kg
01kg

Posted on

Flutter Web | Build with .env File

Managing .env like files is a means of preventing hard-coded credentials and separating environments.

It is good to implement multiple .env files, e.g. .env.production, .env.development in Flutter app.

Then add some code before dotenv.load can do environments separation:

// main.dart
...
void main() async {
  const environment =
      String.fromEnvironment('ENV', defaultValue: 'development');
  await dotenv.load(fileName: '.env.$environment');
...
Enter fullscreen mode Exit fullscreen mode

Then run command like flutter build web --dart-define ENV=production to spin it up.

But, here is a pitfall. In my practical learning, a file starts with dot . could cause 404 issue:

404 error on fetching .env.production file

So, according to this suggestion, we'd better use "dot" instead of ".".

1. Rename .env.production, .env.development files to dotenv.production, dotenv.development

2. Update assets settings

Flutter's assets setting section

3. Update dotenv.load logic

// main.dart
...
void main() async {
  const environment =
      String.fromEnvironment('ENV', defaultValue: 'development');
  await dotenv.load(fileName: 'dotenv.$environment');
...
Enter fullscreen mode Exit fullscreen mode

4. Update .gitignore file

5. After building, delete unnecessary dotenv.* files in build > web > assets

files in build folder

In this case, dotenv.development is not necessary, so delete it to prevent potential sensitive data leaking.

Top comments (0)