env

Load environment variables from .env files and system environment with type-safe access.

Features

  • Load variables from .env files with system environment fallback
  • Type-safe accessors for String, int, bool, double, Uri, and List
  • Three accessor variants per type: strict (throws), nullable, and default value
  • Support for comments, quoted values, and escape sequences
  • Synchronous and asynchronous loading
  • Create from platform environment or a Map (useful for testing)

Installation

dependencies:
  env: ^1.0.0

Usage

Loading Environment Variables

import 'package:env/env.dart';

// Load from .env file (async)
final env = await Env.load();

// Load from .env file (sync)
final env = Env.loadSync();

// Load from a custom path
final env = await Env.load(path: '.env.production');

// Load from system environment only
final env = Env.fromPlatform();

// Load from a map (useful for testing)
final env = Env.fromMap({'PORT': '8080', 'DEBUG': 'true'});

Accessing Variables

Each type has three accessor variants:

// Strict — throws EnvException if missing
final dbHost = env.getString('DB_HOST');
final port = env.getInt('PORT');

// Nullable — returns null if missing
final secret = env.getStringOrNull('SECRET');
final timeout = env.getIntOrNull('TIMEOUT');

// Default — returns fallback if missing
final port = env.getIntOr('PORT', 3000);
final debug = env.getBoolOr('DEBUG', false);

Supported Types

// String
env.getString('APP_NAME');

// int
env.getInt('PORT');

// bool (accepts: true/1/yes/on and false/0/no/off)
env.getBool('DEBUG');

// double
env.getDouble('RATE');

// Uri
env.getUri('DATABASE_URL');

// List (comma-separated by default)
env.getList('ALLOWED_HOSTS');
env.getList('TAGS', separator: ';');

.env File Format

# Comments are supported
APP_NAME=MyApp
PORT=8080
DEBUG=true

# Quoted values preserve whitespace
MESSAGE="Hello, World!"
SINGLE='raw string'

API Reference

EnvException Factories

  • EnvException.missing(key) — Key not found
  • EnvException.invalidType(key, type, value) — Value cannot be parsed
  • EnvException.fileError(path, reason) — File could not be loaded