DEV Community

01kg
01kg

Posted on

1

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay