Flutter_DotEnv: Load Configuration from .env Files
Published on by Flutter News Hub
Flutter_DotEnv is a Flutter library that allows developers to load configuration values from .env
files, which can be beneficial for managing sensitive information or environmental variables.
Usage
To use Flutter_DotEnv:
-
Create a
.env
file in the root of your project directory and add your configuration values.
FOO=foo
BAR=bar
FOOBAR=$FOO$BAR
-
Update your
pubspec.yaml
file to include the Flutter_DotEnv dependency and add the.env
file to your assets:
dependencies:
flutter_dotenv: ^5.0.0
assets:
- .env
-
Import Flutter_DotEnv into
main.dart
and load the.env
file:
import 'package:flutter_dotenv/flutter_dotenv.dart' as DotEnv;
Future main() async {
await DotEnv.load(fileName: ".env");
// Access environment variables using `DotEnv.env['VARIABLE_NAME']`
print(DotEnv.env['FOO']);
}
Advanced Usage
-
Referencing variables: You can reference variables defined earlier in the
.env
file using$
. -
Merging values: You can merge values from a map into the environment on load using
mergeWith
. -
Loading for tests: Use
testLoad
to load a static set of variables for testing purposes. -
Null safety:
get()
can be used to retrieve variables and throw an exception if they are undefined. Provide a default value usingfallback
. -
Usage with
Platform.environment
: Merge thePlatform.environment
map into the environment to access platform-specific values.
Benefits of Using Flutter_DotEnv
- Centralized configuration: Manage configuration values in one place outside of your codebase.
- Security: Keep sensitive information out of your code.
-
Environmental isolation: Easily switch between different environments (e.g., development, staging, production) by using different
.env
files. -
Flexibility: Load multiple
.env
files or merge values from other sources to customize your configuration.
Conclusion
Flutter_DotEnv is a valuable tool for handling configuration in Flutter apps. It simplifies the management of sensitive information, provides flexibility for environmental isolation, and promotes code reusability. Embrace Flutter_DotEnv to enhance the efficiency and security of your Flutter projects.