As a Flutter Developer, there comes a time when you need to specify some confidential information in your source code such as API Keys, File Paths, URLs, Client-Side Secret Key etc, so the question arises that how would you:
βοΈ Keep this data confidential.
π Integrate it without disclosing it inside the source code.
π‘οΈ Protect it if a hacker dismantles the code.
To get into more details, read the medium article.
envify_demo
ββ lib
β ββ config
β β ββ env.dart // The Confidential Information.
β β ββ env.g.dart // The Generated File.
β ββ page
β β ββ envify_demo.dart // The Demo Page.
β ββ main.dart
ββ pubspec.lock
ββ pubspec.yaml
ββ README.md
ββ .env // The Environment File.
-
Add the envify package in the
pubspec.yaml
file.dependencies: flutter: sdk: flutter # A better way to handle environment variables using `.env` file. envify: ^2.0.2 dev_dependencies: # A build system for Dart code generation and modular compilation. build_runner: ^2.1.5 # A code generator for envify. envify_generator: ^2.0.2
-
Add all the files related to
envify
in the.gitignore
file.# Some files to ignore..... # Envify related .env env.dart env.g.dart
-
Outside the
lib
folder, create anEnvironment
file.API_KEY = 'PWEP198104102HEWFUQ' SITE_KEY = '91310!@31rwd2PZECAA' CLIENT_SECRET = 'XXXAd0q39e20q' CLIENT_ID = 'John Doe'
-
Under the
config
folder, create anenv.dart
fileimport 'package:envify/envify.dart'; part 'env.g.dart'; @Envify(name: 'Secret') abstract class Secret { /// Holds the API_KEY. static const api_key = _Secret.api_key; /// Holds the SITE_KEY. static const site_key = _Secret.site_key; /// Holds the CLIENT_SECRET. static const client_secret = _Secret.client_secret; /// Holds the CLIENT_ID. static const client_id = _Secret.client_id; }
-
Generate the
env.g.dart
using the belowcommand
from the terminal.flutter pub run build_runner build --delete-conflicting-outputs