AVAILABLE: 5
One of the main reasons Flutter is so popular is its ability to simplify complex tasks. Checking the build mode of your application is one such requirement developers often encounter. This is crucial for dynamically setting API Endpoints for Debug and Release modes, blocking certain in-development features, and even modifying analytics based on the mode in use.
So, how exactly can we achieve this in Flutter? Flutter's "foundation" package provides the following constants:
- kReleaseMode
- kProfileMode
- kDebugMode
These constants can be used to detect the mode in which your code should behave dynamically. In most cases, you’ll want to use the kReleaseMode
constant. This is set to true
only when the application is built using the --release
flag. Let's take a look at an example:
Example:
Here is the code for a URLController
class that can define API endpoints and routes for various requests:
import 'package:flutter/foundation.dart';
class URLController {
static const String _debugEndpoint = "https://localhost:3000";
static const String _productionEndpoint = "https://retroportalstudio/api";
static const String _endpoint = kReleaseMode ? _productionEndpoint : _debugEndpoint;
static const login = _endpoint + "/authenticate";
static const profile = _endpoint + "/profile";
}
In this case, we have two endpoints:
_debugEndpoint
for development purposes._productionEndpoint
for production builds of the app.
To choose between these, we define a third constant, _endpoint
. The value of this constant is determined by using the kReleaseMode
constant from the foundation package (imported above) to check if the app is running in Release mode. Based on this, the value of _endpoint
is set. We then use _endpoint
as the API Endpoint for our request routes, such as login
and profile
.
Testing the Setup
Now, if we run the app to display the login URL using the following code:
return Scaffold(
appBar: AppBar(
title: Text("Mode"),
),
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 50.0),
child: Text(
"${URLController.login}",
style: TextStyle(fontSize: 25),
),
),
),
);
We observe the following results:
- Debug Mode: Displays the Debug Endpoint URL.
- Release Mode: Displays the Production Endpoint URL.