How To Inject & Secure Confidential Information in your Flutter Source Code

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:

:heavy_check_mark: Keep this data confidential.

:syringe: Integrate it without disclosing it inside the source code.

:shield: Protect it if a hacker dismantles the code.

Have no fear, Envify is your secret vault..

  1. Add the envify package in the pubspec.yaml file.

        sdk: flutter
        # A better way to handle environment variables using `.env` file.
        envify: ^2.0.2
        # 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
  2. Add all the files related to envify in the .gitignore file.

    # Some files to ignore.....
    # Envify related 
  3. Outside the lib folder, create an Environment file.

    API_KEY = 'PWEP198104102HEWFUQ'
    SITE_KEY = '91310!@31rwd2PZECAA'
    CLIENT_SECRET = 'XXXAd0q39e20q'
    CLIENT_ID = 'John Doe'
  4. Under the config folder, create an env.dart file

    import '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;
  5. Generate the env.g.dart using the below command from the terminal.

    flutter pub run build_runner build --delete-conflicting-outputs