feat: 完成智能电网电工端 Flutter 应用初始化

创建完整的 Flutter 项目结构,包含 Android 和 iOS 平台配置、核心网络层、路由、状态管理及业务模块(订单、收益、认证),适配原 uni-app 项目功能逻辑
This commit is contained in:
andyesfly committed 2026-10-06 11:54:10 +08:00
commit 56830e94ec
108 files changed
+9272

No files matched your search

@@ -0,0 +1,100 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/providers.dart';
import '../../../core/storage/token_storage.dart';
import '../data/auth_api.dart';
import '../data/auth_models.dart';
final authApiProvider = Provider<AuthApi>(
(ref) => AuthApi(ref.watch(apiClientProvider)),
);
class SessionState {
const SessionState({this.worker, required this.isLoggedIn});
final WorkerInfo? worker;
final bool isLoggedIn;
SessionState copyWith({WorkerInfo? worker, bool? isLoggedIn}) =>
SessionState(
worker: worker ?? this.worker,
isLoggedIn: isLoggedIn ?? this.isLoggedIn,
);
}
/// 登录态。对应源 `store/user.ts` 的登录/登出与本地缓存恢复。
class SessionController extends Notifier<SessionState> {
TokenStorage get _storage => ref.read(tokenStorageProvider);
@override
SessionState build() {
// 拦截器判定会话失效(401)时,清空本地会话并回到登录页。
final sub = ref
.watch(apiClientProvider)
.onUnauthorized
.listen((_) => clearLocal());
ref.onDispose(sub.cancel);
final cached = _storage.userInfo;
return SessionState(
worker: cached == null ? null : WorkerInfo.fromJson(cached),
isLoggedIn: _storage.hasSession,
);
}
/// 登录成功后写入 token 与电工信息。
Future<void> login({
required String phone,
required String password,
}) async {
final res = await ref
.read(authApiProvider)
.login(phone: phone, password: password);
if (!res.isOk || res.data == null) {
throw AuthException(res.message.isEmpty ? '登录失败' : res.message);
}
final data = res.data!;
await _storage.setAccessToken(data.token);
await _storage.setUserInfo(data.workerInfo.toJson());
state = SessionState(worker: data.workerInfo, isLoggedIn: true);
}
/// 从后端刷新电工信息(「我的」页进入时调用)。
Future<WorkerInfo?> refreshProfile() async {
try {
final res = await ref.read(authApiProvider).profile();
if (res.isOk && res.data != null) {
final info = res.data!.basic;
await _storage.setUserInfo(info.toJson());
state = SessionState(worker: info, isLoggedIn: true);
return info;
}
} catch (_) {
// 拉取失败保持原状态
}
return null;
}
Future<void> logout() async {
await _storage.clearSession();
state = const SessionState(isLoggedIn: false, worker: null);
}
/// 清空本地会话但不跳转(被拦截器判定会话失效时调用)。
Future<void> clearLocal() => logout();
}
final sessionProvider = NotifierProvider<SessionController, SessionState>(
SessionController.new,
);
/// 会话层业务异常,携带后端返回的可读 message。
class AuthException implements Exception {
const AuthException(this.message);
final String message;
@override
String toString() => message;
}
+58
View File
@@ -0,0 +1,58 @@
import '../../../core/network/api_client.dart';
import '../../../core/network/api_response.dart';
import 'auth_models.dart';
/// 认证与个人资料接口,对应后端 `/api/worker-app/auth/*` 与 `/profile`。
class AuthApi {
AuthApi(this._client);
final ApiClient _client;
Future<ApiResponse<LoginResult>> login({
required String phone,
required String password,
}) => _client.post<LoginResult>(
'/worker-app/auth/login',
body: {'phone': phone, 'password': password},
parse: (d) => LoginResult.fromJson((d as Map).cast<String, dynamic>()),
needAuth: false,
);
Future<ApiResponse<WorkerInfo>> register({
required String workerName,
required String phone,
required String password,
String? idCard,
String? workerTitle,
}) => _client.post<WorkerInfo>(
'/worker-app/auth/register',
body: {
'workerName': workerName,
'phone': phone,
'password': password,
if (idCard != null && idCard.isNotEmpty) 'idCard': idCard,
if (workerTitle != null && workerTitle.isNotEmpty) 'workerTitle': workerTitle,
},
parse: (d) => WorkerInfo.fromJson((d as Map).cast<String, dynamic>()),
needAuth: false,
);
Future<ApiResponse<WorkerProfile>> profile() => _client.get<WorkerProfile>(
'/worker-app/profile',
parse: (d) => WorkerProfile.fromJson((d as Map).cast<String, dynamic>()),
);
Future<ApiResponse<WorkerInfo>> updateProfile({
String? workerName,
String? idCard,
String? workerTitle,
}) => _client.put<WorkerInfo>(
'/worker-app/profile',
body: {
'workerName': ?workerName,
'idCard': ?idCard,
'workerTitle': ?workerTitle,
},
parse: (d) => WorkerInfo.fromJson((d as Map).cast<String, dynamic>()),
);
}
+151
View File
@@ -0,0 +1,151 @@
import '../../../core/utils/id_util.dart';
/// 电工基础信息,对应后端 `WorkerAppService.basicInfo()`。
class WorkerInfo {
const WorkerInfo({
required this.id,
required this.workerName,
required this.phone,
required this.workerTitle,
required this.auditStatus,
required this.status,
required this.rating,
required this.completedCount,
});
final int id;
final String workerName;
final String phone;
final String workerTitle;
/// 审核状态:0 待审核 / 1 已通过 / 2 已驳回
final int auditStatus;
/// 在职状态:0 离职 / 1 在职
final int status;
final double rating;
final int completedCount;
String get displayName => workerName.isNotEmpty ? workerName : phone;
/// 头像占位文字:取显示名首个字符(按 Unicode 码点截取,兼容中文)。
String get avatarText =>
displayName.isEmpty ? '电' : String.fromCharCode(displayName.runes.first);
bool get isApproved => auditStatus == 1;
String get auditStatusText => switch (auditStatus) {
0 => '待审核',
1 => '已通过',
2 => '已驳回',
_ => '未知',
};
factory WorkerInfo.fromJson(Map<String, dynamic> json) => WorkerInfo(
id: toIntOr(json['id'], 0),
workerName: json['workerName'] as String? ?? '',
phone: json['phone'] as String? ?? '',
workerTitle: json['workerTitle'] as String? ?? '',
auditStatus: toIntOr(json['auditStatus'], 0),
status: toIntOr(json['status'], 0),
rating: toDoubleOr(json['rating'], 5),
completedCount: toIntOr(json['completedCount'], 0),
);
Map<String, dynamic> toJson() => {
'id': id,
'workerName': workerName,
'phone': phone,
'workerTitle': workerTitle,
'auditStatus': auditStatus,
'status': status,
'rating': rating,
'completedCount': completedCount,
};
}
/// 登录返回体。
class LoginResult {
const LoginResult({required this.token, required this.workerInfo});
final String token;
final WorkerInfo workerInfo;
factory LoginResult.fromJson(Map<String, dynamic> json) => LoginResult(
token: json['token'] as String? ?? '',
workerInfo: WorkerInfo.fromJson(
(json['workerInfo'] as Map?)?.cast<String, dynamic>() ?? const {},
),
);
}
/// 电工资质证照,对应 `worker_cert` 表。
class CertInfo {
const CertInfo({
required this.id,
required this.certType,
required this.certNo,
required this.issueAuthority,
required this.issueDate,
required this.expireDate,
required this.certImageUrl,
required this.status,
});
final int id;
final String certType;
final String certNo;
final String issueAuthority;
final String issueDate;
final String expireDate;
final String certImageUrl;
/// 有效期状态:0 正常 / 1 即将到期 / 2 已过期
final int status;
factory CertInfo.fromJson(Map<String, dynamic> json) => CertInfo(
id: toIntOr(json['id'], 0),
certType: json['certType'] as String? ?? '',
certNo: json['certNo'] as String? ?? '',
issueAuthority: json['issueAuthority'] as String? ?? '',
issueDate: json['issueDate'] as String? ?? '',
expireDate: json['expireDate'] as String? ?? '',
certImageUrl: json['certImageUrl'] as String? ?? '',
status: toIntOr(json['status'], 0),
);
}
/// 个人资料,对应 `GET /api/worker-app/profile`。
class WorkerProfile {
const WorkerProfile({
required this.basic,
required this.idCard,
required this.auditRemark,
required this.certStatus,
required this.certs,
});
final WorkerInfo basic;
final String idCard;
final String auditRemark;
/// 资质汇总状态:none / valid / expiring / expired
final String certStatus;
final List<CertInfo> certs;
/// 「我的」页证书区取首张证书展示(源页面只展示一张「电工职业资格证」)。
CertInfo? get primaryCert => certs.isEmpty ? null : certs.first;
factory WorkerProfile.fromJson(Map<String, dynamic> json) => WorkerProfile(
basic: WorkerInfo.fromJson(json),
idCard: json['idCard'] as String? ?? '',
auditRemark: json['auditRemark'] as String? ?? '',
certStatus: json['certStatus'] as String? ?? 'none',
certs:
(json['certs'] as List?)
?.map((e) => CertInfo.fromJson((e as Map).cast<String, dynamic>()))
.toList() ??
const [],
);
}
@@ -0,0 +1,717 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/env.dart';
import '../../../core/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../shared/widgets/app_feedback.dart';
import '../../../shared/widgets/x_common.dart';
import '../../../shared/widgets/x_icon.dart';
import '../application/session_controller.dart';
/// 是否在 release 包里也显示「服务端设置」入口。
///
/// 默认关闭,正式包不暴露改地址的口子;打内部测试包时用
/// `--dart-define=ENABLE_SERVER_SETTINGS=true` 打开。
const _serverSettingsEnabled = bool.fromEnvironment('ENABLE_SERVER_SETTINGS');
/// 登录页,对应源 `pages/login/index.vue`。
///
/// **与源的差异(已与用户确认)**:源为「手机号 + 验证码」,后端只支持
/// 「手机号 + 密码」,故此处改为手机号 + 密码,并新增注册入口。
class LoginPage extends ConsumerStatefulWidget {
const LoginPage({super.key});
@override
ConsumerState<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends ConsumerState<LoginPage> {
final _phone = TextEditingController();
final _password = TextEditingController();
bool _agree = false;
bool _obscure = true;
bool _loading = false;
String _error = '';
@override
void initState() {
super.initState();
_phone.addListener(_onChanged);
_password.addListener(_onChanged);
}
@override
void dispose() {
_phone.dispose();
_password.dispose();
super.dispose();
}
void _onChanged() => setState(() {});
bool get _canLogin =>
_phone.text.length == 11 && _password.text.length >= 6 && _agree;
Future<void> _handleLogin() async {
if (!_canLogin) {
if (!_agree) _error = '请先阅读并同意服务协议与隐私政策';
setState(() {});
return;
}
setState(() {
_loading = true;
_error = '';
});
try {
await ref
.read(sessionProvider.notifier)
.login(phone: _phone.text.trim(), password: _password.text);
if (!mounted) return;
context.go('/tabs');
} on AuthException catch (e) {
if (mounted) setState(() => _error = e.message);
} catch (_) {
if (mounted) setState(() => _error = '网络异常,请检查服务端地址');
} finally {
if (mounted) setState(() => _loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFFF0F4FF), Color(0xFFFAF9FE)],
),
),
child: Stack(
children: [
Positioned.fill(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(24, 80, 24, 60),
child: Column(
children: [
_buildLogoSection(),
_buildFormSection(),
_buildOtherLogin(),
_buildAgreement(),
const SizedBox(height: 24),
_buildRegisterEntry(),
],
),
),
),
// 测试用「服务端设置」入口:调试版常显,release 需显式开关
if (kDebugMode || _serverSettingsEnabled)
Positioned(
top: 0,
right: 0,
child: SafeArea(
child: GestureDetector(
onTap: _openServerSettings,
behavior: HitTestBehavior.opaque,
child: const Padding(
padding: EdgeInsets.all(12),
child: XIcon(
'settings',
size: 22,
color: AppColors.textMuted,
),
),
),
),
),
],
),
),
);
}
Future<void> _openServerSettings() => showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: AppColors.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xxl)),
),
builder: (_) => const _ServerSettingsSheet(),
);
// ---- 各区块 ----
Widget _buildLogoSection() {
return Padding(
padding: const EdgeInsets.only(bottom: 48),
child: Column(
children: [
// .logo 96×96 / #0052ff / radius 20 / 0 8px 24px rgba(0,82,255,.3)
Container(
width: 96,
height: 96,
margin: const EdgeInsets.only(bottom: 24),
decoration: BoxDecoration(
color: AppColors.primary,
borderRadius: BorderRadius.circular(20),
boxShadow: const [
BoxShadow(
color: Color(0x4D0052FF),
blurRadius: 24,
offset: Offset(0, 8),
),
],
),
alignment: Alignment.center,
child: const XIcon('shandian', size: 48, color: Colors.white),
),
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
'VoltLink',
style: AppTypography.displayMd.copyWith(
color: AppColors.onSurface,
),
),
),
const Text(
'欢迎回到 VoltLink',
style: TextStyle(fontSize: 16, color: AppColors.textMuted),
),
],
),
);
}
Widget _buildFormSection() {
return Padding(
padding: const EdgeInsets.only(bottom: 48),
child: Column(
children: [
// .input-group:白底 / radius 16 / padding 1px
Container(
decoration: BoxDecoration(
color: AppColors.surfaceContainerLowest,
borderRadius: BorderRadius.circular(AppRadius.xl),
),
child: Column(
children: [
_buildPhoneRow(),
_buildPasswordRow(),
],
),
),
const SizedBox(height: 24),
_buildLoginButton(),
if (_error.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 14),
child: Text(
_error,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 13, color: AppColors.error),
),
),
],
),
);
}
/// 手机号行:+86 国家码 + 分隔线 + 输入框。
Widget _buildPhoneRow() {
return Container(
height: 56,
decoration: const BoxDecoration(
border: Border(bottom: BorderSide(color: AppColors.surfaceContainerHighest)),
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: [
Text(
'+86',
style: AppTypography.bodyLg.copyWith(
fontWeight: FontWeight.w600,
color: AppColors.onSurface,
),
),
const SizedBox(width: 4),
const Text(
'▼',
style: TextStyle(fontSize: 12, color: AppColors.textMuted),
),
],
),
),
Container(width: 1, height: 32, color: AppColors.surfaceContainerHighest),
Expanded(
child: TextField(
controller: _phone,
keyboardType: TextInputType.phone,
maxLength: 11,
style: const TextStyle(fontSize: 17, color: AppColors.onSurface),
cursorColor: AppColors.primary,
decoration: _inputDecoration('请输入手机号码'),
),
),
],
),
);
}
/// 密码行:源为「验证码 + 获取验证码」,后端改为密码,右侧按钮换成明文切换。
Widget _buildPasswordRow() {
return SizedBox(
height: 56,
child: Row(
children: [
Expanded(
child: TextField(
controller: _password,
obscureText: _obscure,
style: const TextStyle(fontSize: 17, color: AppColors.onSurface),
cursorColor: AppColors.primary,
decoration: _inputDecoration('请输入密码(至少 6 位)'),
),
),
GestureDetector(
onTap: () => setState(() => _obscure = !_obscure),
behavior: HitTestBehavior.opaque,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 12,
),
child: Text(
_obscure ? '显示' : '隐藏',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
color: AppColors.primary,
),
),
),
),
],
),
);
}
InputDecoration _inputDecoration(String hint) => InputDecoration(
isDense: true,
border: InputBorder.none,
counterText: '',
contentPadding: const EdgeInsets.symmetric(horizontal: 20),
hintText: hint,
hintStyle: const TextStyle(fontSize: 17, color: AppColors.textPlaceholder),
);
Widget _buildLoginButton() {
final enabled = _canLogin && !_loading;
return GestureDetector(
onTap: enabled ? _handleLogin : null,
behavior: HitTestBehavior.opaque,
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
height: 56,
decoration: BoxDecoration(
color: enabled ? AppColors.primary : AppColors.textPlaceholder,
borderRadius: BorderRadius.circular(AppRadius.xl),
boxShadow: enabled
? const [
BoxShadow(
color: Color(0x4D0052FF),
blurRadius: 20,
offset: Offset(0, 8),
),
]
: null,
),
alignment: Alignment.center,
child: _loading
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation(Colors.white),
),
)
: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Text(
'立即登录',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
SizedBox(width: 8),
Text(
'→',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w300,
color: Colors.white,
),
),
],
),
),
);
}
Widget _buildOtherLogin() {
return Padding(
padding: const EdgeInsets.only(bottom: 48),
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(bottom: 24),
child: Row(
children: [
Expanded(
child: SizedBox(
height: 1,
child: ColoredBox(color: AppColors.surfaceContainerHighest),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'微信快捷登录',
style: TextStyle(fontSize: 13, color: AppColors.textMuted),
),
),
Expanded(
child: SizedBox(
height: 1,
child: ColoredBox(color: AppColors.surfaceContainerHighest),
),
),
],
),
),
GestureDetector(
onTap: () => showAppToast('微信登录暂未开放'),
behavior: HitTestBehavior.opaque,
child: Container(
width: 56,
height: 56,
decoration: const BoxDecoration(
color: Color(0xFF07C160),
shape: BoxShape.circle,
),
alignment: Alignment.center,
child: const XIcon('weixin', size: 32, color: Colors.white),
),
),
],
),
);
}
Widget _buildAgreement() {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => setState(() => _agree = !_agree),
behavior: HitTestBehavior.opaque,
child: Container(
width: 20,
height: 20,
margin: const EdgeInsets.only(top: 1),
decoration: BoxDecoration(
color: _agree ? AppColors.primary : Colors.transparent,
border: Border.all(
color: _agree ? AppColors.primary : AppColors.textPlaceholder,
width: 2,
),
borderRadius: BorderRadius.circular(6),
),
alignment: Alignment.center,
child: _agree
? const Text(
'✓',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Colors.white,
height: 1,
),
)
: null,
),
),
const SizedBox(width: 12),
Expanded(
child: RichText(
text: TextSpan(
style: const TextStyle(
fontSize: 13,
height: 1.6,
color: AppColors.textMuted,
),
children: [
const TextSpan(text: '我已阅读并同意'),
_link('《VoltLink服务协议》'),
const TextSpan(text: '与'),
_link('《隐私政策》'),
const TextSpan(text: ',并授权 VoltLink 在登录时获取我的相关信息。'),
],
),
),
),
],
),
);
}
TextSpan _link(String text) => TextSpan(
text: text,
style: const TextStyle(color: AppColors.primary),
recognizer: TapGestureRecognizer()
..onTap = () => showAppToast('$text 暂未开放'),
);
Widget _buildRegisterEntry() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'还没有账号?',
style: TextStyle(fontSize: 14, color: AppColors.textMuted),
),
GestureDetector(
onTap: () => context.push('/register'),
behavior: HitTestBehavior.opaque,
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 6, horizontal: 4),
child: Text(
'立即注册',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
),
),
),
],
);
}
}
/// 调试版「服务端设置」弹窗:只让改 IP 与端口,
/// 协议与路径沿用 [Env.apiBaseUrl] 的编译期配置。
class _ServerSettingsSheet extends ConsumerStatefulWidget {
const _ServerSettingsSheet();
@override
ConsumerState<_ServerSettingsSheet> createState() =>
_ServerSettingsSheetState();
}
class _ServerSettingsSheetState extends ConsumerState<_ServerSettingsSheet> {
late final TextEditingController _host;
late final TextEditingController _port;
String _error = '';
@override
void initState() {
super.initState();
final saved = ref.read(serverAddressProvider);
_host = TextEditingController(
text: saved.host.isEmpty ? Env.defaultHost : saved.host,
);
_port = TextEditingController(
text: saved.port.isEmpty ? '${Env.defaultPort}' : saved.port,
);
}
@override
void dispose() {
_host.dispose();
_port.dispose();
super.dispose();
}
String get _preview {
final host = _host.text.trim();
return Env.buildBaseUrl(
host.isEmpty ? Env.defaultHost : host,
_port.text.trim(),
);
}
Future<void> _save() async {
final host = _host.text.trim();
final port = _port.text.trim();
if (host.isEmpty) {
setState(() => _error = '请输入服务端 IP');
return;
}
if (host.contains('://') || host.contains('/') || host.contains(':')) {
setState(() => _error = '只填 IP 或域名,不要带 http:// 和端口');
return;
}
final parsedPort = int.tryParse(port);
if (parsedPort == null || parsedPort < 1 || parsedPort > 65535) {
setState(() => _error = '端口需为 1 - 65535 的整数');
return;
}
// 保存后 serverAddressProvider 变化会重建 ApiClient,立即生效
await ref.read(serverAddressProvider.notifier).save(host, port);
if (!mounted) return;
Navigator.of(context).pop();
showAppToast('已切换到 ${Env.buildBaseUrl(host, port)}', success: true);
}
Future<void> _reset() async {
await ref.read(serverAddressProvider.notifier).reset();
if (!mounted) return;
Navigator.of(context).pop();
showAppToast('已恢复默认地址', success: true);
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(24, 20, 24, 28),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'服务端设置',
style: AppTypography.headlineMd.copyWith(
color: AppColors.onSurface,
),
),
const SizedBox(height: 6),
const Text(
'保存后立即生效,无需重启 App。',
style: TextStyle(fontSize: 13, color: AppColors.textMuted),
),
const SizedBox(height: 20),
_buildField(
label: '服务端 IP',
controller: _host,
hintText: '如 192.168.3.29',
keyboardType: TextInputType.url,
),
const SizedBox(height: 16),
_buildField(
label: '端口',
controller: _port,
hintText: '如 7001',
keyboardType: TextInputType.number,
),
const SizedBox(height: 14),
// 保存前实时预览拼接结果,避免地址拼错
ListenableBuilder(
listenable: Listenable.merge([_host, _port]),
builder: (context, _) => Text(
'生效地址:$_preview',
style: AppTypography.dataMono.copyWith(
color: AppColors.textMuted,
),
),
),
if (_error.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
_error,
style: const TextStyle(fontSize: 13, color: AppColors.error),
),
),
const SizedBox(height: 24),
Row(
children: [
Expanded(
child: XPrimaryButton(
label: '恢复默认',
onPressed: _reset,
background: AppColors.surfaceContainerHigh,
foreground: AppColors.onSurfaceVariant,
),
),
const SizedBox(width: 12),
Expanded(
child: XPrimaryButton(label: '保存', onPressed: _save),
),
],
),
],
),
),
);
}
Widget _buildField({
required String label,
required TextEditingController controller,
required String hintText,
required TextInputType keyboardType,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: AppTypography.bodySm.copyWith(
color: AppColors.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Container(
height: 48,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(
color: AppColors.surfaceBright,
border: Border.all(color: AppColors.borderSoft),
borderRadius: BorderRadius.circular(AppRadius.lg),
),
child: TextField(
controller: controller,
keyboardType: keyboardType,
autocorrect: false,
style: const TextStyle(fontSize: 15, color: AppColors.onSurface),
cursorColor: AppColors.primary,
decoration: InputDecoration(
isDense: true,
border: InputBorder.none,
hintText: hintText,
hintStyle: const TextStyle(
fontSize: 15,
color: AppColors.textPlaceholder,
),
),
),
),
],
);
}
}
@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/network/api_response.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../shared/widgets/app_feedback.dart';
import '../../../shared/widgets/x_card.dart';
import '../../../shared/widgets/x_common.dart';
import '../../../shared/widgets/x_top_bar.dart';
import '../application/session_controller.dart';
/// 注册页。
///
/// 源工程登录页只有「手机号 + 验证码」,没有注册页;后端 `/auth/register`
/// 支持手机号 + 密码开户,因此这里补一个与登录页同一套视觉语言的注册表单。
class RegisterPage extends ConsumerStatefulWidget {
const RegisterPage({super.key});
@override
ConsumerState<RegisterPage> createState() => _RegisterPageState();
}
class _RegisterPageState extends ConsumerState<RegisterPage> {
final _name = TextEditingController();
final _phone = TextEditingController();
final _password = TextEditingController();
final _idCard = TextEditingController();
final _title = TextEditingController();
bool _loading = false;
String _error = '';
@override
void initState() {
super.initState();
for (final c in [_name, _phone, _password]) {
c.addListener(_onChanged);
}
}
@override
void dispose() {
_name.dispose();
_phone.dispose();
_password.dispose();
_idCard.dispose();
_title.dispose();
super.dispose();
}
void _onChanged() => setState(() {});
bool get _canSubmit =>
_name.text.trim().isNotEmpty &&
_phone.text.length == 11 &&
_password.text.length >= 6;
Future<void> _handleRegister() async {
if (!_canSubmit) {
setState(() => _error = '请填写姓名、11 位手机号与至少 6 位密码');
return;
}
setState(() {
_loading = true;
_error = '';
});
try {
final res = await ref
.read(authApiProvider)
.register(
workerName: _name.text.trim(),
phone: _phone.text.trim(),
password: _password.text,
idCard: _idCard.text.trim(),
workerTitle: _title.text.trim(),
);
if (!mounted) return;
if (!res.isOk) {
setState(() => _error = res.message.isEmpty ? '注册失败' : res.message);
return;
}
showAppToast('注册成功,请登录', success: true);
context.pop();
} on ApiException catch (e) {
if (mounted) setState(() => _error = e.message);
} catch (_) {
if (mounted) setState(() => _error = '网络异常,请稍后重试');
} finally {
if (mounted) setState(() => _loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: XPageShell(
topBar: XTopBar.nav(title: '注册账号', onBack: () => context.pop()),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 20, 16, 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
XCard(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_Field(
label: '姓名',
hint: '请输入真实姓名',
controller: _name,
required: true,
),
const SizedBox(height: 18),
_Field(
label: '手机号',
hint: '请输入 11 位手机号',
controller: _phone,
required: true,
keyboardType: TextInputType.phone,
maxLength: 11,
),
const SizedBox(height: 18),
_Field(
label: '密码',
hint: '至少 6 位',
controller: _password,
required: true,
obscure: true,
),
const SizedBox(height: 18),
_Field(
label: '身份证号',
hint: '选填',
controller: _idCard,
),
const SizedBox(height: 18),
_Field(
label: '工种 / 职称',
hint: '选填,如 高压电工',
controller: _title,
),
],
),
),
const SizedBox(height: 20),
XPrimaryButton(
label: '提交注册',
height: 56,
radius: AppRadius.xl,
loading: _loading,
onPressed: _canSubmit ? _handleRegister : null,
shadows: AppShadows.primaryButton,
),
if (_error.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 14),
child: Text(
_error,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 13, color: AppColors.error),
),
),
const SizedBox(height: 16),
const Text(
'注册后需等待平台审核通过,方可接单。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: AppColors.textMuted),
),
],
),
),
),
);
}
}
class _Field extends StatelessWidget {
const _Field({
required this.label,
required this.hint,
required this.controller,
this.required = false,
this.obscure = false,
this.keyboardType,
this.maxLength,
});
final String label;
final String hint;
final TextEditingController controller;
final bool required;
final bool obscure;
final TextInputType? keyboardType;
final int? maxLength;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
label,
style: AppTypography.bodySm.copyWith(
color: AppColors.onSurfaceVariant,
),
),
if (required)
const Text(
' *',
style: TextStyle(fontSize: 13, color: AppColors.error),
),
],
),
const SizedBox(height: 8),
Container(
height: 48,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(
color: AppColors.surfaceBright,
border: Border.all(color: AppColors.borderSoft),
borderRadius: BorderRadius.circular(AppRadius.lg),
),
child: TextField(
controller: controller,
obscureText: obscure,
keyboardType: keyboardType,
maxLength: maxLength,
style: const TextStyle(fontSize: 15, color: AppColors.onSurface),
cursorColor: AppColors.primary,
decoration: InputDecoration(
isDense: true,
border: InputBorder.none,
counterText: '',
hintText: hint,
hintStyle: const TextStyle(
fontSize: 15,
color: AppColors.textPlaceholder,
),
),
),
),
],
);
}
}