启动时按环回、局域网、公网顺序探测地址,换网络后会静默切到别处,排查 困难。改为代码内一个布尔开关选择环境,地址分别放在 dev_config.dart 与 prod_config.dart,不再探测;调试条改地址后直接重载,不再重新探测。 release 构建若仍是开发开关会启动即报错,避免线上包连开发机。
77 lines
2.3 KiB
Dart
77 lines
2.3 KiB
Dart
// Author: fruit.com.cn
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import 'app_config.dart';
|
|
|
|
/// Debug-only runtime server endpoint persisted outside build-time defines.
|
|
abstract final class ServerEndpoint {
|
|
/// Preference key used for the runtime server address.
|
|
static const String preferenceKey = 'dev.api_base_url';
|
|
|
|
/// Returns a normalized http(s) URL, or null for invalid input.
|
|
static String? normalize(String? raw) {
|
|
final value = raw?.trim() ?? '';
|
|
final uri = Uri.tryParse(value);
|
|
if (uri == null ||
|
|
(uri.scheme != 'http' && uri.scheme != 'https') ||
|
|
uri.host.isEmpty) {
|
|
return null;
|
|
}
|
|
return value.replaceFirst(RegExp(r'/+$'), '');
|
|
}
|
|
|
|
/// 运行时手改优先,其次构建期默认地址;两者都必须先通过规范校验。
|
|
static String resolve({required String? stored, required String fallback}) {
|
|
return normalize(stored) ?? normalize(fallback) ?? fallback;
|
|
}
|
|
|
|
/// Loads the persisted override before the app creates its ApiClient.
|
|
///
|
|
/// In release builds this returns immediately without reading preferences.
|
|
static Future<void> load({
|
|
bool debug = kDebugMode,
|
|
SharedPreferencesAsync? preferences,
|
|
}) async {
|
|
if (!debug) return;
|
|
try {
|
|
final prefs = preferences ?? SharedPreferencesAsync();
|
|
final stored = await prefs.getString(preferenceKey);
|
|
AppConfig.applyRuntimeBaseUrl(
|
|
resolve(stored: stored, fallback: AppConfig.baseUrl),
|
|
);
|
|
} catch (_) {
|
|
AppConfig.clearRuntimeBaseUrl();
|
|
}
|
|
}
|
|
|
|
/// Persists a normalized runtime endpoint.
|
|
static Future<bool> save(
|
|
String raw, {
|
|
SharedPreferencesAsync? preferences,
|
|
}) async {
|
|
final normalized = normalize(raw);
|
|
if (normalized == null) return false;
|
|
try {
|
|
await (preferences ?? SharedPreferencesAsync()).setString(
|
|
preferenceKey,
|
|
normalized,
|
|
);
|
|
AppConfig.applyRuntimeBaseUrl(normalized);
|
|
return true;
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// Removes the persisted runtime endpoint.
|
|
static Future<void> clear({SharedPreferencesAsync? preferences}) async {
|
|
try {
|
|
await (preferences ?? SharedPreferencesAsync()).remove(preferenceKey);
|
|
} catch (_) {
|
|
// Clearing an optional developer override is best effort.
|
|
}
|
|
}
|
|
}
|