0

I am using this package to set environment variables in flutter in a .env .

To read the variables I have to have this is my main.dart

Future main() async {
 await DotEnv().load('.env');
 runApp(MyApp());
} 

And then read like this

print(DotEnv().env['VAR_NAME']);

From this question, I can also add variables in the build command like this

flutter run --dart-define=APP_VERSION=0.1.2

And then to read the ones set in the build command, I have to do this

const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'development');

Is there please a way that I can read variables set in either the .env file or the build command the same way?

I will have the variables in my .env file for local development, and the in dev and prod environments they will be set via commands. So how can I find a way that works for both cases?

Thank you

asked Oct 7, 2020 at 18:11

1 Answer 1

2

I am not familiar with the package you mentioned, but a fairly safe bet would be as follows:

Create a singleton class that is responsible for handling environment variables:

final env = Env._();
class Env {
 Env._(); // private constructor to prevent accidental initialization
}

Create a method that gets an environment variable from its string, and choose something to default to. IMO I would give precedence to command line args, but that is a matter of taste:

String get(String key, {String defaultValue}) {
 final fromFile = DotEnv().env[key];
 final fromArgs = String.fromEnvironment(key);
// return the value from command line if it exists
// if not, return the value from .env file
// if still null, return a default
 return fromArgs ?? fromFile ?? defaultValue;
}

You can then access the data globally using:

env.get('MY_VARIABLE_NAME', defaultValue: 'hello');

For even more brevity, you can use Dart's callable classes, by renaming get() to call(), and then consume it using:

env('MY_VARIABLE_NAME', defaultValue: 'hello');
answered Oct 7, 2020 at 20:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.