Enhance your code with Environment variables

Brunno Marques
Flutter Brasil
Published in
2 min readApr 14, 2024

Manage Your Constants and environment variables easily with — dart-define-from-file.

Why should you use Environment variables?

In a server, you need to store all your sensitive variables inside a .env file so that you won’t need to recompile or change the code when creating a new server or migrating a service. The same principle applies to an App too, and you shouldn’t need to change the code to access a local server instead of the production, or to use another API key because it got revoked.

Always remenber, your code must be indifferent to whatever environment you’re in.

3 Steps to implement it in your Flutter Project

In Dart, you can use environment variables using tags, but you would need to add a new — dart-define tag for each one of the variables, however, if you are in a Flutter project, you can use the — dart-define-from-file and it makes handling the variables way easier. That’s said, let’s implement an environment with a Host and key as example variables with a simple 3 steps guide.

1. The .env file
Create a file named .env in the root of your dart project, containing the variables and it’s values

SERVER_HOST=https://example.com
API_KEY=1234k5678e9011y

2. Get the variable

Add a reference to the variables in your code with String.fromEnvironment

const serverHost = String.fromEnvironment('SERVER_HOST');
const apiKey = String.fromEnvironment('API_KEY');

3. The tag

Edit your run command to include the tag and the reference to the file.

flutter run --dart-define-from-file .env

Good Practices

Versioning: Under no circumstance, you should be versioning the .env file in the GitHub or equivalent, if we want to permit a customization for each environment, then this file should not be standard, but we can create an example by cloning the file with the name .env.example this way you can still declare what dependencies the project is expecting

Security: Whenever you have the .env with sensitive data like ApiKey, it creates security attention points for those variables, the main reason being that anything sent to the client can be exploitable, just have this in mind when using it.

If you want more tips, guidance or talk with me, be part of our awesome community in the Discord

--

--