6

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.

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It should probably be mentioned in the answer that this will only work if using const String.fromEnvironment(). See [github.com/dart-lang/sdk/issues/42177]. Not using const always resulted in the default values for me.
@MagnusW Right! I added this :) Note that this is only the case with dart2js.
Great! Although, it seems to affect my Flutter app when I'm running it on Android as well?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.