如何判断Flutter应用是否处于生产环境?基于Dio实现API端点自动切换的方法
Hey there! Let's tackle your two related questions one by one—first how to check if your Flutter app is in production mode, then how to use that to auto-switch Dio's baseURL between environments.
The easiest and most reliable way to detect production mode in Flutter is using the kReleaseMode constant from the flutter/foundation.dart package. This is a built-in flag that Flutter sets automatically based on how you build your app:
kReleaseModeistruewhen you build a release (production) version (using commands likeflutter build apk,flutter build ios, orflutter build web)- It's
falsewhen you're running in debug mode (the default when you hit "Run" in your IDE) or profile mode.
First, import the required package:
import 'package:flutter/foundation.dart';
Then you can use it directly in your logic:
bool isProduction = kReleaseMode;
If you ever need to distinguish profile mode specifically, there are also kProfileMode and kDebugMode constants available in the same package.
Now that you can detect production mode, integrating this with Dio to switch your baseURL is straightforward. Here's a clean implementation of your desired logic:
Step 1: Define environment-specific URLs
It’s a best practice to keep these constants in a separate config file or class for easy maintenance, rather than hardcoding them directly:
// config/app_config.dart const String developmentBaseURL = "https://dev-api.yourdomain.com/"; const String productionBaseURL = "https://api.yourdomain.com/";
Step 2: Initialize Dio with conditional baseURL
Use kReleaseMode to automatically pick the right baseURL when setting up your Dio instance:
import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'config/app_config.dart'; // Initialize Dio with auto-switching baseURL Dio dio = Dio( BaseOptions( baseUrl: kReleaseMode ? productionBaseURL : developmentBaseURL, // Add other Dio configurations here (headers, timeout, etc.) connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10), ), );
Bonus: Scalable API Service (Optional)
For larger apps, wrapping Dio in a singleton service class helps manage your API instance consistently across the app:
class ApiService { static final ApiService _instance = ApiService._internal(); late Dio dio; factory ApiService() => _instance; ApiService._internal() { dio = Dio( BaseOptions( baseUrl: kReleaseMode ? productionBaseURL : developmentBaseURL, connectTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10), ), ); // Add interceptors here (logging, auth tokens, error handling, etc.) } }
You can then use this service anywhere in your app with ApiService().dio.get("/endpoint"), and the baseURL will automatically adapt to your current environment.
内容的提问来源于stack exchange,提问作者Baimam Boukar Jean Jacques

