When you are building a Flutter Web application that accesses a REST API, then the base URL of that API should be configurable, so that you can use a different API during development than the one which is used for the production system.
Dart Define
The simplest way to do that is to provide key-value declarations to the flutter run
or flutter build web
command, with the help of their --dart-define
parameter.
flutter run -d chrome --dart-define="apiBaseUrl=https://example.com"
Here is the help text for that parameter:
Additional key-value pairs that will be available as constants from the String.fromEnvironment, bool.fromEnvironment, int.fromEnvironment, and double.fromEnvironment constructors. Multiple defines can be passed by repeating "--dart-define" multiple times.
Those declarations can then be used in the Flutter app with the methods String.fromEnvironment
, bool.fromEnvironment
, int.fromEnvironment
, and double.fromEnvironment
. If the app was called without the key-value declaration of the respective name, then a default value will be used. So, when building the app for the production system you can define the key-value pair. And when during development you can use the default value.
void main() {
var apiBaseUrl = const String.fromEnvironment(
'apiBaseUrl',
defaultValue: 'http://localhost:8080',
);
initialiseContext(apiBaseUrl);
runApp(RegistrationDeskApp());
}
GitHub Action
If you are using GitHub Pages as production system and the flutter-gh-pages action to update them, then the API base URL for the production API can be configured like this:
- uses: bluefireteam/flutter-gh-pages@v7
with:
customArgs: --dart-define="apiBaseUrl=https://example.com"
To avoid committing the API base URL to the Git repository, it should be provided as a GitHub repository secret.
Here are some pointers on how this can be set up in the repository settings:
And here is how the secret can be used:
- uses: bluefireteam/flutter-gh-pages@v7
with:
customArgs: --dart-define="apiBaseUrl=${{ secrets.API_BASE_URL }}"
Alternatives
As usual, there are other possibilities for how the problem under discussion could have been solved.
Main profiles
You might want to define different versions of the main.dart
file for the respective environment. An example of this approach can be found in the Flutter template from Web Factory.
dotenv
The configuration could also have been done with a .env
file and the flutter_dotenv plugin.
Top comments (0)