Magnus
Magnus

Reputation: 18758

Can I use Custom Environment Variables in Flutter?

I want to configure our logging library differently than my coworkers, and I don't want to risk checking in my local configuration, i.e:

void main() {
  LOG.minLevel = Logger.VERBOSE;
  LOG.showSymbols = false;

  runApp( RestartWidget(child: ResponsApp()) );
}

I can of course manually exclude these lines every time I make a commit, but I will forget to do it sooner or later.

What would be the best way to safeguard against this code accidentally being checked in and run on my colleagues machines? Is there any way to silently check environment variables in Flutter/Dart (something like kDebugMode/ kReleaseMode but that I can customize on my local machine only)?

I'm using IntelliJ btw.

Upvotes: 6

Views: 7845

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126734

You can make use of compile-time environment variables:

--dart-define

flutter run (and other build commands) allow you to pass environment variables using --dart-define.
The syntax for that would be something like this:

flutter run --dart-define=VARIABLE_ONE=test --dart-define=VARIABLE_TWO=42

.fromEnvironment

You can use three predefined environment getters: String.fromEnvironment (base function), int.fromEnvironment, and bool.fromEnvironment.

The first argument is the variable name and the second argument is the fallback value.

Usage in code

So if you want to have different log modes, you could do something like this:

void main() {
  switch (const String.fromEnvironment('MIN_LOG_LEVEL', 'verbose')) {
    case 'verbose':
       LOG.minLevel = Logger.VERBOSE;
       break;
    case 'info':
       ..
       break;
    ...
  }

  ...
}

Usage when running

flutter run --dart-define=MIN_LOG_LEVEL=info

Note

The environment variables only work with the const modifier in dart2js (web release builds) because they only work as compile-time constants and not as runtime getters. See the GitHub issue for reference.

Upvotes: 12

Related Questions