Skip to content

Checking out flutter_dotenv

Flutter, DotEnv1 min read

flutter_dotenv is a package that allows you to load environment variables from a .env file into your Flutter app. It provides an easy way to access these variables throughout your codebase without hardcoding them. You can store various values in the .env file, such as API endpoints, secret keys, or any other configuration setting specific to your app's environment.


To get started with flutter_dotenv, add the following dependency to your pubspec.yaml file:

2 flutter_dotenv: ^x.x.x

Replace x.x.x with the latest version of flutter_dotenv.

After adding the dependency, run the following command to fetch the package:

1flutter packages get

Setting up the .env file

Create a new file named .env at the root of your Flutter project. This file will contain your environment-specific configuration settings. Here's an example of how the .env file might look:


You can add as many variables as you need, with each variable on a new line in the format KEY=VALUE. Make sure not to include any spaces before or after the equals sign. Also make sure to add the file to your assets bundle in pubspec.yaml:

2 - .env

Also don't forget to add the file to .gitignore if that is your preference(it usually is in most cases).

Loading environment variables

To load the environment variables from the .env file, use the following code snippet:

1import 'package:flutter_dotenv/flutter_dotenv.dart';
3void main() async {
4 await dotenv.load();
5 runApp(MyApp());

This code should be placed in the main() function of your Flutter app. The dotenv.load() method loads the environment variables from the .env file into memory, making them accessible throughout your app.

Accessing environment variables

Once the environment variables are loaded, you can access them using the DotEnv class provided by flutter_dotenv. Here's an example of how to access a variable from the .env file:

1import 'package:flutter_dotenv/flutter_dotenv.dart';
3void main() async {
4 await dotenv.load();
6 final apiKey = dotenv.env['API_KEY'];
7 final baseUrl = dotenv.env['BASE_URL'];
9 runApp(MyApp(apiKey: apiKey, baseUrl: baseUrl));
12class MyApp extends StatelessWidget {
13 final String apiKey;
14 final String baseUrl;
16 MyApp({required this.apiKey, required this.baseUrl});
18 // Rest of the app implementation...

In this example, we're accessing the API_KEY and BASE_URL variables defined in the .env file and passing them as parameters to the MyApp widget.