flutter_dotenv

repository·master·Indexed 42 days ago

https://github.com/java-james/flutter_dotenv

A Flutter package for loading configuration from .env asset files or strings. It provides a singleton for accessing environment variables with support for typed getters (int, double, bool), variable interpolation, and layering multiple environments via override files.

Tokens
3.7K
Snippets
21
Records
26
Agent score
54%

What's inside flutter_dotenv

  1. Understand environment variable precedence

    master

    When loading configuration, multiple sources can provide values. The parser keeps the first value it encounters for each key. The order of precedence (from highest to lowest) is:

    1. mergeWith (Programmatic key-value pairs)
    2. overrideWithFiles / overrideWith (Additional files or strings)
    3. Base file / string (The primary fileName or envString)

    Note: mergeWith values cannot be overridden by .env files. If you need the .env file to take precedence over programmatic values, use override files instead of mergeWith.

  2. Security warning: Do not store secrets in .env files

    master
    Flutter assets are bundled into the app binary and can be extracted by anyone. Do not store sensitive information like API keys, tokens, or passwords in your .env files. Use them only for non-sensitive client-side configuration such as API base URLs, feature flags, or timeout values.
  3. Layer multiple environments using override files

    master

    You can layer environment-specific values over a base configuration by using the overrideWithFiles parameter in load(). This allows you to have a shared .env and specific overrides like .env.staging.

    // .env contains base values
    // .env.staging contains overrides
    await dotenv.load(overrideWithFiles: ['.env.staging']);
  4. Quick start with flutter_dotenv

    master

    Follow these three steps to load and use environment variables from a .env file:

    1. Create a .env file in your project root with your key-value pairs.
    2. Register the file as an asset in your pubspec.yaml under the flutter: assets: section.
    3. Load the file in your main() function using await dotenv.load() before calling runApp().

    Important: Access variables inside functions, widgets, or services. Do not attempt to access them in top-level initializers, as they will run before main() completes.

    import 'package:flutter_dotenv/flutter_dotenv.dart';
    
    Future<void> main() async {
      await dotenv.load();
      runApp(const MyApp());
    }
    
    // Accessing values later in the app lifecycle
    final apiUrl = dotenv.get('API_URL');
    final retries = dotenv.getInt('MAX_RETRIES', fallback: 1);
    final debug = dotenv.getBool('DEBUG', fallback: false);
  5. Set up the code formatter (fmt.sh)

    master

    To ensure code follows the official Dart style, you can use the fmt.sh script. This requires the dart_style package to be installed globally via pub.

    Before running formatting tools, ensure ~/.pub_cache/bin is included in your $PATH.

    $ pub global activate dart_style
  6. Customize iOS launch screen assets

    master

    You can customize the iOS launch screen by replacing the image files within the LaunchImage.imageset directory or by using Xcode.

    Method 1: Direct File Replacement Replace the existing image files in example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ with your own assets.

    Method 2: Using Xcode

    1. Open your Flutter project's iOS workspace in Xcode using the command:
      open ios/Runner.xcworkspace
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the existing launch images.
    open ios/Runner.xcworkspace
  7. Preview documentation with docs.sh

    master

    To preview the dartdoc documentation for the project, use the docs.sh script. This requires the dartdoc package to be installed globally via pub.

    Before running documentation tools, ensure ~/.pub_cache/bin is included in your $PATH.

    $ pub global activate dartdoc
  8. Troubleshoot flutter_dotenv errors

    master
    ErrorCauseSolution
    FileNotFoundErrorThe file isn't registered as an asset.Add the exact path to flutter: assets: in pubspec.yaml and restart the app.
    EmptyEnvFileErrorThe env file or string has no content.Add at least one KEY=value entry, or use isOptional: true.
    NotInitializedErrorAccessing values before loading.Call await dotenv.load() in main() before runApp().
    NotInitializedError (in top-level)Values read in top-level initializers run before main().Move reads inside functions, widgets, or callbacks.
    FormatExceptionThe value can't be parsed as the requested type.Check the raw value with dotenv.env['NAME'].
  9. Parse environment variables with typed getters

    master

    Use typed getters to automatically parse values into int, double, or bool.

    • getBool recognizes true, false, 1, and 0 (case-insensitive).
    • All typed getters throw an AssertionError if the variable is missing and no fallback is provided.
    • They throw a FormatException if the value cannot be parsed into the requested type.
    final retries = dotenv.getInt('MAX_RETRIES', fallback: 3);
    final rate    = dotenv.getDouble('RATE', fallback: 0.5);
    final debug   = dotenv.getBool('DEBUG', fallback: false);
  10. Read environment variables using the dotenv singleton

    master

    The dotenv singleton provides several ways to access variables. Accessing a variable before calling load() or loadFromString() will throw a NotInitializedError.

    MethodReturnsWhen missing
    dotenv.env['NAME']String?null
    dotenv.get('NAME')StringThrows AssertionError
    dotenv.get('NAME', fallback: 'x')String`'x'
    dotenv.maybeGet('NAME')String?null
    dotenv.maybeGet('NAME', fallback: 'x')String?`'x'

    Use dotenv.env to access the loaded key-value map directly (read-only).

    // Required value (throws if missing)
    dotenv.get('API_URL');
    
    // Optional value with fallback
    dotenv.maybeGet('OPTIONAL_VAR', fallback: 'default');
    
    // Direct map access
    String? val = dotenv.env['NAME'];
  11. Merge with Platform.environment (Mobile/Desktop only)

    master

    On platforms where dart:io is available (mobile, desktop), you can merge system environment variables into dotenv. Merged values take precedence over values in the .env file.

    Note: Platform.environment is not available on Flutter web.

    import 'dart:io' show Platform;
    
    await dotenv.load(mergeWith: Platform.environment);