50 lines
2.0 KiB
Dart
50 lines
2.0 KiB
Dart
import 'package:flutter/foundation.dart';
|
||
|
||
/// API 环境配置
|
||
///
|
||
/// ## 开发环境(按平台自动选择)
|
||
/// - **Android 真机/模拟器**:`http://localhost:12345/api`
|
||
/// 需要先做端口转发,把手机的 localhost 映射到电脑的 localhost:
|
||
/// ```
|
||
/// adb reverse tcp:12345 tcp:12345 # 每次插拔设备后需重新执行
|
||
/// adb reverse --list # 确认映射存在
|
||
/// ```
|
||
/// 好处:不受 Windows 防火墙影响,也不要求手机与电脑在同一 Wi-Fi。
|
||
/// 若不想用 adb reverse(仅模拟器可行),可用电脑局域网 IP 覆盖:
|
||
/// `flutter run --dart-define=API_BASE_URL=http://192.168.x.x:12345/api`
|
||
/// (模拟器也可直接用固定地址 `10.0.2.2:12345`)
|
||
/// - **Windows / Chrome / iOS 模拟器**:`http://localhost:12345/api`
|
||
///
|
||
/// ## 生产环境
|
||
/// HTTPS,无需关心明文流量问题。
|
||
const String kProdBaseUrl = 'http://103.36.220.231:12345/api';
|
||
const String kLocalBaseUrl = 'http://localhost:12345/api';
|
||
|
||
/// 手动覆盖地址(优先级最高):
|
||
/// `flutter run --dart-define=API_BASE_URL=http://<host>:12345/api`
|
||
const String _override = String.fromEnvironment('API_BASE_URL');
|
||
|
||
String get baseUrl {
|
||
if (_override.isNotEmpty) return _override;
|
||
if (!kDebugMode) return kProdBaseUrl;
|
||
return kLocalBaseUrl;
|
||
}
|
||
|
||
/// 静态资源根地址(去掉 `/api` 后缀)
|
||
///
|
||
/// 笔记附件由后端以 `/uploads/2026/09/22/xxx.png` 这种相对路径返回,
|
||
/// 客户端要拼上 host 才能加载。
|
||
String get assetBaseUrl {
|
||
const suffix = '/api';
|
||
return baseUrl.endsWith(suffix)
|
||
? baseUrl.substring(0, baseUrl.length - suffix.length)
|
||
: baseUrl;
|
||
}
|
||
|
||
/// 把后端返回的资源地址补成绝对地址(已经是 http(s) 的原样返回)
|
||
String resolveAssetUrl(String path) {
|
||
if (path.isEmpty) return path;
|
||
if (path.startsWith('http://') || path.startsWith('https://')) return path;
|
||
return path.startsWith('/') ? '$assetBaseUrl$path' : '$assetBaseUrl/$path';
|
||
}
|