4.8 KiB
4.8 KiB
多环境配置说明
概述
前端应用现在支持多环境后端 API 配置,可以在开发、预发布和生产环境之间切换。
环境类型
1. 开发环境 (Development)
- 默认 API 地址:
http://localhost:8080/api/v1 - Android 模拟器:
http://10.0.2.2:8080/api/v1 - 用途: 本地开发和测试
2. 预发布环境 (Staging)
- 默认 API 地址:
http://your-staging-domain.com/api/v1 - 用途: 上线前测试
3. 生产环境 (Production)
- 默认 API 地址:
http://your-production-domain.com/api/v1 - 用途: 正式上线
使用方法
方法一:通过命令行参数设置
开发环境
flutter run --dart-define=ENVIRONMENT=development
预发布环境
flutter run --dart-define=ENVIRONMENT=staging
生产环境
flutter run --dart-define=ENVIRONMENT=production
自定义 API 地址
flutter run --dart-define=API_BASE_URL=http://192.168.1.100:8080/api/v1
方法二:通过开发者设置页面(推荐开发环境使用)
- 在应用的设置页面找到"开发者设置"选项
- 选择目标环境或输入自定义 API 地址
- 保存设置并重启应用
构建配置
Android 构建
开发版本
flutter build apk --dart-define=ENVIRONMENT=development
生产版本
flutter build apk --dart-define=ENVIRONMENT=production --release
iOS 构建
开发版本
flutter build ios --dart-define=ENVIRONMENT=development
生产版本
flutter build ios --dart-define=ENVIRONMENT=production --release
Web 构建
开发版本
flutter build web --dart-define=ENVIRONMENT=development
生产版本
flutter build web --dart-define=ENVIRONMENT=production --release
配置文件位置
环境配置文件位于:
lib/core/config/environment.dart
自定义环境配置
如需修改环境配置,编辑 environment.dart 文件:
static const Map<String, String> productionConfig = {
'baseUrl': 'http://your-production-domain.com/api/v1',
'wsUrl': 'ws://your-production-domain.com/ws',
};
常见场景
场景 1: 本地开发(Web)
- 设备: 开发电脑浏览器
- API 地址:
http://localhost:8080/api/v1 - 运行命令:
flutter run -d chrome
场景 2: Android 模拟器开发
- 设备: Android 模拟器
- API 地址:
http://10.0.2.2:8080/api/v1 - 运行命令:
flutter run -d android - 说明: 10.0.2.2 是 Android 模拟器访问宿主机 localhost 的特殊地址
场景 3: 真机调试
- 设备: 手机真机
- API 地址:
http://你的电脑IP:8080/api/v1 - 设置方法:
- 确保手机和电脑在同一局域网
- 查看电脑 IP 地址(如 192.168.1.100)
- 在开发者设置中输入:
http://192.168.1.100:8080/api/v1 - 或使用命令:
flutter run --dart-define=API_BASE_URL=http://192.168.1.100:8080/api/v1
场景 4: 生产环境部署
- 设备: 正式用户设备
- API 地址: 生产服务器地址
- 构建命令:
flutter build apk --dart-define=ENVIRONMENT=production --release
环境检测
在代码中可以使用以下方法检测当前环境:
import 'package:your_app/core/config/environment.dart';
// 检查是否为开发环境
if (EnvironmentConfig.isDevelopment) {
print('当前是开发环境');
}
// 检查是否为生产环境
if (EnvironmentConfig.isProduction) {
print('当前是生产环境');
}
// 获取当前 API 地址
String apiUrl = EnvironmentConfig.baseUrl;
print('API 地址: $apiUrl');
注意事项
- 重启应用: 修改环境配置后必须重启应用才能生效
- 生产环境: 生产环境配置应该在构建时通过命令行参数指定,不要在代码中硬编码
- 安全性: 不要在代码中提交敏感信息,如生产环境的真实 API 地址
- 测试: 切换环境后应该进行充分测试,确保 API 连接正常
- 网络权限: Android 需要在
AndroidManifest.xml中添加网络权限 - HTTPS: 生产环境建议使用 HTTPS 协议
故障排查
问题 1: Android 模拟器无法连接 localhost
解决方案: 使用 10.0.2.2 代替 localhost
问题 2: 真机无法连接开发服务器
解决方案:
- 确保手机和电脑在同一网络
- 检查防火墙设置
- 使用电脑的局域网 IP 地址
问题 3: 环境切换后仍然连接旧地址
解决方案: 完全关闭并重启应用
问题 4: iOS 模拟器无法连接
解决方案: iOS 模拟器可以直接使用 localhost,无需特殊配置