Environment Variables

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.

Overview

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.

Setting Up Environment Variables

Android

  1. Create a .env file in the root directory of your Flutter project if it doesn't already exist.

  2. 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
  3. Add the flutter_dotenv package to your pubspec.yaml file:

    dependencies:
      flutter:
        sdk: flutter
      flutter_dotenv: ^5.0.2
  4. 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());
    }
  5. Access the environment variables using dotenv.env['KEY']:

    String apiKey = dotenv.env['API_KEY'] ?? 'default_value';

iOS

  1. Create a .env file in the root directory of your Flutter project if it doesn't already exist.

  2. 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
  3. Add the flutter_dotenv package to your pubspec.yaml file:

    dependencies:
      flutter:
        sdk: flutter
      flutter_dotenv: ^5.0.2
  4. 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());
    }
  5. Access the environment variables using dotenv.env['KEY']:

    String apiKey = dotenv.env['API_KEY'] ?? 'default_value';

Best Practices

  • Keep .env files out of version control: Add .env to your .gitignore file to prevent sensitive information from being exposed.
  • Use default values: Provide default values for environment variables in case they are not set.
  • Organize variables: Group related environment variables together to improve readability.

Common Issues

  • Environment variables not loading: Ensure that you have called dotenv.load() before accessing the variables.
  • Incorrect variable names: Double-check the keys you use to access environment variables match those defined in your .env file.