DotEnv In Flutter
flutter_dotenv
is a Flutter package that allows you to load environment variables from a .env
file in your Flutter application. An environment variable is a key-value pair that holds configuration information, such as API keys, database credentials, or any other sensitive data. By using a .env
file, you can separate your sensitive information from your codebase and easily manage different configurations for different environments (e.g., development, staging, production).
Here’s a brief introduction on how to use flutter_dotenv
:
- Add the
flutter_dotenv
package to yourpubspec.yaml
file:
dependencies:
flutter_dotenv: ^3.1.0
2. Run flutter pub get
to fetch the package.
3. Create a .env
file in the root directory of your Flutter project. This file will contain your environment variables in the format of KEY=VALUE
. For example:
API_KEY=your_api_key_here
4. add .env
file to the assets in pubspec.yaml file :
assets:
- .env
5. Import the flutter_dotenv
package in your Dart file:
import 'package:flutter_dotenv/flutter_dotenv.dart';
6. Load the environment variables from the .env
file:
void main() async {
await dotenv.load();
runApp(MyApp());
}
The dotenv.load()
function loads the environment variables from the .env
file and makes them accessible via the dotenv.env
object.
7. Access the environment variables in your code using the dotenv.env
object:
String apiKey = dotenv.env['API_KEY']!;
You can access the values of environment variables using the key provided in the .env
file. If the environment variable is not found or empty, you can provide a default value or handle it accordingly.
By using flutter_dotenv
, you can separate your sensitive information from your codebase, easily manage different configurations, and ensure that your sensitive data is not exposed in your version control system.