Adding env to Flutter App

Every project usually has an environment file such as .env, you see it in laravel, Nextjs, and many more. So I started to find what package meets these needs because flutter itself I think you can’t just put .env.

$ flutter pub add envied
$ flutter pub add --dev envied_generator
$ flutter pub add --dev build_runner

You need to install all 3, the example in the package doesn’t explain that once you put in env you need to run flutter pub add --dev build_runner . So the steps are

1. make .env and lib/env.dart
2. in .env


3. in .env.dart

import 'package:envied/envied.dart';
part 'env.g.dart';

@Envied(path: '.env')
abstract class Env {
  @EnviedField(varName: 'API_URL', obfuscate: true)
  static final Uri apiUrl = _Env.apiUrl;

4. flutter pub run build_runner build --delete-conflicting-outputs
5. check env.g.dart if there's any result after run build

The most important thing is to add .gitignore so that when you commit you don't show the credential because the point of having .env is not committing to git.

envied | Dart Package
Explicitly reads environment variables into a dart file from a .env file for more security and faster start up times.

If there's an updated .env this is how you update the env.g.dart

// first need to clean
flutter pub run build_runner clean
flutter pub run build_runner build

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]