RIPPLES: Subekshya Kandel

OVERVIEW

In flutter development, there are many projects that require managing environment-specific values—like API keys, server URLs, or feature flags. It is very crucial to store such values properly to build secure and scalable applications. Managing these configurations can be quite daunting especially when switching between different environments: development, testing, and production. 

That is where .env comes in—a simple text file that contains key-value pairs.

SET-UP

Step 1: Add dependency

Open your pubspec.yaml and add:

dependencies:
flutter_dotenv: ^5.1.0 # or latest

Then run:
flutter pub get

Step 2: Create a .env file

Create a .env file in the root of your project:

API_URL=https://api.example.com
API_KEY=abcdef123456
DEBUG=true

 Step 3: Import and load the env file

 In your main.dart or your app’s entry point:

import ‘package:flutter/material.dart’;
import ‘package:flutter_dotenv/flutter_dotenv.dart’;

Future<void> main() async {

  // Load environment variables before running the app
    await dotenv.load(fileName: “.env”);

     runApp(MyApp());
}

Step 4: Use environment variables

Anywhere in your app:

import ‘package:flutter_dotenv/flutter_dotenv.dart’;

final apiUrl = dotenv.env[‘API_URL’];
final apiKey = dotenv.env[‘API_KEY’];
final debugMode = dotenv.env[‘DEBUG’] == ‘true’;

Step 5: Add .env to .gitignore

To keep secrets secure and avoid pushing them to GitHub:

# .gitignore
.env


SOME USEFUL TIP

  1. Check if .env is loaded and is in the correct path.
  2. Do not forget to include the .env file in your pubspec.yaml file.
    1. flutter:
    2.  assets:
    3.    – .env
  3. The key is spelled correctly and has no surrounding spaces.
  4. To make onboarding easier for teams create .env.example file. No need to hunt through code to find out which keys are needed.


Leave a Reply

Your email address will not be published. Required fields are marked *