Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: make build-time environment variables available to code

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.

like image 214
Matt R Avatar asked Feb 03 '20 12:02

Matt R


People also ask

How do you store environment variables in flutter?

You can add environment variables to your Flutter projects in App settings > Environment variables. Enter the name and the value of the variable.


2 Answers

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.

like image 160
tatsuDn Avatar answered Oct 18 '22 04:10

tatsuDn


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.

like image 34
isacjunior Avatar answered Oct 18 '22 03:10

isacjunior