15

How can I have build-time environment variables available to code within a Flutter app? (My specific use case is to inject app version number and commit hash into a debug screen. This information is available at build time, but not at runtime).

I had hoped to be able to do something like:

flutter run --dart-define=APP_VERSION=0.1.2

And then,

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

But this doesn't seem to work (I'm using Flutter 1.12.13+hotfix.5), and I'm not sure that is a supported feature in Flutter.

Matt R
  • 9,892
  • 10
  • 50
  • 83

2 Answers2

15

Starting from version 1.17 you actually can do that. Recently beta and dev channel got changes that allows you to define compile-time variables. Also you can define multiple variables like this

flutter run --dart-define=APP_VERSION=0.1.2 --dart-define=SOME_OTHER_VAR=SOME_OTHER_VALYE

Also it seems that those changes was cherrypicked, so quite possibly that we will see them in upcoming stable release (fingers crossed)

Update

So a new stable version of flutter is just rolled out. And it contains these changes with --dart-define. So starting from 1.17 you can use this key to define compile-time variables for your Flutter project.

tatsuDn
  • 2,019
  • 1
  • 9
  • 15
  • 6
    There's [an issue](https://github.com/flutter/flutter/issues/55870) with this right now if you _don't_ use `const` when retrieving the value on Flutter mobile clients. – Chance Snow May 10 '20 at 17:36
  • You do not have to do the double equals thing. This works: `--dart-define APP_VERSION=0.1.2` – Pat Niemeyer Sep 16 '21 at 21:08
1

You can use flavors to execute differents main.dart and inside these files you can set your values. But if you need to change build number when you build your app, you can use --build-number flag.

isacjunior
  • 462
  • 3
  • 3
  • Well, it's not workable to have a different `main.dart` for each version number or commit hash you might want to use. I'll investigate `--build-name` / `--build-number` for versioning, but it's not obvious how those could be accessed from code, nor do they help get other values (like a commit hash) available into the source. – Matt R Feb 03 '20 at 17:31