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...
Happy to help with some docs once I figure out how :)
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.
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”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With