Open In App

How to Add .env File in Flutter?

Last Updated : 16 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Environment variables are used to store sensitive data such as passwords, API credentials, and other information that should not be written directly in code. It cannot be uploaded to github, gitlab, and many others. It can be done in different ways in different programming languages. But now we will learn to add a .env file in flutter and access its variable. So we can use the package flutter_dotenv.

Step By Step Implementation

Step 1: Import Package to pubspec.yaml file

Run command in terminal:

flutter pub add flutter_dotenv

OR

Add manually in dependencies:

dependencies:
  flutter_dotenv: ^5.0.2

 

OR

If you using Visual Studio Code you can use these command 

For Windows - ctrl+shift+P
For macOS - command+shift+P

after that select add dart dependency and type flutter_dotenv // you can type any other package with these

 

Step 2: Create a .env File in the Project Folder either on lib or asset

 

Step 3: Add these File Paths to the pubspec.yaml file

assets:
  lib/.env # path to your .env

Example:

 

Step 4:  Load/Initialize the dotenv file in the Main Function 

await dotenv.load(fileName: ".env"  //path to your .env file);

Don’t forget to make the main function as future and add async to it.

Example:

 

Step 5: Add Variable to .env file

// Syntax
VAR_NAME = "variable value"

// Example
COST_FLUTTERWINGS = '$0'

// you can use # in .env file for comments
# This is a comment

 

Step 6: Get the .env file Variable 

import 'package:flutter_dotenv/flutter_dotenv.dart';
dotenv.env['VAR_NAME']; // This is to access variable name from .env file

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads