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

user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

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');
cameron1024
  • 9,083
  • 2
  • 16
  • 36