Reputation: 1736
I am configuring an API endpoint using the flutter package dio
! I have two API endpoints: one for development and another for production. I want my dio
baseURL to automatically switch between development and production endpoints.
Just like so
Dio(
baseURL: isProduction ? productionBaseURL : developmentBaseURL
......
);
How to know if my app is in production environment in Dart?
Upvotes: 7
Views: 4727
Reputation: 3547
if (kDebugMode) {
//your debug code
}
else {
//your release code
}
That's how I check it
Upvotes: 0
Reputation: 10319
Just check the kReleaseMode
global constant. It's true
if the application was compiled in release mode.
Or, I'd recommend that this info comes from an environment variable so it follows one of the bullets from The Twelve-Factor App (the Config bullet). And to get it and check do the following.
For example, IS_PRODUCTION
system environment variable:
final isProduction = Platform.environment['IS_PRODUCTION'] == '1';
Or, getting the dart-defines
compile-time environment variables:
const isProduction = String.fromEnvironment('IS_PRODUCTION') == '1';
There are 2 ways to set a dart-define
:
flutter run --dart-define=IS_PRODUCTION=1
, or;
flutter build <bundle> --dart-define=IS_PRODUCTION=1
;
Where <bundle>
can be: aar
, apk
, appbundle
, bundle,
web
, or windows
.
Note that dart-define
is compiled into the app itself. That's why they accept being const
declaration. From the command-line docs it says:
Additional key-value pairs that will be available as constants from the
String.fromEnvironment
,bool.fromEnvironment
,int.fromEnvironment
, anddouble.fromEnvironment
constructors.
Upvotes: 10
Reputation: 1207
Use can use flavors in flutter to setup two different environments for your app, one for testing and one for production. You can refer this official documentation.
Upvotes: 1
Reputation: 6106
You have to decide and check yourself what "production" means in a way that suits your app. It can be a runtime setting for example in in shared_preferences, or it can be a compile-time setting you pass to flutter build
.
I have implemented a pub.dev package firebase_options_selector that does this at runtime with a Firebase backend. You can use my source code as inspiration if you want.
Upvotes: 1