Manage Flutter Env Files with Dotenv Environment Variable Package

Posted October 18, 2023
Manage Flutter Env Files with Dotenv Environment Variable Package

This guide teaches you how to set up a Flutter env variable file to manage your Flutter environment variables for both development and production environments.

What is Flutter env, and Why You Need dotenv

Env files save any sensitive variable you use in your apps, such as API tokens and other sensitive keys. In Flutter, you use the flutter_dotenv package to manage configuration settings and secrets for your development and deployment workflows.

Let’s dive in and learn how to dotenv and manage a Flutter env file for your environment variables.

Adding dotenv to Flutter

If you have an existing Flutter app, you must first download the flutter_dotenv package before creating your env file environment variables. Run the command to get the flutter_dotenv dependencies:

flutter pub add flutter_dotenv

If not, you can manually add dotenv in your app. Navigate to the pubspec.yaml file and add the flutter_dotenv package as a dependency under the dependencies section as follows:

dependencies:
  flutter:
    sdk: flutter
  flutter_dotenv: ^5.1.0

Manage Flutter Env Files with Dotenv Environment Variable Package

Then, run the following command to get Flutter dotenv installed.

  • For Dart projects:
dart pub get 
  • Flutter projects:
flutter pub get

That is all you need to get dotenv ready to set flutter env files

Setting Flutter dotenv to Use Env Files

Flutter must be able to recognize env files as environment variables. So, you must tell Flutter to do so.

Again, on your pubspec.yaml ensure you have a path corresponding to the location of the .env file added in your pubspec.yaml flutter assets section. If you are adding the .env file at the root of your project’s assets path should be as follows:

flutter:
  assets:
    - .env

Manage Flutter Env Files with Dotenv Environment Variable Package

Now go ahead and create your Flutter .env file and add your environment variables as follows, just as an example:

API_KEY=your_api_key
BASE_URL=https://api.example.com
DEBUG=true

In this case, you replace your_api_key and other environment variables with your actual environment-specific values.

At the same time, you can add a .gitignore and eliminate env files from version control such as GitHub.

*.env

Loading Flutter dotenv Variables using a Configuration Class

To manage the env environment variables, create a lib/config.dart. You will use this file to load the environment variables and make them accessible throughout your app. For example, considering the above .env file, your config.dart file should look as follows:

import 'package:flutter_dotenv/flutter_dotenv.dart';

class Config {
  static final String? apiKey = dotenv.env['API_KEY'];
  static final String? baseUrl = dotenv.env['BASE_URL'];
  static final bool debug = dotenv.env['DEBUG'] == 'true';
}

Loading Environment Variables in main.dart

You must load the env file to your main.dart. This way, you import the necessary packages and load the environment variables from the .env file. Your main.dart must have the following code sample:

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart' as dotenv;

void main() async{
  await dotenv.load(fileName: "/.env");
  runApp(const MyApp());
}

Using Environment Variables in Your App

You have everything ready. And you can use your environment variables right from your .env file as follows:

  • Import config.dart file:
import 'config.dart';
  • In a widget or other parts of your code, you can access Flutter dotenv environment variables as follows:
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ApiKeyScreen(),
    );
  }
}

class ApiKeyScreen extends StatelessWidget {
  const ApiKeyScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('API Key Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('API Key: ${Config.apiKey}'),
            Text('Base URL: ${Config.baseUrl}'),
          ],
        ),
      ),
    );
  }
}

If I run this example, I should be able to have the keys used on this APP:

flutter run

Manage Flutter Env Files with Dotenv Environment Variable Package

Switching Between Environments

If you’re using the app in development and production modes, you can use dotenv and switch between them. I.e., .env.production:, .env.staging: and .env.development:.

This way, your main.dart file will use conditional logic to check the .env file to load as follows:

void main() async {
  
  String envFile;
  if (const bool.fromEnvironment('dart.vm.product')) {
    envFile = '.env.production';
  } else {
    envFile = '.env.development';
  }

  await dotenv.load(fileName: envFile);
  runApp(const MyApp());
}

This donenv example will allow you to use the --dart-define flag during the build process, i.e.:

flutter run --dart-define=FLUTTER_APP_ENV=production

Conclusion

You learned how to use the Flutter env variable while utilizing the Flutter dotenv Flutter to manage environment variables.

I hope you found this helpful!

Further Reading

Manage Flutter Env Files with Dotenv Environment Variable Package

Written By:

Joseph Chege