Environment variables are crucial for managing different configurations in your project. This guide will help you set up and manage environment variables in your Flutter project.
Environment variables are used to configure settings and manage sensitive information such as API keys and configuration options. In Flutter, you can use environment variables to keep this information separate from your codebase and manage it securely.
Create a .env
file in the root directory of your Flutter project if it doesn't already exist.
Add your environment variables to the .env
file in the format KEY=value
. For example:
API_KEY=your_api_key_here
BASE_URL=https://api.example.com
Add the flutter_dotenv
package to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
flutter_dotenv: ^5.0.2
Load the environment variables in your Dart code. Import flutter_dotenv
and load the environment variables at the start of your application:
import 'package:flutter_dotenv/flutter_dotenv.dart';
Future<void> main() async {
await dotenv.load();
runApp(MyApp());
}
Access the environment variables using dotenv.env['KEY']
:
String apiKey = dotenv.env['API_KEY'] ?? 'default_value';
Create a .env
file in the root directory of your Flutter project if it doesn't already exist.
Add your environment variables to the .env
file in the format KEY=value
. For example:
API_KEY=your_api_key_here
BASE_URL=https://api.example.com
Add the flutter_dotenv
package to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
flutter_dotenv: ^5.0.2
Load the environment variables in your Dart code. Import flutter_dotenv
and load the environment variables at the start of your application:
import 'package:flutter_dotenv/flutter_dotenv.dart';
Future<void> main() async {
await dotenv.load();
runApp(MyApp());
}
Access the environment variables using dotenv.env['KEY']
:
String apiKey = dotenv.env['API_KEY'] ?? 'default_value';
.env
files out of version control: Add .env
to your .gitignore
file to prevent sensitive information from being exposed.dotenv.load()
before accessing the variables..env
file.