— Flutter, DotEnv — 1 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:
1dependencies: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
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:
1API_KEY=your_api_key2BASE_URL=http://api.example.com
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:
1assets:2 - .env
Also don't forget to add the file to .gitignore if that is your preference(it usually is in most cases).
To load the environment variables from the .env
file, use the following code snippet:
1import 'package:flutter_dotenv/flutter_dotenv.dart';2
3void main() async {4 await dotenv.load();5 runApp(MyApp());6}
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.
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';2
3void main() async {4 await dotenv.load();5 6 final apiKey = dotenv.env['API_KEY'];7 final baseUrl = dotenv.env['BASE_URL'];8 9 runApp(MyApp(apiKey: apiKey, baseUrl: baseUrl));10}11
12class MyApp extends StatelessWidget {13 final String apiKey;14 final String baseUrl;15
16 MyApp({required this.apiKey, required this.baseUrl});17
18 // Rest of the app implementation...19}
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.