Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variables in Flutter

Tags:

flutter

dart

For example, building a client for an API, like Twitch.

In a Dart CLI binary, I could use a generic environment variable, or a Dart definition variable. For example, using both as fallbacks:

main() {   String clientId =        // dart -dCLIENT_ID='abc bin/example.dart       // This is considered "compiled-into" the application.       const String.fromEnvironment('CLIENT_ID') ??        // CLIENT_ID='abc' dart bin/example.dart       // This is considered a runtime flag.       Platform.environment['CLIENT_ID'];    // Use clientId. } 

Does Flutter have a way of setting either/both of these, specifically...

  • During dev time
  • When shipped to prod

Happy to help with some docs once I figure out how :)

like image 985
matanlurey Avatar asked May 29 '17 20:05

matanlurey


People also ask

What is .env file in flutter?

env file which can be used throughout the application. The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code... they are a language- and OS-agnostic standard.

How do you use variables in flutter?

Although the name of the variable suggests that it should be an Integer type, but we can change the value anytime. Basically, the Dart programming language also has a type “dynamic”. If we do not initialise a variable, and use a keyword “var”, then it becomes “dynamically typed”.


2 Answers

For configuration a common pattern I've seen is to use separate main files instead. i.e.

flutter run -t lib/production_main.dart

and

flutter build apk -t lib/debug_main.dart

And then in those different main files set up the configurations desired.

In terms of reading ids, you can do that from arbitrary assets https://flutter.io/assets-and-images/.

I believe it is possible in Flutter to read from the environment as you suggest, however I don't know how to set those environment variables on iOS or Android.

like image 26
Eric Seidel Avatar answered Oct 03 '22 07:10

Eric Seidel


Starting from Flutter 1.17 you can define compile-time variables if you want to.

To do so just use --dart-define argument during flutter run or flutter build

If you need to pass multiple key-value pairs, just define --dart-define multiple times:

flutter run --dart-define=SOME_VAR=SOME_VALUE --dart-define=OTHER_VAR=OTHER_VALUE 

and then, anywhere in your code you can use them like:

const SOME_VAR = String.fromEnvironment('SOME_VAR', defaultValue: 'SOME_DEFAULT_VALUE'); const OTHER_VAR = String.fromEnvironment('OTHER_VAR', defaultValue: 'OTHER_DEFAULT_VALUE'); 

Also, they can be used in native layers too.

Here is an article that explains more.

like image 187
tatsuDn Avatar answered Oct 03 '22 07:10

tatsuDn