feat: 二级页面色彩刷新 + 用药/通知/设备重构 + 后端健康档案/通知管线增强 + 大量测试

## 后端
- 健康档案: 新增手术状态字段 + EF 迁移; HealthArchiveService 新增查询方法
- 健康记录: HealthRecordService 新增批量/统计方法; 契约扩展
- 用药: 新增 MedicationScheduleStatus 枚举; MedicationService 排班逻辑调整
- 通知: EfUserNotificationPipeline 重构; 新增 EfReminderCatchUpService; 通知管线支持更多场景
- 用户: UserService 账号删除逻辑; 新增 local_account_file_cleanup; EfUserRepository 扩展
- AI: medication_agent_handler 微调; prompt_manager 优化; AiConversationService 上下文处理
- Endpoint: doctor/medication/exercise/health/notification/user 等多接口调整
- BackgroundService: health_record_reminder_service 重构, 提醒补漏逻辑
- 测试: 新增 account_deletion/doctor_endpoint/medication_schedule/medication_update/prompt_manager 测试

## 前端
- UI 系统: app_theme 大幅重构; app_colors/app_design_tokens/app_module_visuals 调整; 二级页面色彩刷新
- 主页: home_page 背景渐变 + 消息列表提取 _HomeMessages + 通知检查逻辑; chat_messages_view 全面重构
- 用药: medication_list/edit/checkin 三页重构, 新增 medication_ui_logic 抽取
- 通知: notification_prefs_page 重构, 新增 notification_prefs_logic; notification_center 优化
- 设备: device_management 重构, 新增 device_sync_ui_logic; device_scan 优化
- 趋势图: trend_page 大幅重构
- 登录: login_page 重构
- 个人资料: 新增 profile_edit_page; profile_page 优化
- 运动: 新增 exercise/ 目录 + care_plan_ui_logic
- 其他: remaining_pages/report_pages/health_drawer/admin/doctor 等多页面调整
- 组件: common_widgets/app_empty_state/app_error_state/app_future_view/app_toast/ai_content 优化
- Provider: chat_provider/consultation_provider/data_providers/auth_provider 调整
- AndroidManifest: 移除多余权限
- 测试: 新增 ai_content/care_plan/home_message/login_flow/medication_checkin/medication_ui/notification_prefs/profile_device/secondary_page/swipe_delete 等大量测试

## 文档
- 新增 ui-design-system.md 设计系统文档
- 新增 secondary-page-color-refresh 计划 + specs 目录
This commit is contained in:
MingNian
2026-07-15 23:22:52 +08:00
parent e654c1e0cc
commit fade61ac21
138 changed files with 12636 additions and 5013 deletions

View File

@@ -2,7 +2,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart' show adminServiceProvider;
import '../../providers/data_providers.dart'
show adminServiceProvider, doctorListProvider;
import '../../widgets/app_toast.dart';
class AdminAddDoctorPage extends ConsumerStatefulWidget {
@@ -48,6 +49,7 @@ class _AdminAddDoctorPageState extends ConsumerState<AdminAddDoctorPage> {
'professionalDirection': _directionCtrl.text.trim(),
});
if (mounted) {
ref.invalidate(doctorListProvider);
AppToast.show(context, '添加成功', type: AppToastType.success);
popRoute(ref);
}
@@ -65,7 +67,7 @@ class _AdminAddDoctorPageState extends ConsumerState<AdminAddDoctorPage> {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: const Text(

View File

@@ -5,25 +5,32 @@ import '../../widgets/admin_drawer.dart';
import 'admin_doctors_page.dart';
import 'admin_patients_page.dart';
final adminPageProvider = NotifierProvider<AdminPageNotifier, String>(AdminPageNotifier.new);
final adminPageProvider = NotifierProvider<AdminPageNotifier, String>(
AdminPageNotifier.new,
);
class AdminPageNotifier extends Notifier<String> {
@override String build() => 'doctors';
@override
String build() => 'doctors';
void set(String page) => state = page;
}
class AdminHomePage extends ConsumerWidget {
const AdminHomePage({super.key});
@override Widget build(BuildContext context, WidgetRef ref) {
@override
Widget build(BuildContext context, WidgetRef ref) {
final page = ref.watch(adminPageProvider);
return Scaffold(
backgroundColor: AppColors.pageGrey,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
title: const Text('系统管理', style: TextStyle(color: AppColors.textPrimary)),
title: const Text(
'系统管理',
style: TextStyle(color: AppColors.textPrimary),
),
iconTheme: const IconThemeData(color: AppColors.textPrimary),
),
drawer: const AdminDrawer(),

View File

@@ -1,6 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../providers/data_providers.dart';
@@ -57,7 +60,8 @@ class _LoginPageState extends ConsumerState<LoginPage> {
setState(() => _error = result.error);
return;
}
if (result.devCode != null) _codeCtrl.text = result.devCode!;
if (!mounted) return;
if (kDebugMode && result.devCode != null) _codeCtrl.text = result.devCode!;
setState(() => _countdown = 60);
_startCountdown();
}
@@ -70,6 +74,18 @@ class _LoginPageState extends ConsumerState<LoginPage> {
}
Future<void> _submit() async {
if (_phoneCtrl.text.trim().isEmpty || _codeCtrl.text.trim().isEmpty) {
setState(() => _error = '请输入手机号和验证码');
return;
}
if (!_isLogin && _nameCtrl.text.trim().isEmpty) {
setState(() => _error = '请输入姓名');
return;
}
if (!_isLogin && _selectedDoctorId == null) {
setState(() => _error = '请选择健康服务医生');
return;
}
if (!_agreed) {
final accepted = await _showAgreementDialog();
if (!mounted || accepted != true) return;
@@ -78,10 +94,6 @@ class _LoginPageState extends ConsumerState<LoginPage> {
_error = null;
});
}
if (_phoneCtrl.text.trim().isEmpty || _codeCtrl.text.trim().isEmpty) {
setState(() => _error = '请输入手机号和验证码');
return;
}
setState(() {
_loading = true;
_error = null;
@@ -94,20 +106,6 @@ class _LoginPageState extends ConsumerState<LoginPage> {
.read(authProvider.notifier)
.login(_phoneCtrl.text.trim(), _codeCtrl.text.trim());
} else {
if (_selectedDoctorId == null) {
setState(() {
_loading = false;
_error = '请选择医生';
});
return;
}
if (_nameCtrl.text.trim().isEmpty) {
setState(() {
_loading = false;
_error = '请输入姓名';
});
return;
}
err = await ref
.read(authProvider.notifier)
.register(
@@ -118,27 +116,14 @@ class _LoginPageState extends ConsumerState<LoginPage> {
);
}
if (!mounted) return;
setState(() => _loading = false);
if (err != null) {
if (err.contains('未注册')) setState(() => _isLogin = false);
setState(() => _error = err);
return;
}
if (!_isLogin) {
setState(() {
_isLogin = true;
_successMsg = '注册成功,请登录';
_error = null;
_phoneCtrl.clear();
_codeCtrl.clear();
_nameCtrl.clear();
_selectedDoctorId = null;
_selectedDoctorName = null;
});
ref.read(authProvider.notifier).logout();
} else {
_goHome();
}
// 登录和注册成功后的页面切换统一由根导航监听认证状态处理。
}
Future<bool?> _showAgreementDialog() {
@@ -152,10 +137,10 @@ class _LoginPageState extends ConsumerState<LoginPage> {
child: Container(
width: double.infinity,
constraints: const BoxConstraints(maxWidth: 380),
padding: const EdgeInsets.fromLTRB(22, 28, 22, 22),
padding: const EdgeInsets.fromLTRB(22, 26, 22, 22),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(28),
borderRadius: AppRadius.xlBorder,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.14),
@@ -247,7 +232,7 @@ class _LoginPageState extends ConsumerState<LoginPage> {
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: _loginActionGradient,
borderRadius: BorderRadius.circular(18),
borderRadius: AppRadius.mdBorder,
boxShadow: AppColors.buttonShadow,
),
child: const Text(
@@ -270,27 +255,13 @@ class _LoginPageState extends ConsumerState<LoginPage> {
);
}
void _goHome() {
ref.invalidate(latestHealthProvider);
ref.invalidate(medicationListProvider);
ref.invalidate(medicationReminderProvider);
ref.invalidate(currentExercisePlanProvider);
final role = ref.read(authProvider).user?.role ?? 'User';
if (role == 'Admin') {
goRoute(ref, 'adminHome');
} else if (role == 'Doctor') {
goRoute(ref, 'doctorHome');
} else {
goRoute(ref, 'home');
}
}
void _showDoctorPicker() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.white,
showDragHandle: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xl)),
),
builder: (ctx) => Consumer(
builder: (ctx, ref, _) {
@@ -311,9 +282,9 @@ class _LoginPageState extends ConsumerState<LoginPage> {
child: Column(
children: [
const Padding(
padding: EdgeInsets.all(18),
padding: EdgeInsets.fromLTRB(20, 2, 20, 16),
child: Text(
'选择医生',
'选择健康服务医生',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
@@ -321,16 +292,34 @@ class _LoginPageState extends ConsumerState<LoginPage> {
),
),
),
const Divider(height: 1, color: AppColors.divider),
Expanded(
child: ListView.builder(
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 20),
itemCount: active.length,
separatorBuilder: (_, _) => const Padding(
padding: EdgeInsets.only(left: 50),
child: Divider(height: 1, color: AppColors.divider),
),
itemBuilder: (_, i) {
final d = active[i];
final name = d['name'] ?? '';
final title = d['title'] ?? '';
final dept = d['department'] ?? '';
return ListTile(
contentPadding: EdgeInsets.zero,
leading: Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: AppColors.primarySoft,
borderRadius: AppRadius.smBorder,
),
child: const Icon(
LucideIcons.stethoscope,
size: 20,
color: AppColors.primaryDark,
),
),
title: Text(
name,
style: const TextStyle(
@@ -345,9 +334,10 @@ class _LoginPageState extends ConsumerState<LoginPage> {
),
),
trailing: _selectedDoctorId == d['id']?.toString()
? const AppGradientIcon(
icon: Icons.check_circle,
? const Icon(
LucideIcons.circleCheck,
size: 22,
color: AppColors.primaryDark,
)
: null,
onTap: () {
@@ -379,11 +369,6 @@ class _LoginPageState extends ConsumerState<LoginPage> {
@override
Widget build(BuildContext context) {
final authState = ref.watch(authProvider);
if (authState.isLoggedIn && !authState.isLoading) {
WidgetsBinding.instance.addPostFrameCallback((_) => _goHome());
}
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
@@ -403,140 +388,146 @@ class _LoginPageState extends ConsumerState<LoginPage> {
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.white.withValues(alpha: 0.10),
Colors.white.withValues(alpha: 0.28),
Colors.white.withValues(alpha: 0.54),
Colors.white.withValues(alpha: 0.02),
Colors.white.withValues(alpha: 0.12),
Colors.white.withValues(alpha: 0.40),
],
stops: const [0.0, 0.52, 1.0],
),
),
),
),
SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 28, 20, 24),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: (constraints.maxHeight - 52).clamp(
0.0,
double.infinity,
AnimatedPadding(
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 22, 20, 24),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: (constraints.maxHeight - 52).clamp(
0.0,
double.infinity,
),
),
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 430),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _LoginHero(),
const SizedBox(height: 28),
_LoginFormCard(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_successMsg != null)
_NoticeBanner(
text: _successMsg!,
success: true,
),
if (!_isLogin) ...[
_DoctorSelector(
name: _selectedDoctorName,
onTap: _showDoctorPicker,
),
const SizedBox(height: 12),
_TextField(
_nameCtrl,
'姓名',
TextInputType.name,
20,
icon: Icons.person_outline_rounded,
),
const SizedBox(height: 12),
],
_TextField(
_phoneCtrl,
'手机号',
TextInputType.phone,
11,
icon: Icons.local_phone_rounded,
gradientIcon: true,
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _TextField(
_codeCtrl,
'验证码',
TextInputType.number,
6,
icon: Icons.sms_rounded,
gradientIcon: true,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 430),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _LoginHero(),
const SizedBox(height: 22),
_LoginFormCard(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_successMsg != null)
_NoticeBanner(
text: _successMsg!,
success: true,
),
const SizedBox(width: 10),
_SmsButton(
sending: _sending,
countdown: _countdown,
onTap: (_countdown > 0 || _sending)
? null
: _sendSms,
if (!_isLogin) ...[
_DoctorSelector(
name: _selectedDoctorName,
onTap: _showDoctorPicker,
),
const SizedBox(height: 12),
_TextField(
_nameCtrl,
'姓名',
TextInputType.name,
20,
icon: LucideIcons.userRound,
),
const SizedBox(height: 12),
],
_TextField(
_phoneCtrl,
'手机号',
TextInputType.phone,
11,
icon: LucideIcons.phone,
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _TextField(
_codeCtrl,
'验证码',
TextInputType.number,
6,
icon: LucideIcons.messageSquareText,
),
),
const SizedBox(width: 10),
_SmsButton(
sending: _sending,
countdown: _countdown,
onTap: (_countdown > 0 || _sending)
? null
: _sendSms,
),
],
),
const SizedBox(height: 14),
_Agreement(
agreed: _agreed,
onTap: () =>
setState(() => _agreed = !_agreed),
onTermsTap: () =>
_openStaticText('terms'),
onPrivacyTap: () =>
_openStaticText('privacy'),
),
if (_error != null) ...[
const SizedBox(height: 12),
_NoticeBanner(
text: _error!,
success: false,
),
],
),
const SizedBox(height: 14),
_Agreement(
agreed: _agreed,
onTap: () =>
setState(() => _agreed = !_agreed),
onTermsTap: () => _openStaticText('terms'),
onPrivacyTap: () =>
_openStaticText('privacy'),
),
if (_error != null) ...[
const SizedBox(height: 12),
_NoticeBanner(
text: _error!,
success: false,
const SizedBox(height: 22),
_PrimaryButton(
loading: _loading,
label: _isLogin ? '登录' : '注册',
onTap: _loading ? null : _submit,
),
],
const SizedBox(height: 22),
_PrimaryButton(
loading: _loading,
label: _isLogin ? '登录' : '注册',
onTap: _loading ? null : _submit,
),
const SizedBox(height: 16),
GestureDetector(
onTap: () => setState(() {
_isLogin = !_isLogin;
_error = null;
_successMsg = null;
}),
child: Center(
child: AppGradientText(
_isLogin ? '没有账号?去注册' : '已有账号?去登录',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
const SizedBox(height: 16),
GestureDetector(
onTap: () => setState(() {
_isLogin = !_isLogin;
_error = null;
_successMsg = null;
}),
child: Center(
child: AppGradientText(
_isLogin ? '没有账号?去注册' : '已有账号?去登录',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
),
),
),
),
),
],
],
),
),
),
],
],
),
),
),
),
),
);
},
);
},
),
),
),
],
@@ -553,11 +544,11 @@ class _LoginHero extends StatelessWidget {
return Column(
children: [
_BrandMark(),
const SizedBox(height: 16),
const SizedBox(height: 12),
const Text(
'小脉健康',
style: TextStyle(
fontSize: 30,
fontSize: 28,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
letterSpacing: 0,
@@ -589,14 +580,13 @@ class _LoginFormCard extends StatelessWidget {
return Container(
padding: const EdgeInsets.fromLTRB(18, 18, 18, 20),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.94),
borderRadius: BorderRadius.circular(22),
border: Border.all(color: AppColors.border, width: 1.1),
color: Colors.white.withValues(alpha: 0.88),
borderRadius: AppRadius.xlBorder,
boxShadow: [
BoxShadow(
color: const Color(0xFF475467).withValues(alpha: 0.10),
blurRadius: 30,
offset: const Offset(0, 16),
color: const Color(0xFF475467).withValues(alpha: 0.07),
blurRadius: 24,
offset: const Offset(0, 12),
),
],
),
@@ -609,10 +599,22 @@ class _BrandMark extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(
width: 132,
height: 132,
child: Transform.scale(
scale: 1.08,
width: 108,
height: 108,
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.72),
shape: BoxShape.circle,
border: Border.all(color: Colors.white.withValues(alpha: 0.86)),
boxShadow: [
BoxShadow(
color: AppColors.primary.withValues(alpha: 0.10),
blurRadius: 20,
offset: const Offset(0, 8),
),
],
),
child: Image.asset(
'assets/branding/health_icon_master.png',
fit: BoxFit.cover,
@@ -628,16 +630,8 @@ class _TextField extends StatelessWidget {
final TextInputType type;
final int maxLen;
final IconData? icon;
final bool gradientIcon;
const _TextField(
this.ctrl,
this.hint,
this.type,
this.maxLen, {
this.icon,
this.gradientIcon = false,
});
const _TextField(this.ctrl, this.hint, this.type, this.maxLen, {this.icon});
@override
Widget build(BuildContext context) => TextField(
@@ -654,38 +648,22 @@ class _TextField extends StatelessWidget {
counterText: '',
prefixIcon: icon == null
? null
: gradientIcon
? _GradientPrefixIcon(icon: icon!)
: Icon(icon, size: 20, color: AppColors.textSecondary),
: Icon(icon, size: 20, color: AppColors.primaryDark),
filled: true,
fillColor: const Color(0xFFF8FAFC),
fillColor: AppColors.cardInner,
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 15),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: AppColors.border, width: 1.1),
borderRadius: AppRadius.mdBorder,
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: AppColors.auraIndigo, width: 1.2),
borderRadius: AppRadius.mdBorder,
borderSide: const BorderSide(color: AppColors.primary, width: 1.2),
),
),
);
}
class _GradientPrefixIcon extends StatelessWidget {
final IconData icon;
const _GradientPrefixIcon({required this.icon});
@override
Widget build(BuildContext context) {
return AppGradientIcon(
icon: icon,
size: 23,
gradient: _LoginPageState._loginActionGradient,
);
}
}
class _DoctorSelector extends StatelessWidget {
final String? name;
final VoidCallback onTap;
@@ -699,21 +677,20 @@ class _DoctorSelector extends StatelessWidget {
height: 50,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(
color: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppColors.border, width: 1.1),
color: AppColors.cardInner,
borderRadius: AppRadius.mdBorder,
),
child: Row(
children: [
const Icon(
Icons.medical_services_outlined,
LucideIcons.stethoscope,
size: 20,
color: AppColors.textSecondary,
),
const SizedBox(width: 12),
Expanded(
child: Text(
name ?? '请选择医生',
name ?? '请选择健康服务医生(必选)',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
@@ -723,7 +700,11 @@ class _DoctorSelector extends StatelessWidget {
),
),
),
const Icon(Icons.keyboard_arrow_down, color: AppColors.textHint),
const Icon(
LucideIcons.chevronDown,
size: 19,
color: AppColors.textHint,
),
],
),
),
@@ -751,11 +732,10 @@ class _SmsButton extends StatelessWidget {
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: disabled ? null : _LoginPageState._loginActionGradient,
color: disabled ? AppColors.cardInner : null,
borderRadius: BorderRadius.circular(14),
color: disabled ? AppColors.cardInner : Colors.white,
borderRadius: AppRadius.mdBorder,
border: Border.all(
color: disabled ? AppColors.border : Colors.transparent,
color: disabled ? AppColors.borderLight : AppColors.primaryLight,
),
),
child: Text(
@@ -767,7 +747,7 @@ class _SmsButton extends StatelessWidget {
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: disabled ? AppColors.textSecondary : Colors.white,
color: disabled ? AppColors.textSecondary : AppColors.primaryDark,
),
),
),
@@ -805,7 +785,7 @@ class _Agreement extends StatelessWidget {
decoration: BoxDecoration(
gradient: agreed ? _LoginPageState._loginActionGradient : null,
color: agreed ? null : Colors.white,
borderRadius: BorderRadius.circular(5),
borderRadius: AppRadius.xsBorder,
border: Border.all(
color: agreed ? Colors.transparent : AppColors.border,
),
@@ -856,7 +836,7 @@ class _NoticeBanner extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: success ? AppColors.successLight : AppColors.errorLight,
borderRadius: BorderRadius.circular(12),
borderRadius: AppRadius.mdBorder,
border: Border.all(
color: success
? AppColors.success.withValues(alpha: 0.16)
@@ -907,7 +887,7 @@ class _PrimaryButton extends StatelessWidget {
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: _LoginPageState._loginActionGradient,
borderRadius: BorderRadius.circular(14),
borderRadius: AppRadius.mdBorder,
boxShadow: AppColors.buttonShadow,
),
child: loading

View File

@@ -0,0 +1,41 @@
enum CarePlanPhase { active, upcoming, ended }
CarePlanPhase resolveCarePlanPhase({
bool enabled = true,
String? startDate,
String? endDate,
DateTime? today,
}) {
if (!enabled) return CarePlanPhase.ended;
final current = _dateOnly(today ?? DateTime.now());
final start = DateTime.tryParse(startDate ?? '');
final end = DateTime.tryParse(endDate ?? '');
if (start != null && _dateOnly(start).isAfter(current)) {
return CarePlanPhase.upcoming;
}
if (end != null && _dateOnly(end).isBefore(current)) {
return CarePlanPhase.ended;
}
return CarePlanPhase.active;
}
String? validateMedicationForm({
required String name,
required String dosage,
required List<String> times,
required DateTime startDate,
DateTime? endDate,
}) {
if (name.trim().isEmpty) return '请输入药品名称';
if (dosage.trim().isEmpty) return '请输入服药剂量';
if (times.isEmpty) return '请至少设置一个服药时间';
if (times.toSet().length != times.length) return '服药时间不能重复';
if (endDate != null && _dateOnly(endDate).isBefore(_dateOnly(startDate))) {
return '结束日期不能早于开始日期';
}
return null;
}
DateTime _dateOnly(DateTime value) =>
DateTime(value.year, value.month, value.day);

File diff suppressed because it is too large Load Diff

View File

@@ -63,7 +63,7 @@ class _DoctorChatPageState extends ConsumerState<DoctorChatPage> {
return GradientScaffold(
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
title: Column(
children: [
Text(

View File

@@ -7,7 +7,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../core/app_colors.dart';
import '../../core/api_client.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../models/ble_device.dart';
@@ -17,6 +19,8 @@ import '../../providers/omron_device_provider.dart';
import '../../services/health_ble_service.dart';
import '../../widgets/ble_sync_dialog.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/app_empty_state.dart';
import 'device_sync_ui_logic.dart';
const _deviceVisual = AppModuleVisuals.device;
@@ -45,6 +49,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
bool _scanning = false;
bool _permissionBlocked = false;
bool _disposed = false;
String? _pageMessage;
@override
void initState() {
@@ -58,15 +63,18 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
begin: 0.85,
end: 1.35,
).animate(CurvedAnimation(parent: _scanCtrl, curve: Curves.easeInOut));
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(_startForegroundScan());
});
}
@override
void dispose() {
_disposed = true;
_scanSub?.cancel();
_scanCtrl.dispose();
unawaited(FlutterBluePlus.stopScan());
unawaited(_bleService.disconnect());
_scanCtrl.dispose();
super.dispose();
}
@@ -94,7 +102,19 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
if (adapterState != BluetoothAdapterState.on) {
try {
await FlutterBluePlus.turnOn();
} catch (_) {}
} catch (_) {
if (mounted) {
setState(() => _pageMessage = '蓝牙未开启,无法查找已绑定设备');
AppToast.show(
context,
deviceSyncErrorMessage(
const DeviceSyncFailure(DeviceSyncFailureStage.bluetooth),
),
type: AppToastType.warning,
);
}
return;
}
}
try {
@@ -104,6 +124,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
final boundIds = ref
.read(omronDeviceProvider)
.devices
.where((device) => HealthBleService.isSyncImplemented(device.type))
.map((device) => device.id)
.toList();
if (boundIds.isEmpty) {
@@ -121,23 +142,44 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
androidScanMode: AndroidScanMode.lowLatency,
oneByOne: true,
);
if (mounted) setState(() => _scanning = true);
} catch (e) {
if (mounted) setState(() => _scanning = false);
if (mounted) {
setState(() {
_scanning = true;
_pageMessage = null;
});
}
} catch (_) {
if (mounted) {
setState(() {
_scanning = false;
_pageMessage = '设备查找失败,请检查蓝牙状态后重试';
});
AppToast.show(context, _pageMessage!, type: AppToastType.error);
}
}
}
Future<bool> _ensureBlePermissions() async {
final statuses = await [
Permission.bluetoothScan,
Permission.bluetoothConnect,
].request();
Map<Permission, PermissionStatus> statuses;
try {
statuses = await [
Permission.bluetoothScan,
Permission.bluetoothConnect,
].request();
} catch (_) {
if (mounted) {
setState(() => _pageMessage = '无法读取蓝牙权限状态');
AppToast.show(context, _pageMessage!, type: AppToastType.error);
}
return false;
}
final granted = statuses.values.every((status) => status.isGranted);
if (granted) {
_permissionBlocked = false;
return true;
}
_permissionBlocked = true;
if (mounted) setState(() => _pageMessage = '需要蓝牙权限才能同步设备');
if (_disposed || !mounted) return false;
AppToast.show(context, '请开启蓝牙权限后再同步设备', type: AppToastType.warning);
await showDialog<void>(
@@ -224,6 +266,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
setState(() {
_busyDeviceId = bound.id;
_connectedDeviceId = null;
_pageMessage = '正在连接 ${bound.name}';
});
await FlutterBluePlus.stopScan();
@@ -237,7 +280,10 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
timeout: const Duration(seconds: 35),
onConnected: () {
if (!_disposed && mounted) {
setState(() => _connectedDeviceId = bound.id);
setState(() {
_connectedDeviceId = bound.id;
_pageMessage = '已连接,等待设备测量数据';
});
}
},
onMeasurementReceived: () {
@@ -246,21 +292,48 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
);
if (syncResult is BloodPressureSyncResult) {
if (_disposed || !mounted) return;
setState(() => _pageMessage = '已读取数据,正在安全上传');
final saved = await _persistBloodPressure(
syncResult.device,
syncResult.reading,
);
if (!_disposed && mounted && saved) {
setState(() => _pageMessage = '同步完成');
await _showBloodPressureDialog(syncResult.reading);
}
}
} on TimeoutException {
if (!_disposed && mounted && _connectedDeviceId == bound.id) {
AppToast.show(context, '已连接设备,但本次未收到测量数据', type: AppToastType.warning);
}
} on Exception {
if (!_disposed && mounted) {
AppToast.show(context, '数据录入失败,请稍后重试', type: AppToastType.error);
final message = _connectedDeviceId == bound.id
? deviceSyncErrorMessage(
const DeviceSyncFailure(DeviceSyncFailureStage.measurement),
)
: deviceSyncErrorMessage(
const DeviceSyncFailure(DeviceSyncFailureStage.connection),
);
setState(() => _pageMessage = message);
AppToast.show(context, message, type: AppToastType.warning);
}
} on UnsupportedBleDeviceException catch (error) {
if (!_disposed && mounted) {
setState(() => _pageMessage = error.message);
AppToast.show(context, error.message, type: AppToastType.warning);
}
} on ApiException catch (error) {
if (!_disposed && mounted) {
final message = deviceSyncErrorMessage(
DeviceSyncFailure(DeviceSyncFailureStage.upload, error.message),
);
setState(() => _pageMessage = message);
AppToast.show(context, message, type: AppToastType.error);
}
} on Exception catch (error) {
if (!_disposed && mounted) {
final message = deviceSyncErrorMessage(
DeviceSyncFailure(DeviceSyncFailureStage.connection, '$error'),
);
setState(() => _pageMessage = message);
AppToast.show(context, message, type: AppToastType.error);
}
} finally {
await _bleService.disconnect();
@@ -282,11 +355,12 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
if (await notifier.isDuplicateReading(device, reading)) return false;
final api = ref.read(apiClientProvider);
await api.post('/api/health-records', data: reading.toHealthRecord());
final records = <Map<String, dynamic>>[reading.toHealthRecord()];
final heartRateRecord = reading.toHeartRateRecord();
if (heartRateRecord != null) {
await api.post('/api/health-records', data: heartRateRecord);
records.add(heartRateRecord);
}
await api.post('/api/health-records/batch', data: records);
await notifier.recordSuccessfulSync(device: device, reading: reading);
return true;
}
@@ -299,10 +373,14 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
Widget build(BuildContext context) {
final state = ref.watch(omronDeviceProvider);
final devices = state.devices;
final connected = _connectedDeviceId != null;
final boundKey = _boundIdsKey(devices.map((device) => device.id).toList());
final syncableDevices = devices
.where((device) => HealthBleService.isSyncImplemented(device.type))
.toList();
final boundKey = _boundIdsKey(
syncableDevices.map((device) => device.id).toList(),
);
if (devices.isNotEmpty &&
if (syncableDevices.isNotEmpty &&
!_scanning &&
_busyDeviceId == null &&
!_permissionBlocked &&
@@ -313,7 +391,10 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
}
ref.listen<DeviceBindState>(omronDeviceProvider, (prev, next) {
final nextIds = next.devices.map((device) => device.id).toList();
final nextIds = next.devices
.where((device) => HealthBleService.isSyncImplemented(device.type))
.map((device) => device.id)
.toList();
final nextKey = _boundIdsKey(nextIds);
if (nextIds.isEmpty) {
_activeScanBoundKey = '';
@@ -343,9 +424,11 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
tooltip: '新增设备',
onPressed: () => pushRoute(ref, 'deviceScan'),
style: IconButton.styleFrom(
backgroundColor: _deviceVisual.lightColor,
foregroundColor: _deviceVisual.color,
backgroundColor: Colors.white,
foregroundColor: AppColors.primaryDark,
fixedSize: const Size(40, 40),
side: const BorderSide(color: AppColors.primaryLight),
shape: const CircleBorder(),
),
icon: const Icon(Icons.add_rounded),
),
@@ -358,6 +441,20 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
padding: const EdgeInsets.fromLTRB(18, 10, 18, 120),
children: [
_DevicesHeader(deviceCount: devices.length),
if (devices.isNotEmpty) ...[
const SizedBox(height: 12),
_SyncStatusBar(
message:
_pageMessage ??
(syncableDevices.isEmpty
? '当前设备已绑定,暂不支持自动同步'
: _scanning
? '正在等待已绑定设备的测量数据'
: '设备同步已暂停'),
active: _scanning || _busyDeviceId != null,
onRetry: _busyDeviceId == null ? _startForegroundScan : null,
),
],
const SizedBox(height: 18),
if (devices.isEmpty)
const _EmptyDevices()
@@ -382,7 +479,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
child: _ScanIndicator(
animation: _scanAnim,
scanning: _scanning,
syncing: connected,
syncing: _connectedDeviceId != null || _busyDeviceId != null,
),
),
],
@@ -394,7 +491,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
shape: RoundedRectangleBorder(borderRadius: AppRadius.xlBorder),
title: const Text('解绑设备'),
content: Text('确定解绑这台${device.type.label}吗?'),
actions: [
@@ -404,7 +501,7 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: AppColors.error),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('解绑'),
),
],
@@ -416,309 +513,6 @@ class _DeviceManagementPageState extends ConsumerState<DeviceManagementPage>
}
}
class _DevicesHeader extends StatelessWidget {
final int deviceCount;
const _DevicesHeader({required this.deviceCount});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.fromLTRB(18, 18, 18, 18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: AppColors.borderLight, width: 1.1),
boxShadow: [AppTheme.shadowLight],
),
child: Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
gradient: _deviceVisual.gradient,
borderRadius: BorderRadius.circular(16),
),
child: const Icon(
Icons.bluetooth_audio_rounded,
color: Colors.white,
size: 27,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'已绑定设备',
style: TextStyle(
fontSize: 19,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
'$deviceCount 台设备',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w800,
color: AppColors.textSecondary,
),
),
],
),
),
],
),
);
}
}
class _DeviceSection extends StatelessWidget {
final BleDeviceType type;
final List<BoundBleDevice> devices;
final String? connectedDeviceId;
final String? busyDeviceId;
final ValueChanged<BoundBleDevice> onUnbind;
const _DeviceSection({
required this.type,
required this.devices,
required this.connectedDeviceId,
required this.busyDeviceId,
required this.onUnbind,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
children: [
Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: _deviceVisual.lightColor,
borderRadius: BorderRadius.circular(11),
border: Border.all(color: AppColors.borderLight),
),
child: Icon(type.icon, size: 19, color: _deviceVisual.color),
),
const SizedBox(width: 10),
Text(
type.label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
),
),
const SizedBox(width: 8),
Text(
'${devices.length}',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w800,
color: AppColors.textHint,
),
),
],
),
),
for (final device in devices)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _BoundDeviceTile(
device: device,
connected: connectedDeviceId == device.id,
onUnbind: () => onUnbind(device),
),
),
],
);
}
}
class _BoundDeviceTile extends StatelessWidget {
final BoundBleDevice device;
final bool connected;
final VoidCallback onUnbind;
const _BoundDeviceTile({
required this.device,
required this.connected,
required this.onUnbind,
});
@override
Widget build(BuildContext context) {
final accent = connected ? AppColors.success : AppColors.textHint;
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: const EdgeInsets.fromLTRB(16, 15, 10, 15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: connected ? AppColors.success : AppColors.border,
width: connected ? 1.4 : 1.1,
),
boxShadow: connected
? [
BoxShadow(
color: AppColors.success.withValues(alpha: 0.14),
blurRadius: 18,
offset: const Offset(0, 8),
),
]
: AppColors.cardShadowLight,
),
child: Row(
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 180),
width: 50,
height: 50,
decoration: BoxDecoration(
color: connected
? AppColors.successLight
: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.borderLight),
),
child: Icon(device.type.icon, color: accent, size: 25),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
device.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
'最近同步:${_formatLastSync(device.lastSyncAt)}',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: AppColors.textHint,
),
),
],
),
),
if (connected)
Container(
margin: const EdgeInsets.only(right: 4),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: AppColors.successLight,
borderRadius: BorderRadius.circular(999),
),
child: const Text(
'已连接',
style: TextStyle(
fontSize: 12,
height: 1,
fontWeight: FontWeight.w900,
color: AppColors.success,
),
),
),
IconButton(
tooltip: '解绑设备',
onPressed: connected ? null : onUnbind,
icon: const Icon(Icons.delete_outline_rounded),
color: connected ? AppColors.textHint : AppColors.error,
),
],
),
);
}
String _formatLastSync(DateTime? value) {
if (value == null) return '暂无';
final now = DateTime.now();
final dayLabel =
value.year == now.year &&
value.month == now.month &&
value.day == now.day
? '今天'
: '${value.month}/${value.day}';
final minute = value.minute.toString().padLeft(2, '0');
return '$dayLabel ${value.hour}:$minute';
}
}
class _EmptyDevices extends StatelessWidget {
const _EmptyDevices();
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(24, 46, 24, 46),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(22),
border: Border.all(color: AppColors.borderLight, width: 1.1),
boxShadow: [AppTheme.shadowLight],
),
child: Column(
children: [
Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: AppColors.deviceLight,
borderRadius: BorderRadius.circular(22),
),
child: const Icon(
Icons.bluetooth_disabled_rounded,
color: AppColors.device,
size: 36,
),
),
const SizedBox(height: 18),
const Text(
'还没有绑定设备',
style: TextStyle(
fontSize: 19,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 8),
const Text(
'右上角添加设备',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: AppColors.textSecondary,
),
),
],
),
);
}
}
class _ScanIndicator extends StatelessWidget {
final Animation<double> animation;
final bool scanning;
@@ -771,9 +565,9 @@ class _ScanIndicator extends StatelessWidget {
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: AppColors.device.withValues(alpha: 0.24),
blurRadius: 18,
offset: const Offset(0, 8),
color: AppColors.device.withValues(alpha: 0.22),
blurRadius: 16,
offset: const Offset(0, 7),
),
],
),
@@ -790,3 +584,339 @@ class _ScanIndicator extends StatelessWidget {
);
}
}
class _DevicesHeader extends StatelessWidget {
final int deviceCount;
const _DevicesHeader({required this.deviceCount});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.fromLTRB(18, 18, 18, 18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: _deviceVisual.lightColor,
borderRadius: AppRadius.smBorder,
),
child: Icon(_deviceVisual.icon, color: AppColors.device, size: 27),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'已绑定设备',
style: TextStyle(
fontSize: 19,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
'$deviceCount 台设备',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w800,
color: AppColors.textSecondary,
),
),
],
),
),
],
),
);
}
}
class _DeviceSection extends StatelessWidget {
final BleDeviceType type;
final List<BoundBleDevice> devices;
final String? connectedDeviceId;
final String? busyDeviceId;
final ValueChanged<BoundBleDevice> onUnbind;
const _DeviceSection({
required this.type,
required this.devices,
required this.connectedDeviceId,
required this.busyDeviceId,
required this.onUnbind,
});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: AppRadius.lgBorder,
child: ColoredBox(
color: Colors.white,
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(14, 13, 14, 10),
child: Row(
children: [
Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: _deviceVisual.lightColor,
borderRadius: AppRadius.smBorder,
),
child: Icon(
type.icon,
size: 19,
color: _deviceVisual.color,
),
),
const SizedBox(width: 10),
Text(
type.label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w900,
color: AppColors.textPrimary,
),
),
const Spacer(),
Text(
'${devices.length}',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: AppColors.textHint,
),
),
],
),
),
for (var index = 0; index < devices.length; index++)
_BoundDeviceTile(
device: devices[index],
connected: connectedDeviceId == devices[index].id,
busy: busyDeviceId == devices[index].id,
showDivider: index < devices.length - 1,
onUnbind: () => onUnbind(devices[index]),
),
],
),
),
);
}
}
class _BoundDeviceTile extends StatelessWidget {
final BoundBleDevice device;
final bool connected;
final bool busy;
final bool showDivider;
final VoidCallback onUnbind;
const _BoundDeviceTile({
required this.device,
required this.connected,
required this.busy,
required this.showDivider,
required this.onUnbind,
});
@override
Widget build(BuildContext context) {
final accent = connected ? AppColors.successText : AppColors.textHint;
final availability = deviceSyncAvailabilityLabel(device.type);
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
padding: const EdgeInsets.only(left: 14),
decoration: BoxDecoration(
color: connected
? AppColors.successLight.withValues(alpha: 0.45)
: Colors.white,
),
child: Row(
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 180),
width: 42,
height: 42,
decoration: BoxDecoration(
color: connected ? AppColors.successLight : AppColors.deviceLight,
borderRadius: AppRadius.smBorder,
),
child: Icon(device.type.icon, color: accent, size: 22),
),
const SizedBox(width: 12),
Expanded(
child: Container(
constraints: const BoxConstraints(minHeight: 70),
padding: const EdgeInsets.fromLTRB(0, 12, 6, 12),
decoration: BoxDecoration(
border: showDivider
? const Border(
bottom: BorderSide(
color: AppColors.divider,
width: 0.7,
),
)
: null,
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
device.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
availability ??
(busy
? connected
? '已连接,正在读取数据'
: '正在连接设备'
: '最近同步:${_formatLastSync(device.lastSyncAt)}'),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: availability == null
? AppColors.textHint
: AppColors.textSecondary,
),
),
],
),
),
if (connected)
Container(
margin: const EdgeInsets.only(right: 2),
padding: const EdgeInsets.symmetric(
horizontal: 9,
vertical: 5,
),
decoration: BoxDecoration(
color: AppColors.successLight,
borderRadius: AppRadius.pillBorder,
),
child: const Text(
'已连接',
style: TextStyle(
fontSize: 12,
height: 1,
fontWeight: FontWeight.w800,
color: AppColors.successText,
),
),
),
IconButton(
tooltip: '解绑设备',
onPressed: busy ? null : onUnbind,
icon: const Icon(Icons.delete_outline_rounded, size: 21),
color: AppColors.textHint,
),
],
),
),
),
],
),
);
}
String _formatLastSync(DateTime? value) {
if (value == null) return '暂无';
final now = DateTime.now();
final dayLabel =
value.year == now.year &&
value.month == now.month &&
value.day == now.day
? '今天'
: '${value.month}-${value.day}';
final minute = value.minute.toString().padLeft(2, '0');
return '$dayLabel ${value.hour}:$minute';
}
}
class _EmptyDevices extends StatelessWidget {
const _EmptyDevices();
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: AppEmptyState(
icon: _deviceVisual.icon,
iconColor: _deviceVisual.color,
title: '还没有绑定设备',
subtitle: '点击右上角添加设备',
),
);
}
}
class _SyncStatusBar extends StatelessWidget {
final String message;
final bool active;
final Future<void> Function()? onRetry;
const _SyncStatusBar({
required this.message,
required this.active,
required this.onRetry,
});
@override
Widget build(BuildContext context) => Container(
padding: const EdgeInsets.fromLTRB(14, 11, 8, 11),
decoration: BoxDecoration(
color: active ? AppColors.deviceLight : Colors.white,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.borderLight),
),
child: Row(
children: [
Icon(
active ? Icons.sync_rounded : Icons.info_outline_rounded,
size: 20,
color: active ? AppColors.device : AppColors.textSecondary,
),
const SizedBox(width: 10),
Expanded(
child: Text(
message,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: AppColors.textSecondary,
),
),
),
if (!active && onRetry != null)
TextButton(onPressed: onRetry, child: const Text('重试')),
],
),
);
}

View File

@@ -7,6 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../models/ble_device.dart';
@@ -290,8 +291,6 @@ class _DeviceScanPageState extends ConsumerState<DeviceScanPage>
Widget build(BuildContext context) {
return GradientScaffold(
appBar: AppBar(
backgroundColor: Colors.white.withValues(alpha: 0.92),
elevation: 0,
title: const Text(
'新增设备',
style: TextStyle(color: AppColors.textPrimary),
@@ -303,19 +302,30 @@ class _DeviceScanPageState extends ConsumerState<DeviceScanPage>
),
body: _results.isEmpty
? _ScanningEmpty(animation: _pulseAnim, scanning: _scanning)
: ListView.separated(
: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
itemCount: _results.length,
separatorBuilder: (context, index) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final result = _results[index];
return _DeviceResultTile(
result: result,
connecting:
_connectingId == result.device.remoteId.toString(),
onConnect: () => _connectBindAndSync(result),
);
},
children: [
ClipRRect(
borderRadius: AppRadius.lgBorder,
child: ColoredBox(
color: Colors.white,
child: Column(
children: [
for (var index = 0; index < _results.length; index++)
_DeviceResultTile(
result: _results[index],
connecting:
_connectingId ==
_results[index].device.remoteId.toString(),
showDivider: index < _results.length - 1,
onConnect: () =>
_connectBindAndSync(_results[index]),
),
],
),
),
),
],
),
);
}
@@ -413,11 +423,13 @@ class _ScanningEmpty extends StatelessWidget {
class _DeviceResultTile extends StatelessWidget {
final ScanResult result;
final bool connecting;
final bool showDivider;
final VoidCallback onConnect;
const _DeviceResultTile({
required this.result,
required this.connecting,
required this.showDivider,
required this.onConnect,
});
@@ -425,23 +437,16 @@ class _DeviceResultTile extends StatelessWidget {
Widget build(BuildContext context) {
final type = HealthBleService.deviceTypeFromScan(result);
final name = _deviceNameOf(result, type);
return Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.border, width: 1.1),
boxShadow: [AppTheme.shadowLight],
),
return Padding(
padding: const EdgeInsets.only(left: 14),
child: Row(
children: [
Container(
width: 48,
height: 48,
width: 42,
height: 42,
decoration: BoxDecoration(
color: AppColors.deviceLight,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppColors.deviceBorder),
borderRadius: AppRadius.smBorder,
),
child: Icon(
type?.icon ?? Icons.bluetooth_rounded,
@@ -449,52 +454,76 @@ class _DeviceResultTile extends StatelessWidget {
size: 25,
),
),
const SizedBox(width: 14),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
type?.label ?? '健康设备',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
color: AppColors.textHint,
),
),
],
),
),
const SizedBox(width: 10),
SizedBox(
height: 38,
child: FilledButton(
onPressed: connecting ? null : onConnect,
style: FilledButton.styleFrom(
backgroundColor: AppColors.device,
foregroundColor: Colors.white,
disabledBackgroundColor: AppColors.cardInner,
disabledForegroundColor: AppColors.textHint,
padding: const EdgeInsets.symmetric(horizontal: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
textStyle: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
),
child: Container(
constraints: const BoxConstraints(minHeight: 70),
padding: const EdgeInsets.fromLTRB(0, 12, 12, 12),
decoration: BoxDecoration(
border: showDivider
? const Border(
bottom: BorderSide(
color: AppColors.divider,
width: 0.7,
),
)
: null,
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
type?.label ?? '健康设备',
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13,
color: AppColors.textHint,
),
),
],
),
),
const SizedBox(width: 10),
SizedBox(
height: 36,
child: OutlinedButton(
onPressed: connecting ? null : onConnect,
style: OutlinedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: AppColors.device,
disabledForegroundColor: AppColors.textHint,
side: BorderSide(
color: connecting
? AppColors.borderLight
: AppColors.device,
),
padding: const EdgeInsets.symmetric(horizontal: 13),
shape: RoundedRectangleBorder(
borderRadius: AppRadius.smBorder,
),
textStyle: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
),
),
child: Text(connecting ? '连接中' : '连接'),
),
),
],
),
child: Text(connecting ? '连接中' : '连接'),
),
),
],
@@ -537,7 +566,7 @@ class _ScanPulse extends StatelessWidget {
height: 64,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
borderRadius: AppRadius.xlBorder,
border: Border.all(color: AppColors.borderLight),
),
child: const Icon(

View File

@@ -0,0 +1,33 @@
import '../../models/ble_device.dart';
enum DeviceSyncFailureStage {
permission,
bluetooth,
connection,
measurement,
upload,
}
class DeviceSyncFailure implements Exception {
final DeviceSyncFailureStage stage;
final String? detail;
const DeviceSyncFailure(this.stage, [this.detail]);
}
String? deviceSyncAvailabilityLabel(BleDeviceType type) {
return type == BleDeviceType.bloodPressure ? null : '暂不支持自动同步';
}
String deviceSyncErrorMessage(DeviceSyncFailure failure) {
final detail = failure.detail?.trim();
return switch (failure.stage) {
DeviceSyncFailureStage.permission => '请开启蓝牙权限后再同步设备',
DeviceSyncFailureStage.bluetooth => '蓝牙未开启,请开启后重试',
DeviceSyncFailureStage.connection =>
detail?.isNotEmpty == true ? '设备连接失败:$detail' : '设备连接失败,请靠近设备后重试',
DeviceSyncFailureStage.measurement => '已连接设备,但本次未收到测量数据',
DeviceSyncFailureStage.upload =>
detail?.isNotEmpty == true ? '数据上传失败:$detail' : '数据已读取,但上传失败,请检查网络后重试',
};
}

View File

@@ -9,6 +9,8 @@ import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../providers/auth_provider.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/common_widgets.dart';
import '../../widgets/app_empty_state.dart';
import 'diet_nutrition_widgets.dart';
import 'diet_record_logic.dart';
@@ -321,10 +323,9 @@ class DietNotifier extends Notifier<DietState> {
}
}
// ─────────── 饮食主题色(暖橙系,不再用紫色)───────────
// 饮食主题色
const _dietAccent = DietPalette.primary;
const _dietKcalText = DietPalette.calorie;
const _dietGradient = DietPalette.gradient;
class DietCapturePage extends ConsumerStatefulWidget {
const DietCapturePage({super.key});
@@ -352,7 +353,7 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
final state = ref.watch(dietProvider);
return GradientScaffold(
appBar: AppBar(
backgroundColor: Colors.white.withValues(alpha: 0.9),
backgroundColor: Colors.white,
title: const Text(
'饮食分析',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
@@ -425,7 +426,6 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.xlBorder,
boxShadow: AppColors.cardShadowLight,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -480,7 +480,7 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
);
}
// ─────────── 分析中 ───────────
// 分析中
Widget _buildAnalyzing(DietState state) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
@@ -503,7 +503,7 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
const SizedBox(height: 8),
Text(
state.errorMessage!,
style: const TextStyle(fontSize: 14, color: AppColors.error),
style: const TextStyle(fontSize: 14, color: AppColors.errorText),
textAlign: TextAlign.center,
),
],
@@ -513,43 +513,15 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
}
Widget _buildNoFoodHint() {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 36, horizontal: 18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
border: Border.all(color: AppColors.borderLight),
boxShadow: AppColors.cardShadowLight,
),
child: Column(
children: [
const Icon(
Icons.image_not_supported_outlined,
size: 44,
color: AppColors.textHint,
),
const SizedBox(height: 14),
const Text(
'未识别到食物',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 6),
const Text(
'请重新拍摄或选择含有食物的清晰照片',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: AppColors.textSecondary),
),
],
),
return AppEmptyState(
icon: Icons.image_not_supported_outlined,
iconColor: _dietAccent,
title: '未识别到食物',
subtitle: '请重新拍摄或选择含有食物的清晰照片',
);
}
// ─────────── 食物列表 ───────────
// 食物列表
Widget _buildFoodList(WidgetRef ref) {
final state = ref.watch(dietProvider);
return Container(
@@ -557,7 +529,6 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.xlBorder,
boxShadow: AppColors.cardShadowLight,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -618,8 +589,9 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
height: 26,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: food.selected ? _dietGradient : null,
color: food.selected ? null : DietPalette.primarySoft,
color: food.selected
? AppColors.primary
: AppColors.primarySoft,
borderRadius: AppRadius.smBorder,
border: Border.all(
color: food.selected
@@ -751,7 +723,7 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
return c;
}
// ─────────── AI 点评 ───────────
// AI 点评
Widget _buildAiCommentary(String? text) {
final hasText = text != null && text.trim().isNotEmpty;
return Container(
@@ -759,7 +731,6 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.xlBorder,
boxShadow: AppColors.cardShadowLight,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -770,8 +741,8 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
width: 4,
height: 18,
decoration: BoxDecoration(
gradient: _dietGradient,
borderRadius: BorderRadius.circular(999),
color: _dietAccent,
borderRadius: AppRadius.pillBorder,
),
),
const SizedBox(width: 9),
@@ -816,31 +787,9 @@ class _DietCapturePageState extends ConsumerState<DietCapturePage> {
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 12),
child: GestureDetector(
onTap: _saveDietRecord,
child: Container(
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: _dietGradient,
borderRadius: AppRadius.mdBorder,
boxShadow: [
BoxShadow(
color: _dietAccent.withValues(alpha: 0.24),
blurRadius: 14,
offset: const Offset(0, 7),
),
],
),
child: const Text(
'保存记录',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w900,
color: Colors.white,
),
),
),
child: AppGradientOutlineButton(
label: '保存记录',
onPressed: _saveDietRecord,
),
),
),

View File

@@ -133,9 +133,7 @@ class _CalorieRingPainter extends CustomPainter {
..strokeWidth = 9
..strokeCap = StrokeCap.round;
final progressPaint = Paint()
..shader = const LinearGradient(
colors: [Color(0xFF8FA7FF), DietPalette.calorie],
).createShader(Offset.zero & size)
..shader = DietPalette.gradient.createShader(Offset.zero & size)
..style = PaintingStyle.stroke
..strokeWidth = 9
..strokeCap = StrokeCap.round;

View File

@@ -1,3 +1,12 @@
import 'package:flutter/widgets.dart';
enum DietRecordSwipeAction { edit, delete }
DietRecordSwipeAction dietRecordSwipeAction(DismissDirection direction) =>
direction == DismissDirection.startToEnd
? DietRecordSwipeAction.edit
: DietRecordSwipeAction.delete;
List<DateTime> recentDietDates(DateTime now, {int count = 7}) {
final today = DateTime(now.year, now.month, now.day);
return List.generate(

View File

@@ -62,7 +62,7 @@ class _DoctorFollowUpEditPageState
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: Text(

View File

@@ -23,7 +23,7 @@ class DoctorHomePage extends ConsumerWidget {
child: Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: Text(

View File

@@ -21,7 +21,7 @@ class DoctorPatientDetailPage extends ConsumerWidget {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: const Text(
@@ -125,11 +125,13 @@ class DoctorPatientDetailPage extends ConsumerWidget {
(archive['surgeries'] as List).isNotEmpty)
_row(
'手术史',
(archive['surgeries'] as List).map((item) {
final surgery = item as Map;
final date = surgery['date']?.toString() ?? '';
return '${surgery['type'] ?? ''}${date.isEmpty ? '' : ' $date'}';
}).join(''),
(archive['surgeries'] as List)
.map((item) {
final surgery = item as Map;
final date = surgery['date']?.toString() ?? '';
return '${surgery['type'] ?? ''}${date.isEmpty ? '' : ' $date'}';
})
.join(''),
)
else if (archive['surgeryType'] != null)
_row(

View File

@@ -40,7 +40,7 @@ class _DoctorProfileEditPageState extends ConsumerState<DoctorProfileEditPage> {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: const Text(

View File

@@ -90,7 +90,7 @@ class _DoctorReportDetailPageState
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: const Text(
@@ -298,8 +298,12 @@ class _DoctorReportDetailPageState
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
pushRoute(ref, 'reportOriginal', params: {'url': fileUrl, 'title': '原始报告'});
},
pushRoute(
ref,
'reportOriginal',
params: {'url': fileUrl, 'title': '原始报告'},
);
},
icon: const Icon(Icons.visibility, size: 18),
label: const Text('查看原始报告'),
style: OutlinedButton.styleFrom(

View File

@@ -11,7 +11,7 @@ class DoctorSettingsPage extends ConsumerWidget {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
title: const Text('设置', style: TextStyle(color: AppColors.textPrimary)),
@@ -28,8 +28,20 @@ class DoctorSettingsPage extends ConsumerWidget {
'推送通知',
trailing: Switch(value: true, onChanged: (_) {}),
),
_SettingTile(Icons.description_outlined, '隐私政策', onTap: () { pushRoute(ref, 'staticText', params: {'type': 'privacy'}); }),
_SettingTile(Icons.article_outlined, '用户协议', onTap: () { pushRoute(ref, 'staticText', params: {'type': 'terms'}); }),
_SettingTile(
Icons.description_outlined,
'隐私政策',
onTap: () {
pushRoute(ref, 'staticText', params: {'type': 'privacy'});
},
),
_SettingTile(
Icons.article_outlined,
'用户协议',
onTap: () {
pushRoute(ref, 'staticText', params: {'type': 'terms'});
},
),
const SizedBox(height: 24),
_SettingTile(
Icons.delete_forever_outlined,

View File

@@ -0,0 +1,604 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api_client.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart';
import '../../widgets/app_empty_state.dart';
import '../../widgets/app_future_view.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/common_widgets.dart';
import '../care_plan_ui_logic.dart';
class EnterpriseExercisePlanPage extends ConsumerStatefulWidget {
const EnterpriseExercisePlanPage({super.key});
@override
ConsumerState<EnterpriseExercisePlanPage> createState() =>
_EnterpriseExercisePlanPageState();
}
class _EnterpriseExercisePlanPageState
extends ConsumerState<EnterpriseExercisePlanPage> {
Future<List<Map<String, dynamic>>>? _future;
final Set<String> _busyItems = {};
final Set<String> _deletingPlans = {};
@override
void initState() {
super.initState();
_load();
}
void _load() => setState(() {
_future = ref.read(exerciseServiceProvider).getPlans();
});
Future<void> _refresh() async {
_load();
await _future;
}
Future<void> _toggleCheckIn(String itemId) async {
if (itemId.isEmpty || _busyItems.contains(itemId)) return;
setState(() => _busyItems.add(itemId));
try {
await ref.read(exerciseServiceProvider).checkIn(itemId);
ref.invalidate(currentExercisePlanProvider);
_load();
} catch (error) {
if (mounted) {
AppToast.show(
context,
error is ApiException ? error.message : '打卡失败,请稍后重试',
type: AppToastType.error,
);
}
} finally {
if (mounted) setState(() => _busyItems.remove(itemId));
}
}
Future<void> _confirmDelete(String id, String title) async {
if (id.isEmpty || _deletingPlans.contains(id)) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('删除运动计划'),
content: Text('确定删除“$title”吗?删除后无法恢复。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('删除'),
),
],
),
);
if (confirmed != true || !mounted) return;
setState(() => _deletingPlans.add(id));
try {
await ref.read(exerciseServiceProvider).deletePlan(id);
ref.invalidate(currentExercisePlanProvider);
_load();
if (mounted) {
AppToast.show(context, '运动计划已删除', type: AppToastType.success);
}
} catch (error) {
if (mounted) {
AppToast.show(
context,
error is ApiException ? error.message : '删除失败,请稍后重试',
type: AppToastType.error,
);
}
} finally {
if (mounted) setState(() => _deletingPlans.remove(id));
}
}
@override
Widget build(BuildContext context) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: const Text('运动计划'),
),
floatingActionButton: AppCreateFab(
tooltip: '新建运动计划',
onPressed: () => pushRoute(ref, 'exerciseCreate'),
),
body: AppFutureView<List<Map<String, dynamic>>>(
future: _future,
onRetry: _load,
errorTitle: '运动计划加载失败',
onData: (_, plans) {
if (plans.isEmpty) {
return AppEmptyState(
icon: AppModuleVisuals.exercise.icon,
title: '暂无运动计划',
subtitle: '点击右下角添加运动计划',
iconColor: AppColors.exercise,
);
}
final todayKey = _dateKey(DateTime.now());
final validPlans = plans.where((plan) {
return (plan['items'] as List?)?.isNotEmpty == true;
}).toList();
final todayItems = validPlans
.expand(_itemsOf)
.where((item) => item['scheduledDate']?.toString() == todayKey)
.where((item) => item['isRestDay'] != true)
.toList();
final completedToday = todayItems
.where((item) => item['isCompleted'] == true)
.length;
final groups = <CarePlanPhase, List<Map<String, dynamic>>>{
for (final phase in CarePlanPhase.values) phase: [],
};
for (final plan in validPlans) {
groups[resolveCarePlanPhase(
startDate: plan['startDate']?.toString(),
endDate: plan['endDate']?.toString(),
)]!
.add(plan);
}
return RefreshIndicator(
onRefresh: _refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: AppSpacing.pageWithFab,
children: [
_TodayExercisePanel(
items: todayItems,
completed: completedToday,
busyItems: _busyItems,
onCheckIn: _toggleCheckIn,
),
const SizedBox(height: 18),
for (final phase in CarePlanPhase.values)
if (groups[phase]!.isNotEmpty) ...[
_ExercisePlanGroup(
phase: phase,
plans: groups[phase]!,
todayKey: todayKey,
busyItems: _busyItems,
deletingPlans: _deletingPlans,
onCheckIn: _toggleCheckIn,
onDelete: _confirmDelete,
),
const SizedBox(height: 18),
],
],
),
);
},
),
);
}
}
class _TodayExercisePanel extends StatelessWidget {
final List<Map<String, dynamic>> items;
final int completed;
final Set<String> busyItems;
final Future<void> Function(String) onCheckIn;
const _TodayExercisePanel({
required this.items,
required this.completed,
required this.busyItems,
required this.onCheckIn,
});
@override
Widget build(BuildContext context) {
final progress = items.isEmpty ? 0.0 : completed / items.length;
final next = items.cast<Map<String, dynamic>?>().firstWhere(
(item) => item?['isCompleted'] != true,
orElse: () => null,
);
if (items.isEmpty) {
return Container(
padding: AppSpacing.panel,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Row(
children: [
Container(
width: 42,
height: 42,
decoration: BoxDecoration(
color: AppColors.exerciseLight,
borderRadius: AppRadius.smBorder,
),
child: Icon(
AppModuleVisuals.exercise.icon,
color: AppColors.exercise,
size: 22,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('今日休息', style: AppTextStyles.sectionTitle),
SizedBox(height: 3),
Text('今天没有安排运动,保持轻松活动即可', style: AppTextStyles.listSubtitle),
],
),
),
],
),
);
}
return Container(
padding: AppSpacing.panel,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('今日任务', style: AppTextStyles.sectionTitle),
const SizedBox(height: 3),
Text(
'$completed / ${items.length} 已完成',
style: AppTextStyles.listSubtitle,
),
],
),
),
if (next != null)
_CompactActionButton(
busy: busyItems.contains(next['id']?.toString() ?? ''),
completed: false,
onPressed: () => onCheckIn(next['id']?.toString() ?? ''),
),
],
),
const SizedBox(height: 14),
ClipRRect(
borderRadius: AppRadius.pillBorder,
child: LinearProgressIndicator(
minHeight: 5,
value: progress,
backgroundColor: AppColors.cardInner,
valueColor: const AlwaysStoppedAnimation(AppColors.exercise),
),
),
if (next != null) ...[
const SizedBox(height: 12),
Text(
'${next['exerciseType'] ?? '运动'} · ${next['durationMinutes'] ?? 0} 分钟',
style: AppTextStyles.listTitle.copyWith(fontSize: 16),
),
],
],
),
);
}
}
class _ExercisePlanGroup extends StatelessWidget {
final CarePlanPhase phase;
final List<Map<String, dynamic>> plans;
final String todayKey;
final Set<String> busyItems;
final Set<String> deletingPlans;
final Future<void> Function(String) onCheckIn;
final Future<void> Function(String, String) onDelete;
const _ExercisePlanGroup({
required this.phase,
required this.plans,
required this.todayKey,
required this.busyItems,
required this.deletingPlans,
required this.onCheckIn,
required this.onDelete,
});
@override
Widget build(BuildContext context) {
final color = _phaseColor(phase);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 2, bottom: 9),
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
),
const SizedBox(width: 8),
Text(
'${_phaseLabel(phase)}${plans.length}',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
color: color,
),
),
],
),
),
Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
children: List.generate(plans.length, (index) {
final plan = plans[index];
final items = _itemsOf(plan);
final id = plan['id']?.toString() ?? '';
final title = _exerciseTitle(items);
final isDeleting = deletingPlans.contains(id);
return SwipeDeleteTile(
key: ValueKey(id),
margin: EdgeInsets.zero,
borderRadius: BorderRadius.zero,
enabled: !isDeleting,
onDelete: () => onDelete(id, title),
child: _ExercisePlanRow(
plan: plan,
title: title,
phase: phase,
todayKey: todayKey,
busyItems: busyItems,
deleting: isDeleting,
showDivider: index < plans.length - 1,
onCheckIn: onCheckIn,
),
);
}),
),
),
],
);
}
}
class _ExercisePlanRow extends StatelessWidget {
final Map<String, dynamic> plan;
final String title;
final CarePlanPhase phase;
final String todayKey;
final Set<String> busyItems;
final bool deleting;
final bool showDivider;
final Future<void> Function(String) onCheckIn;
const _ExercisePlanRow({
required this.plan,
required this.title,
required this.phase,
required this.todayKey,
required this.busyItems,
required this.deleting,
required this.showDivider,
required this.onCheckIn,
});
@override
Widget build(BuildContext context) {
final items = _itemsOf(plan);
final done = items.where((item) => item['isCompleted'] == true).length;
final progress = items.isEmpty ? 0.0 : done / items.length;
final todayItem = items.cast<Map<String, dynamic>?>().firstWhere(
(item) => item?['scheduledDate']?.toString() == todayKey,
orElse: () => null,
);
final canCheckIn =
phase == CarePlanPhase.active &&
todayItem != null &&
todayItem['isRestDay'] != true;
final itemId = todayItem?['id']?.toString() ?? '';
final completed = todayItem?['isCompleted'] == true;
return Material(
color: Colors.white,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
child: Row(
children: [
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: AppColors.exerciseLight,
borderRadius: AppRadius.smBorder,
),
child: Icon(
AppModuleVisuals.exercise.icon,
color: AppColors.exercise,
size: 22,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listTitle.copyWith(
fontSize: 17,
),
),
),
const SizedBox(width: 8),
Text(
'$done/${items.length}',
style: AppTextStyles.tag,
),
],
),
const SizedBox(height: 4),
Text(
'${_compactDate(plan['startDate'])} - ${_compactDate(plan['endDate'])}',
style: AppTextStyles.listSubtitle.copyWith(
fontSize: 13,
),
),
const SizedBox(height: 8),
ClipRRect(
borderRadius: AppRadius.pillBorder,
child: LinearProgressIndicator(
minHeight: 4,
value: progress,
backgroundColor: AppColors.cardInner,
valueColor: AlwaysStoppedAnimation(
_phaseColor(phase),
),
),
),
],
),
),
if (canCheckIn && !deleting) ...[
const SizedBox(width: 8),
_CompactActionButton(
busy: busyItems.contains(itemId) || deleting,
completed: completed,
onPressed: () => onCheckIn(itemId),
),
],
if (deleting)
const Padding(
padding: EdgeInsets.all(12),
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
],
),
),
if (showDivider)
const Positioned(
left: 68,
right: 0,
bottom: 0,
child: Divider(
height: 1,
thickness: 0.7,
color: AppColors.divider,
),
),
],
),
);
}
}
class _CompactActionButton extends StatelessWidget {
final bool busy;
final bool completed;
final VoidCallback onPressed;
const _CompactActionButton({
required this.busy,
required this.completed,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 38,
child: OutlinedButton(
onPressed: busy ? null : onPressed,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 14),
backgroundColor: completed ? AppColors.successLight : Colors.white,
foregroundColor: completed
? AppColors.successText
: AppColors.exercise,
side: BorderSide(
color: completed ? AppColors.successText : AppColors.exercise,
),
shape: RoundedRectangleBorder(borderRadius: AppRadius.smBorder),
),
child: busy
? const SizedBox(
width: 15,
height: 15,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(completed ? '撤销' : '打卡', style: AppTextStyles.miniButton),
),
);
}
}
List<Map<String, dynamic>> _itemsOf(Map<String, dynamic> plan) =>
(plan['items'] as List?)?.cast<Map<String, dynamic>>() ?? [];
String _exerciseTitle(List<Map<String, dynamic>> items) {
final names = items
.where((item) => item['isRestDay'] != true)
.map((item) => item['exerciseType']?.toString().trim() ?? '')
.where((name) => name.isNotEmpty)
.toSet()
.toList();
if (names.isEmpty) return '运动计划';
return names.length == 1 ? names.first : '${names.first}${names.length}';
}
String _dateKey(DateTime date) =>
'${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
String _compactDate(Object? value) {
final parsed = DateTime.tryParse(value?.toString() ?? '');
return parsed == null
? '--'
: '${parsed.year}.${parsed.month.toString().padLeft(2, '0')}.${parsed.day.toString().padLeft(2, '0')}';
}
String _phaseLabel(CarePlanPhase phase) => switch (phase) {
CarePlanPhase.active => '进行中',
CarePlanPhase.upcoming => '即将开始',
CarePlanPhase.ended => '已结束',
};
Color _phaseColor(CarePlanPhase phase) => switch (phase) {
CarePlanPhase.active => AppColors.successText,
CarePlanPhase.upcoming => AppColors.blueMeasure,
CarePlanPhase.ended => AppColors.textHint,
};

View File

@@ -2,12 +2,24 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/chat_provider.dart';
import '../../providers/conversation_history_provider.dart';
import '../../widgets/app_toast.dart';
Future<bool> deleteConversationForDismiss(
Future<void> Function() delete,
) async {
try {
await delete();
return true;
} catch (_) {
return false;
}
}
class ConversationHistoryPage extends ConsumerWidget {
const ConversationHistoryPage({super.key});
@@ -17,7 +29,7 @@ class ConversationHistoryPage extends ConsumerWidget {
return GradientScaffold(
appBar: AppBar(
backgroundColor: Colors.white.withValues(alpha: 0.9),
backgroundColor: Colors.white,
title: const Text('对话记录'),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
@@ -29,7 +41,7 @@ class ConversationHistoryPage extends ConsumerWidget {
child: const Text(
'清空',
style: TextStyle(
color: AppColors.error,
color: AppColors.errorText,
fontWeight: FontWeight.w800,
),
),
@@ -51,13 +63,15 @@ class ConversationHistoryPage extends ConsumerWidget {
: ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 24),
itemCount: list.length,
separatorBuilder: (_, index) => const SizedBox(height: 10),
separatorBuilder: (_, index) => const SizedBox.shrink(),
itemBuilder: (context, index) {
final item = list[index];
return _HistoryTile(
item: item,
onTap: () => _openConversation(context, ref, item.id),
onDelete: () => _deleteOne(context, ref, item.id),
isFirst: index == 0,
isLast: index == list.length - 1,
);
},
),
@@ -81,21 +95,22 @@ class ConversationHistoryPage extends ConsumerWidget {
popRoute(ref);
}
Future<void> _deleteOne(
Future<bool> _deleteOne(
BuildContext context,
WidgetRef ref,
String id,
) async {
try {
await ref.read(conversationHistoryProvider.notifier).deleteOne(id);
if (context.mounted) {
AppToast.show(context, '已删除', type: AppToastType.success);
}
} catch (_) {
if (context.mounted) {
AppToast.show(context, '删除失败,请稍后重试', type: AppToastType.error);
}
final deleted = await deleteConversationForDismiss(
() => ref.read(conversationHistoryProvider.notifier).deleteOne(id),
);
if (context.mounted) {
AppToast.show(
context,
deleted ? '已删除' : '删除失败,请稍后重试',
type: deleted ? AppToastType.success : AppToastType.error,
);
}
return deleted;
}
Future<void> _confirmClearAll(BuildContext context, WidgetRef ref) async {
@@ -111,7 +126,7 @@ class ConversationHistoryPage extends ConsumerWidget {
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: AppColors.error),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('清空'),
),
],
@@ -136,12 +151,16 @@ class ConversationHistoryPage extends ConsumerWidget {
class _HistoryTile extends StatelessWidget {
final ConversationListItem item;
final VoidCallback onTap;
final VoidCallback onDelete;
final Future<bool> Function() onDelete;
final bool isFirst;
final bool isLast;
const _HistoryTile({
required this.item,
required this.onTap,
required this.onDelete,
required this.isFirst,
required this.isLast,
});
@override
@@ -153,25 +172,25 @@ class _HistoryTile extends StatelessWidget {
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 18),
decoration: BoxDecoration(
color: AppColors.error,
borderRadius: BorderRadius.circular(14),
color: AppColors.errorText,
borderRadius: AppRadius.lgBorder,
),
child: const Icon(Icons.delete_outline, color: Colors.white),
),
confirmDismiss: (_) async {
onDelete();
return true;
},
confirmDismiss: (_) => onDelete(),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(14),
borderRadius: _rowRadius,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppColors.borderLight),
boxShadow: AppColors.cardShadowLight,
borderRadius: _rowRadius,
border: isLast
? null
: const Border(
bottom: BorderSide(color: AppColors.divider, width: 0.7),
),
),
child: Row(
children: [
@@ -225,8 +244,15 @@ class _HistoryTile extends StatelessWidget {
local.day == yesterday.day) {
return '昨天';
}
return '${local.month}/${local.day}';
return '${local.month}-${local.day}';
}
BorderRadius get _rowRadius => BorderRadius.only(
topLeft: isFirst ? const Radius.circular(AppRadius.lg) : Radius.zero,
topRight: isFirst ? const Radius.circular(AppRadius.lg) : Radius.zero,
bottomLeft: isLast ? const Radius.circular(AppRadius.lg) : Radius.zero,
bottomRight: isLast ? const Radius.circular(AppRadius.lg) : Radius.zero,
);
}
class _EmptyHint extends StatelessWidget {

View File

@@ -1,13 +1,14 @@
import 'dart:io';
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:file_picker/file_picker.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../providers/chat_provider.dart';
@@ -28,7 +29,6 @@ class _HomePageState extends ConsumerState<HomePage>
final _scrollCtrl = ScrollController();
final _focusNode = FocusNode();
final _scaffoldKey = GlobalKey<ScaffoldState>();
double? _drawerDragStartX;
String? _pickedImagePath;
Timer? _notificationTimer;
@@ -36,19 +36,21 @@ class _HomePageState extends ConsumerState<HomePage>
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback(
(_) => ref.invalidate(notificationUnreadCountProvider),
);
_scheduleScrollToLatest();
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkDueNotifications();
_refreshTodayHealthIfCached();
});
_notificationTimer = Timer.periodic(
const Duration(minutes: 2),
(_) => ref.invalidate(notificationUnreadCountProvider),
(_) => _checkDueNotifications(),
);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
ref.invalidate(notificationUnreadCountProvider);
_checkDueNotifications();
}
}
@@ -76,6 +78,26 @@ class _HomePageState extends ConsumerState<HomePage>
}
}
void _refreshTodayHealthIfCached() {
if (!ref.read(todayHealthSnapshotProvider).hasValue) return;
ref.invalidate(latestHealthProvider);
ref.invalidate(medicationReminderProvider);
ref.invalidate(currentExercisePlanProvider);
}
void _scheduleScrollToLatest() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_scrollCtrl.hasClients) return;
_scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
// Lazy list items can refine the final extent after the first layout.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_scrollCtrl.hasClients) return;
_scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
});
});
}
@override
Widget build(BuildContext context) {
final auth = ref.watch(authProvider);
@@ -105,55 +127,36 @@ class _HomePageState extends ConsumerState<HomePage>
current,
) {
if (current <= (previous ?? 0)) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scrollCtrl.hasClients) {
_scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
}
});
_scheduleScrollToLatest();
});
return Scaffold(
key: _scaffoldKey,
backgroundColor: const Color(0xFFFFFCFF),
drawer: const HealthDrawer(),
drawerEnableOpenDragGesture: false,
body: AppBackground(
safeArea: true,
child: Column(
children: [
_buildHeader(user),
Expanded(
child: Stack(
children: [
RepaintBoundary(
child: _HomeMessages(scrollCtrl: _scrollCtrl),
),
Positioned(
left: 0,
top: 0,
bottom: 0,
width: MediaQuery.sizeOf(context).width * 0.8,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onHorizontalDragStart: (details) {
_drawerDragStartX = details.globalPosition.dx;
},
onHorizontalDragUpdate: (details) {
final startX = _drawerDragStartX;
if (startX == null) return;
if (details.globalPosition.dx - startX < 28) return;
_drawerDragStartX = null;
_scaffoldKey.currentState?.openDrawer();
},
onHorizontalDragEnd: (_) => _drawerDragStartX = null,
onHorizontalDragCancel: () => _drawerDragStartX = null,
),
),
],
drawerEnableOpenDragGesture: true,
drawerDragStartBehavior: DragStartBehavior.down,
drawerEdgeDragWidth: MediaQuery.sizeOf(context).width * 0.8,
body: DecoratedBox(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFF0EDFF), Color(0xFFE6ECFF)],
),
),
child: SafeArea(
child: Column(
children: [
_buildHeader(user),
Expanded(
child: RepaintBoundary(
child: _HomeMessages(scrollCtrl: _scrollCtrl),
),
),
),
_buildBottomBar(context),
],
_buildBottomBar(context),
],
),
),
),
);
@@ -165,20 +168,7 @@ class _HomePageState extends ConsumerState<HomePage>
: '用户';
final unreadCount = ref.watch(notificationUnreadCountProvider).value ?? 0;
return Container(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 10),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.34),
border: Border(
bottom: BorderSide(color: Colors.white.withValues(alpha: 0.62)),
),
boxShadow: [
BoxShadow(
color: const Color(0xFF101828).withValues(alpha: 0.025),
blurRadius: 16,
offset: const Offset(0, 6),
),
],
),
padding: const EdgeInsets.fromLTRB(14, 8, 14, 6),
child: Row(
children: [
Builder(
@@ -189,7 +179,7 @@ class _HomePageState extends ConsumerState<HomePage>
);
},
),
const SizedBox(width: 12),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -261,39 +251,44 @@ class _HomePageState extends ConsumerState<HomePage>
.read(chatProvider.notifier)
.triggerAgent(agent, visual.label),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: selected
? AppColors.auraIndigo.withValues(alpha: 0.42)
: const Color(0xFFD5DAE4),
width: selected ? 1.4 : 1.1,
),
color: selected ? null : Colors.transparent,
gradient: selected ? AppColors.actionOutlineGradient : null,
borderRadius: AppRadius.pillBorder,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 16,
height: 16,
decoration: BoxDecoration(
gradient: visual.gradient,
borderRadius: BorderRadius.circular(6),
padding: const EdgeInsets.all(1.2),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 11.8,
vertical: 7.8,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.pillBorder,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 18,
height: 18,
decoration: BoxDecoration(
gradient: visual.gradient,
borderRadius: BorderRadius.circular(6),
),
child: Icon(visual.icon, size: 13, color: Colors.white),
),
child: Icon(visual.icon, size: 11, color: Colors.white),
),
const SizedBox(width: 6),
Text(
visual.label,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
const SizedBox(width: 6),
Text(
visual.label,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
),
),
],
],
),
),
),
);
@@ -314,7 +309,7 @@ class _HomePageState extends ConsumerState<HomePage>
ActiveAgent.health => fromModule('记数据', AppModuleVisuals.health),
ActiveAgent.diet => fromModule('拍饮食', AppModuleVisuals.diet),
ActiveAgent.medication => fromModule('药管家', AppModuleVisuals.medication),
ActiveAgent.report => fromModule('报告分析', AppModuleVisuals.report),
ActiveAgent.report => fromModule('报告', AppModuleVisuals.report),
ActiveAgent.exercise => fromModule('运动', AppModuleVisuals.exercise),
_ => null,
};
@@ -400,74 +395,87 @@ class _HomePageState extends ConsumerState<HomePage>
Widget _buildInputBar() {
return Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_RoundToolButton(
icon: LucideIcons.plus,
onTap: () => _showAttachmentPicker(context),
),
const SizedBox(width: 8),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 118),
child: TextField(
controller: _textCtrl,
focusNode: _focusNode,
style: const TextStyle(
fontSize: 15,
color: AppColors.textPrimary,
child: Container(
padding: const EdgeInsets.fromLTRB(6, 5, 6, 5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.pillBorder,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Material(
color: Colors.transparent,
child: InkWell(
customBorder: const CircleBorder(),
onTap: () => _showAttachmentPicker(context),
child: Ink(
width: 38,
height: 38,
decoration: const BoxDecoration(
gradient: AppColors.primaryGradient,
shape: BoxShape.circle,
),
child: const Icon(
LucideIcons.plus,
size: 21,
color: Colors.white,
),
),
maxLines: null,
textInputAction: TextInputAction.newline,
decoration: InputDecoration(
hintText: '输入你想说的...',
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 11,
),
),
const SizedBox(width: 6),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 112),
child: TextField(
controller: _textCtrl,
focusNode: _focusNode,
style: const TextStyle(
fontSize: 15,
color: AppColors.textPrimary,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(22),
borderSide: const BorderSide(color: AppColors.borderLight),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(22),
borderSide: const BorderSide(color: AppColors.borderLight),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(22),
borderSide: const BorderSide(
color: AppColors.auraIndigo,
width: 1.2,
maxLines: null,
textInputAction: TextInputAction.newline,
decoration: const InputDecoration(
hintText: '输入你想说的...',
filled: false,
isDense: true,
contentPadding: EdgeInsets.symmetric(
horizontal: 4,
vertical: 12,
),
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
onSubmitted: (_) => _sendMessage(),
),
),
),
const SizedBox(width: 6),
Material(
color: Colors.transparent,
child: InkWell(
customBorder: const CircleBorder(),
onTap: _sendMessage,
child: Ink(
width: 38,
height: 38,
decoration: const BoxDecoration(
gradient: AppColors.primaryGradient,
shape: BoxShape.circle,
),
child: const Icon(
LucideIcons.send,
size: 18,
color: Colors.white,
),
),
onSubmitted: (_) => _sendMessage(),
),
),
),
const SizedBox(width: 8),
GestureDetector(
onTap: _sendMessage,
child: Container(
width: 42,
height: 42,
margin: EdgeInsets.only(bottom: _pickedImagePath != null ? 0 : 2),
decoration: BoxDecoration(
gradient: AppColors.primaryGradient,
borderRadius: BorderRadius.circular(21),
boxShadow: AppColors.buttonShadow,
),
child: const Icon(
LucideIcons.send,
size: 19,
color: Colors.white,
),
),
),
],
],
),
),
);
}
@@ -517,23 +525,7 @@ class _HomePageState extends ConsumerState<HomePage>
title: const Text('上传 PDF'),
onTap: () async {
Navigator.pop(ctx);
_dismissKeyboard();
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: false,
);
if (result == null || result.files.isEmpty) return;
final pdfFile = result.files.first;
final path = pdfFile.path;
if (path == null || path.isEmpty) return;
// 上传 + 让 AI 看 PDF 内容
await ref
.read(chatProvider.notifier)
.sendPdf(path, pdfFile.name, _textCtrl.text.trim());
_textCtrl.clear();
_dismissKeyboard();
if (mounted) setState(() {});
await _pickPdf();
},
),
],
@@ -563,6 +555,34 @@ class _HomePageState extends ConsumerState<HomePage>
FocusManager.instance.primaryFocus?.unfocus();
}
Future<void> _pickPdf() async {
_dismissKeyboard();
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: false,
);
if (result == null || result.files.isEmpty) return;
final pdfFile = result.files.first;
final path = pdfFile.path;
if (path == null || path.isEmpty) return;
await ref
.read(chatProvider.notifier)
.sendPdf(path, pdfFile.name, _textCtrl.text.trim());
_textCtrl.clear();
_dismissKeyboard();
}
Future<void> _checkDueNotifications() async {
try {
await ref.read(inAppNotificationServiceProvider).checkDue();
} catch (_) {
// Network failures should not block the home page.
} finally {
ref.invalidate(notificationUnreadCountProvider);
}
}
Future<void> _pickFoodImage(ImageSource source) async {
final picked = await ImagePicker().pickImage(
source: source,
@@ -609,8 +629,8 @@ class _HeaderIconButton extends StatelessWidget {
clipBehavior: Clip.none,
children: [
Container(
width: 38,
height: 38,
width: 44,
height: 44,
decoration: BoxDecoration(
gradient: AppColors.surfaceGradient,
borderRadius: BorderRadius.circular(14),
@@ -647,28 +667,3 @@ class _HeaderIconButton extends StatelessWidget {
);
}
}
class _RoundToolButton extends StatelessWidget {
final IconData icon;
final VoidCallback onTap;
const _RoundToolButton({required this.icon, required this.onTap});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
width: 42,
height: 42,
margin: const EdgeInsets.only(bottom: 2),
decoration: BoxDecoration(
gradient: AppColors.surfaceGradient,
borderRadius: BorderRadius.circular(21),
border: Border.all(color: AppColors.borderLight),
boxShadow: AppColors.cardShadowLight,
),
child: Icon(icon, size: 21, color: AppColors.primaryDark),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/api_client.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
@@ -22,9 +25,6 @@ class MedicationCheckInPage extends ConsumerStatefulWidget {
}
class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
static const _visual = AppModuleVisuals.medication;
static const _softGreen = Color(0xFFEAF8EF);
Future<List<Map<String, dynamic>>>? _future;
final Set<String> _busyDoses = {};
@@ -34,11 +34,9 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
_load();
}
void _load() {
setState(() {
_future = ref.read(medicationReminderProvider.future);
});
}
void _load() => setState(() {
_future = ref.read(medicationReminderProvider.future);
});
Future<void> _refresh() async {
ref.invalidate(medicationReminderProvider);
@@ -48,26 +46,32 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
Future<void> _toggleDose(String medId, String time, bool taken) async {
final doseKey = '$medId-$time';
if (_busyDoses.contains(doseKey)) return;
if (medId.isEmpty || time.isEmpty || _busyDoses.contains(doseKey)) return;
setState(() => _busyDoses.add(doseKey));
try {
final api = ref.read(apiClientProvider);
if (taken) {
await api.delete('/api/medications/$medId/confirm-dose/$time');
} else {
await api.post(
final response = await api.post(
'/api/medications/$medId/confirm-dose',
data: {'scheduledTime': time, 'status': 'taken'},
);
final data = response.data is Map ? response.data['data'] : null;
if (data is Map && data['success'] == false) {
throw const ApiException('该次服药已经打卡');
}
}
ref.invalidate(medicationReminderProvider);
ref.invalidate(medicationListProvider);
_load();
} catch (e) {
debugPrint('[MedCheckIn] 打卡失败: $e');
} catch (error) {
if (mounted) {
AppToast.show(context, '打卡失败,请稍后重试', type: AppToastType.error);
AppToast.show(
context,
error is ApiException ? error.message : '打卡失败,请稍后重试',
type: AppToastType.error,
);
}
} finally {
if (mounted) setState(() => _busyDoses.remove(doseKey));
@@ -83,59 +87,86 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
onPressed: () => popRoute(ref),
),
title: const Text('服药打卡'),
centerTitle: true,
),
body: FutureBuilder<List<Map<String, dynamic>>>(
future: _future,
builder: (ctx, snap) {
if (snap.connectionState == ConnectionState.waiting &&
!snap.hasData) {
return const Center(
child: CircularProgressIndicator(color: AppTheme.primary),
);
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting &&
!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snap.hasError) {
if (snapshot.hasError) {
return AppErrorState(title: '用药信息加载失败', onRetry: _load);
}
final reminders = _filterReminders(snap.data ?? []);
final reminders = _filterReminders(snapshot.data ?? const []);
if (reminders.isEmpty) {
return RefreshIndicator(
onRefresh: _refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
SizedBox(height: 92),
children: [
const SizedBox(height: 92),
AppEmptyState(
icon: Icons.task_alt_outlined,
title: '今天的用药已完成',
subtitle: '下拉可刷新最新用药提醒',
icon: AppModuleVisuals.medication.icon,
title: '今天没有服药安排',
subtitle: '今日可以安心休息,下拉可刷新最新计划',
iconColor: AppColors.medication,
),
],
),
);
}
final grouped = _groupByMedication(reminders);
final total = reminders.length;
final taken = reminders.where(_isTaken).length;
final pending = total - taken;
final sorted = [...reminders]
..sort(
(a, b) => _formatTime(
a['scheduledTime']?.toString() ?? '',
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
);
final taken = sorted.where(_isTaken).length;
return RefreshIndicator(
onRefresh: _refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
padding: AppSpacing.page,
children: [
_CheckInSummary(total: total, taken: taken, pending: pending),
const SizedBox(height: 14),
...grouped.entries.map(
(entry) => _MedicationDoseCard(
name: entry.key,
doses: entry.value,
busyDoses: _busyDoses,
onToggle: _toggleDose,
_DoseProgressHeader(total: sorted.length, taken: taken),
const SizedBox(height: 18),
Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
children: List.generate(sorted.length, (index) {
final dose = sorted[index];
final key =
'${dose['id']?.toString() ?? ''}-${dose['scheduledTime']?.toString() ?? ''}';
return _DoseTimelineRow(
dose: dose,
isFirst: index == 0,
isLast: index == sorted.length - 1,
isBusy: _busyDoses.contains(key),
onToggle: _toggleDose,
);
}),
),
),
const SizedBox(height: 18),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
LucideIcons.shield,
size: 16,
color: AppColors.textHint,
),
SizedBox(width: 6),
Text(
'请按医嘱服药,如有不适及时咨询医生',
style: TextStyle(fontSize: 12, color: AppColors.textHint),
),
],
),
],
),
@@ -148,210 +179,88 @@ class _MedicationCheckInPageState extends ConsumerState<MedicationCheckInPage> {
List<Map<String, dynamic>> _filterReminders(
List<Map<String, dynamic>> reminders,
) {
if (widget.medId == null) return reminders;
return reminders.where((r) => r['id']?.toString() == widget.medId).toList();
}
Map<String, List<Map<String, dynamic>>> _groupByMedication(
List<Map<String, dynamic>> reminders,
) {
final grouped = <String, List<Map<String, dynamic>>>{};
for (final reminder in reminders) {
final name = reminder['name']?.toString().trim();
grouped
.putIfAbsent(name?.isNotEmpty == true ? name! : '未命名药品', () {
return <Map<String, dynamic>>[];
})
.add(reminder);
}
for (final doses in grouped.values) {
doses.sort(
(a, b) => _formatTime(
a['scheduledTime']?.toString() ?? '',
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
);
}
return grouped;
if (widget.medId == null || widget.medId!.isEmpty) return reminders;
return reminders
.where((item) => item['id']?.toString() == widget.medId)
.toList();
}
}
class _CheckInSummary extends StatelessWidget {
Map<String, List<Map<String, dynamic>>> groupMedicationReminders(
List<Map<String, dynamic>> reminders,
) {
final grouped = <String, List<Map<String, dynamic>>>{};
for (var index = 0; index < reminders.length; index++) {
final reminder = reminders[index];
final medicationId = reminder['id']?.toString().trim();
final key = medicationId?.isNotEmpty == true
? medicationId!
: 'unknown-$index';
grouped.putIfAbsent(key, () => <Map<String, dynamic>>[]).add(reminder);
}
for (final doses in grouped.values) {
doses.sort(
(a, b) => _formatTime(
a['scheduledTime']?.toString() ?? '',
).compareTo(_formatTime(b['scheduledTime']?.toString() ?? '')),
);
}
return grouped;
}
class _DoseProgressHeader extends StatelessWidget {
final int total;
final int taken;
final int pending;
const _CheckInSummary({
required this.total,
required this.taken,
required this.pending,
});
const _DoseProgressHeader({required this.total, required this.taken});
@override
Widget build(BuildContext context) {
final now = DateTime.now();
final progress = total == 0 ? 0.0 : taken / total;
return Container(
padding: const EdgeInsets.all(16),
padding: const EdgeInsets.fromLTRB(16, 16, 16, 15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.border, width: 1.1),
boxShadow: [AppTheme.shadowLight],
borderRadius: AppRadius.lgBorder,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 42,
height: 42,
decoration: BoxDecoration(
gradient: _MedicationCheckInPageState._visual.gradient,
borderRadius: BorderRadius.circular(14),
),
child: const Icon(
Icons.medication_outlined,
color: Colors.white,
size: 24,
),
),
const SizedBox(width: 12),
const Expanded(
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'今日服药进度',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
'${now.month}${now.day}日 · 今日用药',
style: AppTextStyles.sectionTitle,
),
SizedBox(height: 2),
const SizedBox(height: 3),
Text(
'按提醒时间逐项确认,保持用药节奏',
style: TextStyle(
fontSize: 13,
color: AppColors.textSecondary,
),
'$taken / $total 已完成',
style: AppTextStyles.listSubtitle,
),
],
),
),
Text(
'${(progress * 100).round()}%',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w900,
color: _MedicationCheckInPageState._visual.color,
style: AppTextStyles.summaryTitle.copyWith(
color: AppColors.medication,
),
),
],
),
const SizedBox(height: 16),
const SizedBox(height: 12),
ClipRRect(
borderRadius: BorderRadius.circular(999),
borderRadius: AppRadius.pillBorder,
child: LinearProgressIndicator(
minHeight: 9,
minHeight: 5,
value: progress,
backgroundColor: AppColors.cardInner,
valueColor: AlwaysStoppedAnimation<Color>(
_MedicationCheckInPageState._visual.color,
),
),
),
const SizedBox(height: 14),
Row(
children: [
Expanded(
child: _SummaryStat(
label: '待完成',
value: '$pending',
icon: Icons.schedule_outlined,
color: AppColors.warning,
),
),
const SizedBox(width: 8),
Expanded(
child: _SummaryStat(
label: '已打卡',
value: '$taken',
icon: Icons.check_circle_outline,
color: AppTheme.success,
),
),
const SizedBox(width: 8),
Expanded(
child: _SummaryStat(
label: '总次数',
value: '$total',
icon: Icons.format_list_numbered_outlined,
color: _MedicationCheckInPageState._visual.color,
),
),
],
),
],
),
);
}
}
class _SummaryStat extends StatelessWidget {
final String label;
final String value;
final IconData icon;
final Color color;
const _SummaryStat({
required this.label,
required this.value,
required this.icon,
required this.color,
});
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(minHeight: 58),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: color.withValues(alpha: 0.14)),
),
child: Row(
children: [
Icon(icon, color: color, size: 17),
const SizedBox(width: 7),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: AppColors.textSecondary,
),
),
],
valueColor: const AlwaysStoppedAnimation(AppColors.medication),
),
),
],
@@ -360,138 +269,16 @@ class _SummaryStat extends StatelessWidget {
}
}
class _MedicationDoseCard extends StatelessWidget {
final String name;
final List<Map<String, dynamic>> doses;
final Set<String> busyDoses;
final Future<void> Function(String medId, String time, bool taken) onToggle;
const _MedicationDoseCard({
required this.name,
required this.doses,
required this.busyDoses,
required this.onToggle,
});
@override
Widget build(BuildContext context) {
final dosage = doses.first['dosage']?.toString().trim() ?? '';
final takenCount = doses.where(_isTaken).length;
final allTaken = takenCount == doses.length;
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: allTaken
? AppTheme.success.withValues(alpha: 0.26)
: AppColors.border,
width: 1.1,
),
boxShadow: [AppTheme.shadowLight],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: allTaken
? _MedicationCheckInPageState._softGreen
: _MedicationCheckInPageState._visual.lightColor,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: AppColors.borderLight),
),
child: Icon(
allTaken ? Icons.done_all_rounded : Icons.medication_liquid,
color: allTaken
? AppTheme.success
: _MedicationCheckInPageState._visual.color,
size: 24,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
if (dosage.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
dosage,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
color: AppColors.textSecondary,
),
),
],
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
decoration: BoxDecoration(
color: allTaken
? _MedicationCheckInPageState._softGreen
: AppColors.cardInner,
borderRadius: BorderRadius.circular(999),
),
child: Text(
'$takenCount/${doses.length}',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w800,
color: allTaken
? AppTheme.success
: AppColors.textSecondary,
),
),
),
],
),
const SizedBox(height: 14),
for (var i = 0; i < doses.length; i++) ...[
_DoseRow(
dose: doses[i],
isLast: i == doses.length - 1,
isBusy: busyDoses.contains(
'${doses[i]['id']?.toString() ?? ''}-${doses[i]['scheduledTime']?.toString() ?? ''}',
),
onToggle: onToggle,
),
],
],
),
);
}
}
class _DoseRow extends StatelessWidget {
class _DoseTimelineRow extends StatelessWidget {
final Map<String, dynamic> dose;
final bool isFirst;
final bool isLast;
final bool isBusy;
final Future<void> Function(String medId, String time, bool taken) onToggle;
final Future<void> Function(String, String, bool) onToggle;
const _DoseRow({
const _DoseTimelineRow({
required this.dose,
required this.isFirst,
required this.isLast,
required this.isBusy,
required this.onToggle,
@@ -499,171 +286,175 @@ class _DoseRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final time = dose['scheduledTime']?.toString() ?? '';
final medId = dose['id']?.toString() ?? '';
final isTaken = _isTaken(dose);
final displayTime = _formatTime(time);
final statusColor = isTaken ? AppTheme.success : AppColors.warning;
final rawTime = dose['scheduledTime']?.toString() ?? '';
final time = _formatTime(rawTime);
final name = dose['name']?.toString().trim().isNotEmpty == true
? dose['name'].toString().trim()
: '未命名药品';
final dosage = dose['dosage']?.toString().trim() ?? '';
final status = dose['status']?.toString().toLowerCase() ?? 'scheduled';
final taken = status == 'taken';
final scheduled = status == 'scheduled';
final color = _statusColor(status);
return IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
return ConstrainedBox(
constraints: const BoxConstraints(minHeight: 92),
child: Stack(
children: [
SizedBox(
width: 28,
child: Column(
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Row(
children: [
Container(
width: 22,
height: 22,
decoration: BoxDecoration(
color: isTaken ? AppTheme.success : Colors.white,
shape: BoxShape.circle,
border: Border.all(
color: isTaken ? AppTheme.success : AppColors.border,
width: 2,
),
SizedBox(
width: 54,
child: Text(
time,
style: AppTextStyles.listTitle.copyWith(fontSize: 18),
),
child: isTaken
? const Icon(Icons.check, size: 14, color: Colors.white)
: null,
),
if (!isLast)
Expanded(
child: Container(
width: 2,
margin: const EdgeInsets.symmetric(vertical: 4),
color: isTaken
? AppTheme.success.withValues(alpha: 0.34)
: AppColors.borderLight,
),
SizedBox(
width: 28,
height: 92,
child: Stack(
alignment: Alignment.center,
children: [
if (!isFirst)
Positioned(
top: 0,
bottom: 46,
child: Container(width: 2, color: AppColors.divider),
),
if (!isLast)
Positioned(
top: 46,
bottom: 0,
child: Container(width: 2, color: AppColors.divider),
),
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: taken ? color : Colors.white,
shape: BoxShape.circle,
border: Border.all(color: color, width: 2),
),
child: taken
? const Icon(
Icons.check,
size: 13,
color: Colors.white,
)
: null,
),
],
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listTitle.copyWith(fontSize: 16),
),
const SizedBox(height: 3),
Text(
[
dosage,
_statusLabel(status),
].where((text) => text.isNotEmpty).join(' · '),
style: AppTextStyles.listSubtitle.copyWith(
fontSize: 13,
color: color,
),
),
],
),
),
const SizedBox(width: 8),
SizedBox(
height: 36,
child: OutlinedButton(
onPressed: isBusy || scheduled
? null
: () => onToggle(medId, rawTime, taken),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 13),
backgroundColor: taken
? AppColors.successLight
: Colors.white,
foregroundColor: taken
? AppColors.successText
: AppColors.medication,
disabledForegroundColor: AppColors.textHint,
side: BorderSide(
color: scheduled
? AppColors.borderLight
: (taken
? AppColors.successText
: AppColors.medication),
),
shape: RoundedRectangleBorder(
borderRadius: AppRadius.smBorder,
),
),
child: isBusy
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
scheduled ? '未到时间' : (taken ? '撤销' : '打卡'),
style: AppTextStyles.miniButton,
),
),
),
],
),
),
const SizedBox(width: 10),
Expanded(
child: Padding(
padding: EdgeInsets.only(bottom: isLast ? 0 : 12),
child: Container(
padding: const EdgeInsets.fromLTRB(12, 10, 10, 10),
decoration: BoxDecoration(
color: isTaken
? _MedicationCheckInPageState._softGreen
: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isTaken
? AppTheme.success.withValues(alpha: 0.18)
: AppColors.borderLight,
),
),
child: Row(
children: [
Icon(Icons.access_time, size: 18, color: statusColor),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
displayTime,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: isTaken ? AppTheme.textSub : AppTheme.text,
),
),
const SizedBox(height: 1),
Text(
isTaken ? '已完成打卡' : '等待确认服用',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: isTaken
? AppTheme.success
: AppColors.textSecondary,
),
),
],
),
),
const SizedBox(width: 8),
SizedBox(
height: 36,
child: FilledButton.icon(
onPressed: isBusy || medId.isEmpty || time.isEmpty
? null
: () => onToggle(medId, time, isTaken),
style: FilledButton.styleFrom(
backgroundColor: isTaken
? Colors.white
: _MedicationCheckInPageState._visual.color,
foregroundColor: isTaken
? AppTheme.success
: Colors.white,
disabledBackgroundColor: AppColors.cardInner,
disabledForegroundColor: AppColors.textHint,
padding: const EdgeInsets.symmetric(horizontal: 12),
minimumSize: const Size(0, 36),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isTaken
? AppTheme.success.withValues(alpha: 0.34)
: Colors.transparent,
),
),
),
icon: isBusy
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.textHint,
),
)
: Icon(
isTaken
? Icons.undo_rounded
: Icons.check_rounded,
size: 17,
),
label: Text(
isTaken ? '撤销' : '打卡',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
),
),
),
),
],
),
if (!isLast)
const Positioned(
left: 96,
right: 0,
bottom: 0,
child: Divider(
height: 1,
thickness: 0.7,
color: AppColors.divider,
),
),
),
],
),
);
}
}
bool _isTaken(Map<String, dynamic> dose) {
return dose['status']?.toString().toLowerCase() == 'taken';
}
bool _isTaken(Map<String, dynamic> dose) =>
dose['status']?.toString().toLowerCase() == 'taken';
String _formatTime(String raw) {
final value = raw.trim();
if (value.length >= 5 && value[2] == ':') return value.substring(0, 5);
final parsed = DateTime.tryParse(value);
if (parsed == null) return value;
final hour = parsed.hour.toString().padLeft(2, '0');
final minute = parsed.minute.toString().padLeft(2, '0');
return '$hour:$minute';
return value.length >= 5 ? value.substring(0, 5) : value;
}
String _statusLabel(String status) => switch (status) {
'taken' => '已完成',
'overdue' => '已超时',
'upcoming' => '待完成',
'skipped' => '已跳过',
_ => '未到时间',
};
Color _statusColor(String status) => switch (status) {
'taken' => AppColors.successText,
'overdue' => AppColors.errorText,
'upcoming' => AppColors.blueMeasure,
'skipped' => AppColors.textHint,
_ => AppColors.textHint,
};

View File

@@ -1,12 +1,18 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/api_client.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart';
import '../../widgets/app_error_state.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/common_widgets.dart';
import '../care_plan_ui_logic.dart';
import 'medication_ui_logic.dart';
class MedicationEditPage extends ConsumerStatefulWidget {
final String? id;
@@ -18,117 +24,163 @@ class MedicationEditPage extends ConsumerStatefulWidget {
}
class _MedicationEditPageState extends ConsumerState<MedicationEditPage> {
final _nameCtrl = TextEditingController();
final _dosageCtrl = TextEditingController();
final _notesCtrl = TextEditingController();
int _timesPerDay = 2;
final _nameController = TextEditingController();
final _dosageController = TextEditingController();
final _notesController = TextEditingController();
List<TimeOfDay> _times = [
const TimeOfDay(hour: 8, minute: 0),
const TimeOfDay(hour: 18, minute: 0),
];
DateTime _start = DateTime.now();
DateTime? _end;
DateTime _startDate = DateTime.now();
DateTime? _endDate;
bool _saving = false;
bool _loading = false;
String? _loadError;
bool get _editing => widget.id?.isNotEmpty == true;
@override
void initState() {
super.initState();
if (widget.id != null) _load();
if (_editing) _load();
}
@override
void dispose() {
_nameCtrl.dispose();
_dosageCtrl.dispose();
_notesCtrl.dispose();
_nameController.dispose();
_dosageController.dispose();
_notesController.dispose();
super.dispose();
}
Future<void> _load() async {
final srv = ref.read(medicationServiceProvider);
final list = await srv.getList();
final m = list.cast<Map<String, dynamic>?>().firstWhere(
(x) => x?['id']?.toString() == widget.id,
orElse: () => null,
);
if (m == null || !mounted) return;
_nameCtrl.text = m['name']?.toString() ?? '';
_dosageCtrl.text = m['dosage']?.toString() ?? '';
_notesCtrl.text = m['notes']?.toString() ?? '';
final tod =
(m['timeOfDay'] as List?)?.map((t) {
final parts = t.toString().split(':');
return TimeOfDay(
hour: int.tryParse(parts[0]) ?? 8,
minute: int.tryParse(parts.length > 1 ? parts[1] : '0') ?? 0,
);
}).toList() ??
[
const TimeOfDay(hour: 8, minute: 0),
const TimeOfDay(hour: 18, minute: 0),
];
_timesPerDay = tod.length;
_times = tod;
if (m['startDate'] != null) {
_start = DateTime.tryParse(m['startDate'].toString()) ?? DateTime.now();
setState(() {
_loading = true;
_loadError = null;
});
try {
final medications = await ref.read(medicationServiceProvider).getList();
final medication = medications.cast<Map<String, dynamic>?>().firstWhere(
(item) => item?['id']?.toString() == widget.id,
orElse: () => null,
);
if (medication == null) throw const ApiException('该用药记录不存在');
_nameController.text = medication['name']?.toString() ?? '';
_dosageController.text = medication['dosage']?.toString() ?? '';
_notesController.text = medication['notes']?.toString() ?? '';
final loadedTimes =
(medication['timeOfDay'] as List?)
?.map((value) => _parseTime(value))
.whereType<TimeOfDay>()
.toList() ??
[];
if (loadedTimes.isNotEmpty) _times = loadedTimes;
_startDate =
DateTime.tryParse(medication['startDate']?.toString() ?? '') ??
DateTime.now();
_endDate = DateTime.tryParse(medication['endDate']?.toString() ?? '');
} catch (error) {
_loadError = error is ApiException ? error.message : '用药信息加载失败';
} finally {
if (mounted) setState(() => _loading = false);
}
if (m['endDate'] != null) _end = DateTime.tryParse(m['endDate'].toString());
setState(() {});
}
Future<void> _save() async {
final name = _nameCtrl.text.trim();
if (name.isEmpty) {
AppToast.show(context, '请输入药品名称', type: AppToastType.warning);
final timeValues = _times.map(_timeValue).toList();
final validation = validateMedicationForm(
name: _nameController.text,
dosage: _dosageController.text,
times: timeValues,
startDate: _startDate,
endDate: _endDate,
);
if (validation != null) {
AppToast.show(context, validation, type: AppToastType.warning);
return;
}
setState(() => _loading = true);
final data = {
'name': name,
'dosage': _dosageCtrl.text.trim(),
'frequency': 'Daily',
'notes': _notesCtrl.text.trim(),
'timeOfDay': _times
.map(
(t) =>
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}',
)
.toList(),
'startDate':
'${_start.year}-${_start.month.toString().padLeft(2, '0')}-${_start.day.toString().padLeft(2, '0')}',
if (_end != null)
'endDate':
'${_end!.year}-${_end!.month.toString().padLeft(2, '0')}-${_end!.day.toString().padLeft(2, '0')}',
setState(() => _saving = true);
final payload = <String, dynamic>{
'name': _nameController.text.trim(),
'dosage': _dosageController.text.trim(),
'frequency': _frequencyForTimes(_times.length),
'notes': _notesController.text.trim(),
'timeOfDay': timeValues,
'startDate': _dateValue(_startDate),
'endDate': _endDate == null ? null : _dateValue(_endDate!),
'source': 'Manual',
};
final srv = ref.read(medicationServiceProvider);
try {
if (widget.id != null) {
await srv.update(widget.id!, data);
final service = ref.read(medicationServiceProvider);
if (_editing) {
await service.update(widget.id!, payload);
} else {
await srv.create(data);
await service.create(payload);
}
ref.invalidate(medicationListProvider);
ref.invalidate(medicationReminderProvider);
if (mounted) popRoute(ref);
} catch (_) {
if (mounted) {
AppToast.show(context, '保存失败', type: AppToastType.error);
AppToast.show(
context,
_editing ? '用药已更新' : '用药已添加',
type: AppToastType.success,
);
popRoute(ref);
}
} catch (error) {
if (mounted) {
AppToast.show(
context,
error is ApiException ? error.message : '保存失败,请稍后重试',
type: AppToastType.error,
);
}
} finally {
if (mounted) setState(() => _saving = false);
}
if (mounted) setState(() => _loading = false);
}
void _updateTimes(int n) {
setState(() {
_timesPerDay = n;
while (_times.length < n) {
_times.add(const TimeOfDay(hour: 12, minute: 0));
Future<void> _deleteMedication() async {
if (!_editing || _saving) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('删除用药'),
content: Text('确定删除“${_nameController.text.trim()}”吗?相关服药记录也将一并删除。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('删除'),
),
],
),
);
if (confirmed != true || !mounted) return;
setState(() => _saving = true);
try {
await ref.read(medicationServiceProvider).deleteMedication(widget.id!);
ref.invalidate(medicationListProvider);
ref.invalidate(medicationReminderProvider);
if (mounted) {
AppToast.show(context, '用药已删除', type: AppToastType.success);
popRoute(ref);
}
while (_times.length > n) {
_times.removeLast();
} catch (error) {
if (mounted) {
AppToast.show(
context,
error is ApiException ? error.message : '删除失败,请稍后重试',
type: AppToastType.error,
);
}
});
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
@@ -139,282 +191,371 @@ class _MedicationEditPageState extends ConsumerState<MedicationEditPage> {
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: Text(widget.id != null ? '编辑用药' : '添加用药'),
title: Text(_editing ? '编辑用药' : '添加用药'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Row(
children: [
Expanded(
flex: 3,
child: _field('药品名称', _nameCtrl, hint: '如:阿司匹林'),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: _field('剂量', _dosageCtrl, hint: '100mg'),
),
],
),
const SizedBox(height: 16),
_label('每日服药次数'),
const SizedBox(height: 8),
GestureDetector(
onTap: () async {
final n = await showAppCountPicker(
context,
initialValue: _timesPerDay,
min: 1,
max: 4,
label: '',
);
if (n != null) _updateTimes(n);
},
child: _PickerBox(
child: Text('$_timesPerDay 次/天', style: AppTextStyles.formValue),
),
),
const SizedBox(height: 16),
_label('服药时间'),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: List.generate(
_timesPerDay,
(i) => GestureDetector(
onTap: () async {
final t = await showAppTimePicker(
context,
initialTime: _times[i],
);
if (t != null) setState(() => _times[i] = t);
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 10,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.border, width: 1),
),
child: Text(
'${_times[i].hour.toString().padLeft(2, '0')}:${_times[i].minute.toString().padLeft(2, '0')}',
style: AppTextStyles.formValue,
),
bottomNavigationBar: _loading || _loadError != null
? null
: SafeArea(
top: false,
child: Container(
color: Colors.white,
padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
child: AppGradientOutlineButton(
label: _editing ? '保存修改' : '添加用药',
onPressed: _saving ? null : _save,
loading: _saving,
),
),
),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _dateField(
'开始日期',
_start,
(d) => setState(() => _start = d),
body: _loading
? const Center(child: CircularProgressIndicator())
: _loadError != null
? AppErrorState(title: _loadError!, onRetry: _load)
: ListView(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
children: [
_FormSection(
title: '药品信息',
children: [
_TextFieldRow(
label: '药品名称',
controller: _nameController,
hint: '请输入药品名称',
),
const _SectionDivider(),
_TextFieldRow(
label: '剂量',
controller: _dosageController,
hint: '例如 100 mg',
),
],
),
),
const SizedBox(width: 12),
Expanded(
child: _dateFieldOpt(
'结束日期(可选)',
_end,
(d) => setState(() => _end = d),
),
),
],
),
const SizedBox(height: 16),
_field('备注', _notesCtrl, hint: '如:饭后服用、睡前'),
const SizedBox(height: 32),
_GradientOutlineButton(
onPressed: _loading ? null : _save,
label: _loading ? '保存中...' : '保存',
),
const SizedBox(height: 20),
],
),
);
}
Widget _label(String text) => Text(text, style: AppTextStyles.formLabel);
Widget _field(String label, TextEditingController ctrl, {String? hint}) =>
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_label(label),
const SizedBox(height: 6),
TextField(
controller: ctrl,
decoration: InputDecoration(
hintText: hint,
filled: true,
fillColor: AppTheme.surface,
border: _inputBorder(AppColors.border),
enabledBorder: _inputBorder(AppColors.border),
focusedBorder: _inputBorder(AppColors.primary),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 12,
),
),
style: AppTextStyles.formValue,
),
],
);
Widget _dateField(String label, DateTime val, ValueChanged<DateTime> cb) =>
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_label(label),
const SizedBox(height: 6),
GestureDetector(
onTap: () async {
final d = await showAppDatePicker(
context,
initialDate: val,
firstDate: DateTime(2024),
lastDate: DateTime(2030),
);
if (d != null) cb(d);
},
child: _PickerBox(
child: Text(_displayDate(val), style: AppTextStyles.formValue),
),
),
],
);
Widget _dateFieldOpt(
String label,
DateTime? val,
ValueChanged<DateTime?> cb,
) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_label(label),
const SizedBox(height: 6),
GestureDetector(
onTap: () async {
final d = await showAppDatePicker(
context,
initialDate: val ?? DateTime.now(),
firstDate: DateTime(2024),
lastDate: DateTime(2030),
);
if (d != null) cb(d);
},
child: _PickerBox(
child: Row(
children: [
Expanded(
child: Text(
val != null ? _displayDate(val) : '不设置',
style: AppTextStyles.formValue.copyWith(
color: val != null ? null : AppTheme.textHint,
),
),
),
if (val != null)
GestureDetector(
onTap: () => cb(null),
child: const Icon(
Icons.close,
size: 19,
color: AppColors.textHint,
),
),
],
),
),
),
],
);
OutlineInputBorder _inputBorder(Color color) => OutlineInputBorder(
borderRadius: AppRadius.mdBorder,
borderSide: BorderSide(color: color),
);
}
class _PickerBox extends StatelessWidget {
final Widget child;
const _PickerBox({required this.child});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppTheme.surface,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.border),
),
child: child,
);
}
}
class _GradientOutlineButton extends StatelessWidget {
final VoidCallback? onPressed;
final String label;
const _GradientOutlineButton({required this.onPressed, required this.label});
@override
Widget build(BuildContext context) {
final enabled = onPressed != null;
return Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: enabled ? AppColors.actionOutlineGradient : null,
color: enabled ? null : AppColors.border,
borderRadius: AppRadius.lgBorder,
),
padding: const EdgeInsets.all(1.4),
child: Material(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
child: InkWell(
onTap: onPressed,
borderRadius: AppRadius.lgBorder,
child: SizedBox(
height: 46,
child: Center(
child: enabled
? ShaderMask(
shaderCallback: (bounds) =>
AppColors.actionOutlineGradient.createShader(bounds),
child: Text(
label,
style: AppTextStyles.button.copyWith(
color: Colors.white,
),
),
)
: Text(
label,
style: AppTextStyles.button.copyWith(
color: AppColors.textHint,
const SizedBox(height: 16),
_FormSection(
title: '服用安排',
children: [
_PickerRow(
label: '每日次数',
value: '${_times.length}',
onTap: _pickCount,
),
const _SectionDivider(),
Padding(
padding: const EdgeInsets.fromLTRB(16, 11, 12, 11),
child: Row(
children: [
const Text('服药时间', style: AppTextStyles.formLabel),
const SizedBox(width: 12),
Expanded(
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: List.generate(
_times.length,
(index) => _TimeButton(
value: _timeValue(_times[index]),
onTap: () => _pickTime(index),
),
),
),
),
],
),
),
],
),
const SizedBox(height: 16),
_FormSection(
title: '用药周期',
children: [
_PickerRow(
label: '开始日期',
value: _displayDate(_startDate),
onTap: _pickStartDate,
),
const _SectionDivider(),
_PickerRow(
label: '结束日期',
value: _endDate == null ? '长期' : _displayDate(_endDate!),
onTap: _pickEndDate,
onClear: _endDate == null
? null
: () => setState(() => _endDate = null),
),
],
),
const SizedBox(height: 16),
_FormSection(
title: '备注',
children: [
Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: _notesController,
minLines: 3,
maxLines: 5,
maxLength: 200,
decoration: const InputDecoration(
hintText: '可填写饭前、饭后或其他用药要求(选填)',
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
filled: false,
contentPadding: EdgeInsets.zero,
),
),
),
],
),
if (_editing) ...[
const SizedBox(height: 16),
Material(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _saving ? null : _deleteMedication,
child: const SizedBox(
height: 54,
child: Center(
child: Text(
'删除用药',
style: TextStyle(
color: AppColors.errorText,
fontSize: 15,
fontWeight: FontWeight.w700,
),
),
),
),
),
),
],
],
),
);
}
Future<void> _pickCount() async {
final count = await showAppCountPicker(
context,
initialValue: _times.length,
min: 1,
max: 4,
label: '',
);
if (count == null || !mounted) return;
setState(() {
while (_times.length < count) {
final hour = (8 + _times.length * 5).clamp(0, 23);
_times.add(TimeOfDay(hour: hour, minute: 0));
}
while (_times.length > count) {
_times.removeLast();
}
});
}
Future<void> _pickTime(int index) async {
final value = await showAppTimePicker(context, initialTime: _times[index]);
if (value != null && mounted) setState(() => _times[index] = value);
}
Future<void> _pickStartDate() async {
final value = await showAppDatePicker(
context,
initialDate: _startDate,
firstDate: DateTime(2020),
lastDate: DateTime(2035),
);
if (value != null && mounted) setState(() => _startDate = value);
}
Future<void> _pickEndDate() async {
final value = await showAppDatePicker(
context,
initialDate: _endDate ?? _startDate,
firstDate: DateTime(2020),
lastDate: DateTime(2035),
);
if (value != null && mounted) setState(() => _endDate = value);
}
}
class _FormSection extends StatelessWidget {
final String title;
final List<Widget> children;
const _FormSection({required this.title, required this.children});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 2, bottom: 8),
child: Text(
title,
style: AppTextStyles.sectionTitle.copyWith(fontSize: 16),
),
),
Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(children: children),
),
],
);
}
}
class _TextFieldRow extends StatelessWidget {
final String label;
final TextEditingController controller;
final String hint;
const _TextFieldRow({
required this.label,
required this.controller,
required this.hint,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
SizedBox(
width: 82,
child: Text(label, style: AppTextStyles.formLabel),
),
Expanded(
child: TextField(
controller: controller,
textAlign: TextAlign.right,
decoration: InputDecoration(
hintText: hint,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
filled: false,
contentPadding: const EdgeInsets.symmetric(vertical: 14),
),
style: AppTextStyles.formValue,
),
),
],
),
);
}
}
class _PickerRow extends StatelessWidget {
final String label;
final String value;
final VoidCallback onTap;
final VoidCallback? onClear;
const _PickerRow({
required this.label,
required this.value,
required this.onTap,
this.onClear,
});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 15, 10, 15),
child: Row(
children: [
Expanded(child: Text(label, style: AppTextStyles.formLabel)),
Text(value, style: AppTextStyles.formValue),
if (onClear != null)
IconButton(
tooltip: '清除结束日期',
visualDensity: VisualDensity.compact,
onPressed: onClear,
icon: const Icon(Icons.close, size: 18),
)
else
const Padding(
padding: EdgeInsets.only(left: 6),
child: Icon(
LucideIcons.chevronRight,
color: AppColors.textHint,
size: 20,
),
),
],
),
),
);
}
}
String _displayDate(DateTime date) {
return '${date.year}/${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')}';
class _TimeButton extends StatelessWidget {
final String value;
final VoidCallback onTap;
const _TimeButton({required this.value, required this.onTap});
@override
Widget build(BuildContext context) {
return OutlinedButton.icon(
onPressed: onTap,
icon: const Icon(LucideIcons.clock, size: 18),
label: Text(value),
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.primary,
side: BorderSide(color: AppColors.primary.withValues(alpha: 0.38)),
shape: RoundedRectangleBorder(borderRadius: AppRadius.smBorder),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
),
);
}
}
class _SectionDivider extends StatelessWidget {
const _SectionDivider();
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.only(left: 16),
child: Divider(height: 1, thickness: 0.7, color: AppColors.divider),
);
}
}
TimeOfDay? _parseTime(Object value) {
final parts = value.toString().split(':');
if (parts.length < 2) return null;
final hour = int.tryParse(parts[0]);
final minute = int.tryParse(parts[1]);
if (hour == null || minute == null) return null;
return TimeOfDay(hour: hour, minute: minute);
}
String _timeValue(TimeOfDay value) =>
'${value.hour.toString().padLeft(2, '0')}:${value.minute.toString().padLeft(2, '0')}';
String _dateValue(DateTime value) =>
'${value.year}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
String _displayDate(DateTime value) => formatMedicationFormDate(value);
String _frequencyForTimes(int count) => switch (count) {
2 => 'TwiceDaily',
3 => 'ThreeTimesDaily',
_ => 'Daily',
};

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/api_client.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
@@ -8,20 +11,21 @@ import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart';
import '../../widgets/app_empty_state.dart';
import '../../widgets/app_future_view.dart';
import '../../widgets/app_status_badge.dart';
import '../../widgets/common_widgets.dart';
import '../../widgets/enterprise_widgets.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/common_widgets.dart';
import '../care_plan_ui_logic.dart';
import 'medication_ui_logic.dart';
class MedicationListPage extends ConsumerStatefulWidget {
const MedicationListPage({super.key});
@override
ConsumerState<MedicationListPage> createState() => _MedicationListPageState();
}
class _MedicationListPageState extends ConsumerState<MedicationListPage> {
static const _medVisual = AppModuleVisuals.medication;
Future<List<Map<String, dynamic>>>? _future;
final Set<String> _deleting = {};
@override
void initState() {
@@ -29,22 +33,53 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
_load();
}
void _load() {
setState(() {
_future = ref.read(medicationServiceProvider).getMedications('');
});
void _load() => setState(() {
_future = ref.read(medicationServiceProvider).getMedications('');
});
Future<void> _refresh() async {
_load();
await _future;
}
Future<void> _delete(String id) async {
Future<void> _confirmDelete(String id, String name) async {
if (id.isEmpty || _deleting.contains(id)) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('删除用药'),
content: Text('确定删除“$name”吗?相关服药记录也将一并删除。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('删除'),
),
],
),
);
if (confirmed != true || !mounted) return;
setState(() => _deleting.add(id));
try {
await ref.read(medicationServiceProvider).deleteMedication(id);
ref.invalidate(medicationListProvider);
ref.invalidate(medicationReminderProvider);
_load();
if (mounted) AppToast.show(context, '已删除', type: AppToastType.success);
} catch (_) {
if (mounted) AppToast.show(context, '用药已删除', type: AppToastType.success);
} catch (error) {
if (mounted) {
AppToast.show(context, '删除失败,请稍后重试', type: AppToastType.error);
AppToast.show(
context,
error is ApiException ? error.message : '删除失败,请稍后重试',
type: AppToastType.error,
);
}
} finally {
if (mounted) setState(() => _deleting.remove(id));
}
}
@@ -58,83 +93,67 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
),
title: const Text('用药管理'),
),
floatingActionButton: _GradientFab(
gradient: _medVisual.gradient,
onTap: () => pushRoute(ref, 'medicationEdit'),
floatingActionButton: AppCreateFab(
tooltip: '添加用药',
onPressed: () => pushRoute(ref, 'medicationEdit'),
),
body: AppFutureView<List<Map<String, dynamic>>>(
future: _future,
onRetry: _load,
errorTitle: '用药信息加载失败',
onData: (ctx, list) {
if (list.isEmpty) {
onData: (_, medications) {
if (medications.isEmpty) {
return AppEmptyState(
icon: _medVisual.icon,
icon: AppModuleVisuals.medication.icon,
title: '暂无用药',
subtitle: '点击右下角添加药品',
subtitle: '点击右下角添加药品',
iconColor: AppColors.medication,
);
}
final activeCount = list.where((m) => m['isActive'] == true).length;
final reminderCount = list.where((m) {
final times = m['timeOfDay'] as List?;
return times != null && times.isNotEmpty;
}).length;
return ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 88),
children: [
EnterpriseHeader(
title: '今日用药概览',
subtitle: '集中管理服药计划、剂量和每日打卡状态',
icon: _medVisual.icon,
color: _medVisual.color,
accent: AppColors.primary,
showIcon: false,
stats: [
EnterpriseStat(
label: '药品总数',
value: '${list.length}',
icon: Icons.inventory_2_outlined,
),
EnterpriseStat(
label: '服用中',
value: '$activeCount',
icon: Icons.check_circle_outline,
),
EnterpriseStat(
label: '有提醒',
value: '$reminderCount',
icon: Icons.alarm_outlined,
),
],
),
const SizedBox(height: 10),
_MedicationListGroup(
children: List.generate(list.length, (i) {
final m = list[i];
final times =
(m['timeOfDay'] as List?)
?.map((t) => t.toString().substring(0, 5))
.join(' ') ??
'';
final isActive = m['isActive'] == true;
final id = m['id']?.toString() ?? '';
return SwipeDeleteTile(
key: Key(id),
onDelete: () => _delete(id),
onTap: () =>
pushRoute(ref, 'medCheckIn', params: {'id': id}),
margin: EdgeInsets.zero,
child: _MedicationRow(
name: m['name']?.toString() ?? '',
subtitle: '${m['dosage'] ?? ''} $times',
isActive: isActive,
showDivider: i < list.length - 1,
visual: _medVisual,
final groups = <CarePlanPhase, List<Map<String, dynamic>>>{
for (final phase in CarePlanPhase.values) phase: [],
};
for (final medication in medications) {
final phase = resolveCarePlanPhase(
enabled: medication['isActive'] == true,
startDate: medication['startDate']?.toString(),
endDate: medication['endDate']?.toString(),
);
groups[phase]!.add(medication);
}
final active = groups[CarePlanPhase.active]!;
final doseCount = active.fold<int>(
0,
(sum, item) => sum + ((item['timeOfDay'] as List?)?.length ?? 0),
);
return RefreshIndicator(
onRefresh: _refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: AppSpacing.pageWithFab,
children: [
_MedicationOverview(
activeCount: active.length,
doseCount: doseCount,
nextReminder: _nextReminder(active),
),
const SizedBox(height: 18),
for (final phase in CarePlanPhase.values)
if (groups[phase]!.isNotEmpty) ...[
_MedicationPhaseGroup(
phase: phase,
medications: groups[phase]!,
deleting: _deleting,
onOpen: (id) =>
pushRoute(ref, 'medCheckIn', params: {'id': id}),
onEdit: (id) =>
pushRoute(ref, 'medicationEdit', params: {'id': id}),
onDelete: _confirmDelete,
),
);
}),
),
],
const SizedBox(height: 18),
],
],
),
);
},
),
@@ -142,104 +161,223 @@ class _MedicationListPageState extends ConsumerState<MedicationListPage> {
}
}
class _GradientFab extends StatelessWidget {
final Gradient gradient;
final VoidCallback onTap;
class _MedicationOverview extends StatelessWidget {
final int activeCount;
final int doseCount;
final String? nextReminder;
const _GradientFab({required this.gradient, required this.onTap});
@override
Widget build(BuildContext context) {
return Container(
width: 56,
height: 56,
decoration: BoxDecoration(
gradient: gradient,
borderRadius: AppRadius.lgBorder,
boxShadow: [
BoxShadow(
color: AppColors.medication.withValues(alpha: 0.22),
blurRadius: 16,
offset: const Offset(0, 8),
),
],
),
child: Material(
color: Colors.transparent,
borderRadius: AppRadius.lgBorder,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.lgBorder,
child: const Icon(Icons.add, size: 28, color: Colors.white),
),
),
);
}
}
class _MedicationListGroup extends StatelessWidget {
final List<Widget> children;
const _MedicationListGroup({required this.children});
@override
Widget build(BuildContext context) {
return Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.xlBorder,
),
child: Column(children: children),
);
}
}
class _MedicationRow extends StatelessWidget {
final String name;
final String subtitle;
final bool isActive;
final bool showDivider;
final AppModuleVisual visual;
const _MedicationRow({
required this.name,
required this.subtitle,
required this.isActive,
required this.showDivider,
required this.visual,
const _MedicationOverview({
required this.activeCount,
required this.doseCount,
required this.nextReminder,
});
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
padding: AppSpacing.panel,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Expanded(
child: Text('用药概览', style: AppTextStyles.sectionTitle),
),
Text(
nextReminder == null ? '今日已无待服' : '下次 $nextReminder',
style: AppTextStyles.listSubtitle.copyWith(
color: nextReminder == null
? AppColors.successText
: AppColors.textSecondary,
fontWeight: FontWeight.w700,
),
),
],
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _OverviewValue(
value: '$activeCount种',
label: '正在服用',
color: AppColors.textPrimary,
),
),
Container(width: 1, height: 46, color: AppColors.divider),
Expanded(
child: _OverviewValue(
value: '$doseCount次',
label: '今日安排',
color: AppColors.textPrimary,
),
),
],
),
],
),
);
}
}
class _OverviewValue extends StatelessWidget {
final String value;
final String label;
final Color color;
const _OverviewValue({
required this.value,
required this.label,
required this.color,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(value, style: AppTextStyles.summaryTitle.copyWith(color: color)),
const SizedBox(height: 2),
Text(label, style: AppTextStyles.listSubtitle.copyWith(fontSize: 13)),
],
);
}
}
class _MedicationPhaseGroup extends StatelessWidget {
final CarePlanPhase phase;
final List<Map<String, dynamic>> medications;
final Set<String> deleting;
final ValueChanged<String> onOpen;
final ValueChanged<String> onEdit;
final Future<void> Function(String, String) onDelete;
const _MedicationPhaseGroup({
required this.phase,
required this.medications,
required this.deleting,
required this.onOpen,
required this.onEdit,
required this.onDelete,
});
@override
Widget build(BuildContext context) {
final color = _phaseColor(phase);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 2, bottom: 9),
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
),
const SizedBox(width: 8),
Text(
'${_phaseLabel(phase)}${medications.length}',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
color: color,
),
),
],
),
),
Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
children: List.generate(medications.length, (index) {
final medication = medications[index];
final id = medication['id']?.toString() ?? '';
final name =
medication['name']?.toString().trim().isNotEmpty == true
? medication['name'].toString().trim()
: '未命名药品';
final isDeleting = deleting.contains(id);
return SwipeDeleteTile(
key: ValueKey(id),
margin: EdgeInsets.zero,
borderRadius: BorderRadius.zero,
enabled: !isDeleting,
onDelete: () => onDelete(id, name),
child: _MedicationRow(
medication: medication,
phase: phase,
deleting: isDeleting,
showDivider: index < medications.length - 1,
onOpen: () => onOpen(id),
onEdit: () => onEdit(id),
),
);
}),
),
),
],
);
}
}
class _MedicationRow extends StatelessWidget {
final Map<String, dynamic> medication;
final CarePlanPhase phase;
final bool deleting;
final bool showDivider;
final VoidCallback onOpen;
final VoidCallback onEdit;
const _MedicationRow({
required this.medication,
required this.phase,
required this.deleting,
required this.showDivider,
required this.onOpen,
required this.onEdit,
});
@override
Widget build(BuildContext context) {
final name = medication['name']?.toString() ?? '未命名药品';
final dosage = medication['dosage']?.toString().trim() ?? '';
final times =
(medication['timeOfDay'] as List?)
?.map((time) => _formatTime(time.toString()))
.join('') ??
'';
return InkWell(
onTap: deleting ? null : onOpen,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppTheme.sLg,
vertical: 13,
),
padding: const EdgeInsets.fromLTRB(16, 12, 6, 12),
child: Row(
children: [
Container(
width: 44,
height: 44,
width: 40,
height: 40,
decoration: BoxDecoration(
gradient: isActive
? visual.gradient
: AppColors.surfaceGradient,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.borderLight),
color: _phaseColor(phase).withValues(alpha: 0.10),
borderRadius: AppRadius.smBorder,
),
child: Icon(
visual.icon,
size: 25,
color: isActive ? Colors.white : AppTheme.textSub,
AppModuleVisuals.medication.icon,
color: _phaseColor(phase),
size: 22,
),
),
const SizedBox(width: AppTheme.sMd),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -252,45 +390,66 @@ class _MedicationRow extends StatelessWidget {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listTitle.copyWith(
color: isActive
? AppTheme.text
: AppTheme.textSub,
fontSize: 17,
),
),
),
if (!isActive) ...[
const SizedBox(width: 6),
AppStatusBadge(label: '已停', color: visual.color),
if (dosage.isNotEmpty) ...[
const SizedBox(width: 8),
Text(dosage, style: AppTextStyles.tag),
],
],
),
const SizedBox(height: 2),
const SizedBox(height: 3),
Text(
subtitle,
times.isEmpty ? '未设置服药时间' : times,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listSubtitle.copyWith(
color: AppTheme.textSub,
fontSize: 13,
),
),
const SizedBox(height: 2),
Text(
_periodText(medication),
style: AppTextStyles.listSubtitle.copyWith(
fontSize: 12,
),
),
],
),
),
const Icon(
Icons.chevron_right,
size: 21,
color: AppColors.textHint,
),
if (deleting)
const Padding(
padding: EdgeInsets.all(12),
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
)
else
IconButton(
tooltip: '编辑用药',
onPressed: onEdit,
icon: const Icon(
LucideIcons.pencil,
size: 21,
color: AppColors.textSecondary,
),
),
],
),
),
if (showDivider)
const Padding(
padding: EdgeInsets.only(left: 74),
const Positioned(
left: 68,
right: 0,
bottom: 0,
child: Divider(
height: 1,
thickness: 0.7,
color: Color(0xFFE8ECF2),
color: AppColors.divider,
),
),
],
@@ -298,3 +457,40 @@ class _MedicationRow extends StatelessWidget {
);
}
}
String? _nextReminder(List<Map<String, dynamic>> medications) {
final now = TimeOfDay.now();
final nowMinutes = now.hour * 60 + now.minute;
final times =
medications
.expand((item) => (item['timeOfDay'] as List?) ?? const [])
.map((value) => _formatTime(value.toString()))
.where((value) => value.length == 5)
.toList()
..sort();
for (final time in times) {
final parts = time.split(':');
final minutes =
(int.tryParse(parts[0]) ?? 0) * 60 + (int.tryParse(parts[1]) ?? 0);
if (minutes >= nowMinutes) return time;
}
return null;
}
String _periodText(Map<String, dynamic> medication) {
return formatMedicationPeriod(medication['startDate'], medication['endDate']);
}
String _formatTime(String raw) => raw.length >= 5 ? raw.substring(0, 5) : raw;
String _phaseLabel(CarePlanPhase phase) => switch (phase) {
CarePlanPhase.active => '正在服用',
CarePlanPhase.upcoming => '即将开始',
CarePlanPhase.ended => '已结束',
};
Color _phaseColor(CarePlanPhase phase) => switch (phase) {
CarePlanPhase.active => AppColors.successText,
CarePlanPhase.upcoming => AppColors.blueMeasure,
CarePlanPhase.ended => AppColors.textHint,
};

View File

@@ -0,0 +1,33 @@
String formatMedicationPeriod(
Object? startValue,
Object? endValue, {
DateTime? now,
}) {
final start = DateTime.tryParse(startValue?.toString() ?? '');
final end = DateTime.tryParse(endValue?.toString() ?? '');
if (start == null && end == null) return '长期';
final reference = now ?? DateTime.now();
if (start == null) return '-- - ${_compactMedicationDate(end!, reference)}';
final startText = _compactMedicationDate(start, reference, other: end);
if (end == null) return '$startText - 长期';
final endText = _compactMedicationDate(end, reference, other: start);
return '$startText - $endText';
}
String _compactMedicationDate(
DateTime date,
DateTime reference, {
DateTime? other,
}) {
final showYear =
date.year != reference.year || (other != null && other.year != date.year);
final month = date.month.toString().padLeft(2, '0');
final day = date.day.toString().padLeft(2, '0');
return showYear ? '${date.year}.$month.$day' : '$month.$day';
}
String formatMedicationFormDate(DateTime value) {
final month = value.month.toString().padLeft(2, '0');
final day = value.day.toString().padLeft(2, '0');
return '${value.year}-$month-$day';
}

View File

@@ -5,10 +5,27 @@ import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/data_providers.dart';
import '../../services/in_app_notification_service.dart';
import '../../widgets/app_empty_state.dart';
import '../../widgets/common_widgets.dart';
Future<bool> acknowledgeBeforeNotificationOpen({
required Future<void> Function() acknowledge,
VoidCallback? onAcknowledged,
required VoidCallback open,
}) async {
var acknowledged = true;
try {
await acknowledge();
onAcknowledged?.call();
} catch (_) {
acknowledged = false;
}
open();
return acknowledged;
}
class NotificationCenterPage extends ConsumerStatefulWidget {
const NotificationCenterPage({super.key});
@@ -61,24 +78,40 @@ class _NotificationCenterPageState
Future<void> _open(InAppNotification item) async {
if (!item.isRead) {
await _service.acknowledge(item.id);
if (!mounted) return;
setState(() {
final current = _history;
if (current == null) return;
_history = InAppNotificationHistory(
unreadCount: (current.unreadCount - 1).clamp(0, current.unreadCount),
items: current.items
.map(
(value) =>
value.id == item.id ? value.copyWith(isRead: true) : value,
)
.toList(),
);
});
ref.invalidate(notificationUnreadCountProvider);
await acknowledgeBeforeNotificationOpen(
acknowledge: () => _service.acknowledge(item.id),
onAcknowledged: () {
if (!mounted) return;
setState(() {
final current = _history;
if (current == null) return;
_history = InAppNotificationHistory(
unreadCount: (current.unreadCount - 1).clamp(
0,
current.unreadCount,
),
items: current.items
.map(
(value) => value.id == item.id
? value.copyWith(isRead: true)
: value,
)
.toList(),
);
});
ref.invalidate(notificationUnreadCountProvider);
},
open: () {
if (mounted) _openTarget(item);
},
);
return;
}
_openTarget(item);
}
void _openTarget(InAppNotification item) {
if (!mounted || item.actionType == null) return;
switch (item.actionType) {
case 'medication':
@@ -149,11 +182,11 @@ class _NotificationCenterPageState
final unread = _history?.unreadCount ?? 0;
return Scaffold(
backgroundColor: const Color(0xFFF6F8FC),
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
scrolledUnderElevation: 0.5,
scrolledUnderElevation: 0,
surfaceTintColor: Colors.transparent,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
@@ -194,10 +227,15 @@ class _NotificationCenterPageState
const SizedBox(width: 4),
],
),
body: RefreshIndicator(
onRefresh: _load,
color: AppColors.primary,
child: _buildBody(items, unread),
body: ColoredBox(
color: AppColors.background,
child: SizedBox.expand(
child: RefreshIndicator(
onRefresh: _load,
color: AppColors.primary,
child: _buildBody(items, unread),
),
),
),
);
}
@@ -319,13 +357,6 @@ class _NotificationGroup extends StatelessWidget {
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.xlBorder,
boxShadow: [
BoxShadow(
color: const Color(0xFF101828).withValues(alpha: 0.035),
blurRadius: 14,
offset: const Offset(0, 6),
),
],
),
child: Column(children: children),
);
@@ -339,27 +370,38 @@ class _UnreadHint extends StatelessWidget {
@override
Widget build(BuildContext context) => Container(
margin: const EdgeInsets.fromLTRB(0, 2, 0, 14),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
margin: const EdgeInsets.fromLTRB(0, 2, 0, 10),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
decoration: BoxDecoration(
color: AppColors.notificationLight,
color: Colors.white,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.notificationBorder),
),
child: Row(
children: [
const Icon(
LucideIcons.bellRing,
size: 18,
color: AppColors.notification,
size: 17,
color: AppColors.textSecondary,
),
const SizedBox(width: 9),
Text(
'你有 $unreadCount 条未读消息',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: AppColors.notification,
const SizedBox(width: 8),
RichText(
text: TextSpan(
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
children: [
const TextSpan(text: '还有 '),
TextSpan(
text: '$unreadCount',
style: const TextStyle(
fontWeight: FontWeight.w800,
color: AppColors.errorText,
),
),
const TextSpan(text: ' 条未读消息'),
],
),
),
],
@@ -465,27 +507,24 @@ class _NotificationRow extends StatelessWidget {
child: InkWell(
onTap: onTap,
child: Container(
constraints: const BoxConstraints(minHeight: 94),
constraints: const BoxConstraints(minHeight: 82),
color: Colors.white,
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(14, 13, 12, 12),
padding: const EdgeInsets.fromLTRB(14, 10, 10, 10),
child: Row(
children: [
Container(
width: 48,
height: 48,
width: 40,
height: 40,
decoration: BoxDecoration(
gradient: visual.gradient,
borderRadius: AppRadius.mdBorder,
border: Border.all(
color: visual.borderColor.withValues(alpha: 0.85),
),
color: visual.lightColor,
borderRadius: AppRadius.smBorder,
),
child: Icon(visual.icon, size: 24, color: Colors.white),
child: Icon(visual.icon, size: 21, color: visual.color),
),
const SizedBox(width: 13),
const SizedBox(width: 11),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -493,10 +532,26 @@ class _NotificationRow extends StatelessWidget {
children: [
Row(
children: [
Expanded(
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15,
fontWeight: item.isRead
? FontWeight.w700
: FontWeight.w800,
color: AppColors.textPrimary,
height: 1.2,
),
),
),
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 3,
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: visual.lightColor,
@@ -505,45 +560,22 @@ class _NotificationRow extends StatelessWidget {
child: Text(
visual.label,
style: TextStyle(
fontSize: 12,
fontSize: 11,
fontWeight: FontWeight.w800,
color: visual.color,
),
),
),
const SizedBox(width: 8),
Text(
_formatTime(item.createdAt),
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: AppColors.textHint,
),
),
],
),
const SizedBox(height: 5),
Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: item.isRead
? FontWeight.w700
: FontWeight.w800,
color: AppColors.textPrimary,
height: 1.2,
),
),
const SizedBox(height: 4),
Text(
item.message,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
height: 1.25,
fontSize: 13,
height: 1.2,
fontWeight: FontWeight.w500,
color: AppColors.textSecondary,
),
@@ -551,20 +583,36 @@ class _NotificationRow extends StatelessWidget {
],
),
),
const SizedBox(width: 10),
const SizedBox(width: 8),
SizedBox(
width: 12,
child: Center(
child: item.isRead
? const SizedBox.shrink()
: Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
color: AppColors.error,
shape: BoxShape.circle,
),
width: 68,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (item.isRead)
const SizedBox(height: 8)
else
Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
color: AppColors.error,
shape: BoxShape.circle,
),
),
const SizedBox(height: 7),
Text(
_formatTime(item.createdAt),
maxLines: 1,
textAlign: TextAlign.right,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: AppColors.textHint,
),
),
],
),
),
],
@@ -572,7 +620,7 @@ class _NotificationRow extends StatelessWidget {
),
if (showDivider)
const Padding(
padding: EdgeInsets.only(left: 75),
padding: EdgeInsets.only(left: 65),
child: Divider(
height: 1,
thickness: 0.7,
@@ -597,8 +645,8 @@ class _NotificationRow extends StatelessWidget {
local.day == now.day) {
return time;
}
if (local.year == now.year) return '${local.month}/${local.day} $time';
return '${local.year}/${local.month}/${local.day} $time';
if (local.year == now.year) return '${local.month}-${local.day} $time';
return '${local.year}-${local.month}-${local.day} $time';
}
}
@@ -606,26 +654,15 @@ class _NotificationVisual {
final IconData icon;
final Color color;
final Color lightColor;
final Color borderColor;
final LinearGradient gradient;
final String label;
const _NotificationVisual(
this.icon,
this.color,
this.lightColor,
this.borderColor,
this.gradient,
this.label,
);
const _NotificationVisual(this.icon, this.color, this.lightColor, this.label);
factory _NotificationVisual.fromModule(AppModuleVisual visual) {
return _NotificationVisual(
visual.icon,
visual.color,
visual.lightColor,
visual.borderColor,
visual.gradient,
visual.label,
);
}
@@ -639,14 +676,8 @@ class _NotificationVisual {
return item.severity == 'critical'
? const _NotificationVisual(
LucideIcons.triangleAlert,
Color(0xFFEF4444),
Color(0xFFFEE2E2),
Color(0xFFFECACA),
LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFFF7A7A), Color(0xFFEF4444)],
),
AppColors.errorText,
AppColors.errorLight,
'紧急',
)
: _NotificationVisual.fromModule(AppModuleVisuals.health);
@@ -654,14 +685,8 @@ class _NotificationVisual {
return item.severity == 'error'
? const _NotificationVisual(
LucideIcons.fileWarning,
Color(0xFFEF4444),
Color(0xFFFEE2E2),
Color(0xFFFECACA),
LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFFF7A7A), Color(0xFFEF4444)],
),
AppColors.errorText,
AppColors.errorLight,
'报告',
)
: _NotificationVisual.fromModule(AppModuleVisuals.report);
@@ -693,62 +718,23 @@ class _MessageState extends StatelessWidget {
@override
Widget build(BuildContext context) => ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(28, 120, 28, 32),
padding: const EdgeInsets.fromLTRB(28, 100, 28, 32),
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 36),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.borderLight),
boxShadow: [AppTheme.shadowLight],
),
child: Column(
children: [
Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: AppColors.primaryLight,
borderRadius: BorderRadius.circular(18),
),
child: Icon(icon, size: 32, color: AppColors.primary),
),
const SizedBox(height: 20),
Text(
title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 8),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
height: 1.5,
color: AppColors.textSecondary,
),
),
if (buttonText != null) ...[
const SizedBox(height: 22),
FilledButton(
onPressed: onPressed,
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
padding: const EdgeInsets.symmetric(
horizontal: 28,
vertical: 12,
),
AppEmptyState(
icon: icon,
iconColor: onPressed == null ? AppColors.notification : AppColors.error,
title: title,
subtitle: message,
padding: const EdgeInsets.all(24),
action: buttonText == null
? null
: SizedBox(
width: 140,
child: AppGradientOutlineButton(
label: buttonText!,
onPressed: onPressed,
),
child: Text(buttonText!),
),
],
],
),
),
],
);

View File

@@ -0,0 +1,278 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../providers/data_providers.dart';
import '../../widgets/app_error_state.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/common_widgets.dart';
class ProfileEditPage extends ConsumerStatefulWidget {
const ProfileEditPage({super.key});
@override
ConsumerState<ProfileEditPage> createState() => _ProfileEditPageState();
}
class _ProfileEditPageState extends ConsumerState<ProfileEditPage> {
final _nameController = TextEditingController();
bool _loading = true;
bool _saving = false;
String? _error;
String _gender = '';
DateTime? _birthDate;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
Future<void> _load() async {
try {
final profile = await ref.read(userServiceProvider).getProfile();
if (!mounted) return;
setState(() {
_nameController.text = profile?['name']?.toString() ?? '';
_gender = profile?['gender']?.toString() ?? '';
_birthDate = DateTime.tryParse(profile?['birthDate']?.toString() ?? '');
_loading = false;
_error = null;
});
} catch (_) {
if (!mounted) return;
setState(() {
_loading = false;
_error = '个人资料加载失败';
});
}
}
Future<void> _save() async {
final name = _nameController.text.trim();
if (name.isEmpty) {
AppToast.show(context, '请填写姓名', type: AppToastType.warning);
return;
}
setState(() => _saving = true);
try {
await ref
.read(userServiceProvider)
.updateProfile(
name: name,
gender: _gender.isEmpty ? null : _gender,
birthDate: _birthDate == null ? null : _formatDate(_birthDate!),
);
await ref.read(authProvider.notifier).refreshProfile();
if (!mounted) return;
AppToast.show(context, '个人资料已保存', type: AppToastType.success);
popRoute(ref);
} catch (_) {
if (mounted) {
AppToast.show(context, '保存失败,请稍后重试', type: AppToastType.error);
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
Future<void> _pickBirthDate() async {
final now = DateTime.now();
final selected = await showDatePicker(
context: context,
initialDate: _birthDate ?? DateTime(now.year - 30),
firstDate: DateTime(1900),
lastDate: now,
);
if (selected != null && mounted) setState(() => _birthDate = selected);
}
@override
Widget build(BuildContext context) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 19),
onPressed: _saving ? null : () => popRoute(ref),
),
title: const Text('基本资料'),
centerTitle: true,
),
bottomNavigationBar: _loading || _error != null
? null
: SafeArea(
minimum: const EdgeInsets.fromLTRB(18, 8, 18, 14),
child: AppGradientOutlineButton(
label: _saving ? '保存中...' : '保存',
loading: _saving,
onPressed: _saving ? null : _save,
),
),
body: _loading
? const Center(child: CircularProgressIndicator(strokeWidth: 2))
: _error != null
? AppErrorState(title: _error!, subtitle: '请检查网络后重试', onRetry: _load)
: ListView(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.fromLTRB(18, 12, 18, 28),
children: [
_FormPanel(
children: [
const _FieldLabel('姓名'),
const SizedBox(height: 8),
TextField(
controller: _nameController,
maxLength: 30,
textInputAction: TextInputAction.done,
decoration: const InputDecoration(
hintText: '请输入姓名',
counterText: '',
),
),
const SizedBox(height: 18),
const _FieldLabel('性别'),
const SizedBox(height: 8),
SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'Male', label: Text('')),
ButtonSegment(value: 'Female', label: Text('')),
ButtonSegment(value: 'Other', label: Text('其他')),
],
selected: _gender.isEmpty ? const {} : {_gender},
emptySelectionAllowed: true,
showSelectedIcon: false,
onSelectionChanged: (value) {
setState(
() => _gender = value.isEmpty ? '' : value.first,
);
},
),
const SizedBox(height: 18),
const _FieldLabel('出生日期'),
const SizedBox(height: 8),
InkWell(
onTap: _pickBirthDate,
borderRadius: AppRadius.mdBorder,
child: Container(
height: 52,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(
border: Border.all(color: AppColors.border),
borderRadius: AppRadius.mdBorder,
),
child: Row(
children: [
Expanded(
child: Text(
_birthDate == null
? '请选择出生日期'
: _formatDate(_birthDate!),
style: TextStyle(
fontSize: 15,
color: _birthDate == null
? AppColors.textHint
: AppColors.textPrimary,
),
),
),
const Icon(
Icons.calendar_today_outlined,
size: 19,
color: AppColors.primary,
),
],
),
),
),
],
),
const SizedBox(height: 16),
_ReadOnlyPhone(phone: ref.read(authProvider).user?.phone ?? ''),
],
),
);
}
String _formatDate(DateTime value) =>
'${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
}
class _FormPanel extends StatelessWidget {
final List<Widget> children;
const _FormPanel({required this.children});
@override
Widget build(BuildContext context) => Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
),
);
}
class _FieldLabel extends StatelessWidget {
final String text;
const _FieldLabel(this.text);
@override
Widget build(BuildContext context) => Text(
text,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
);
}
class _ReadOnlyPhone extends StatelessWidget {
final String phone;
const _ReadOnlyPhone({required this.phone});
@override
Widget build(BuildContext context) => Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Row(
children: [
const Icon(Icons.phone_iphone_rounded, color: AppColors.textSecondary),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('手机号', style: AppTextStyles.listTitle),
const SizedBox(height: 4),
Text(
phone.isEmpty ? '未绑定' : phone,
style: AppTextStyles.listSubtitle,
),
],
),
),
const Text(
'手机号不可修改',
style: TextStyle(fontSize: 12, color: AppColors.textHint),
),
],
),
);
}

View File

@@ -13,10 +13,11 @@ class ProfilePage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final auth = ref.watch(authProvider);
final user = auth.user;
final name = user?.name?.isNotEmpty == true ? user!.name! : '未设置昵称';
final phone = user?.phone ?? '';
final user = ref.watch(authProvider.select((state) => state.user));
final name = user?.name?.trim().isNotEmpty == true ? user!.name! : '未设置昵称';
final phone = user?.phone.trim().isNotEmpty == true
? user!.phone
: '未绑定手机号';
return GradientScaffold(
appBar: AppBar(
@@ -29,23 +30,48 @@ class ProfilePage extends ConsumerWidget {
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.fromLTRB(18, 16, 18, 32),
padding: const EdgeInsets.fromLTRB(18, 12, 18, 32),
children: [
_AccountCard(
_AccountSummary(
name: name,
phone: phone.isNotEmpty ? phone : '未绑定手机号',
phone: phone,
avatarUrl: user?.avatarUrl,
),
const SizedBox(height: 14),
_ActionTile(
icon: AppModuleVisuals.health.icon,
title: '健康档案',
subtitle: '维护个人资料、病史、手术和过敏信息',
visual: AppModuleVisuals.health,
onTap: () => pushRoute(ref, 'healthArchive'),
const SizedBox(height: 20),
const _SectionTitle('资料管理'),
const SizedBox(height: 9),
_SettingsGroup(
children: [
_ActionRow(
icon: Icons.badge_outlined,
iconColor: AppColors.primary,
title: '基本资料',
subtitle: '姓名、性别和出生日期',
onTap: () => pushRoute(ref, 'profileEdit'),
),
_ActionRow(
icon: AppModuleVisuals.health.icon,
iconColor: AppModuleVisuals.health.color,
title: '健康档案',
subtitle: '疾病、手术、过敏和生活习惯',
onTap: () => pushRoute(ref, 'healthArchive'),
),
],
),
const SizedBox(height: 20),
const _SectionTitle('账号操作'),
const SizedBox(height: 9),
_SettingsGroup(
children: [
_ActionRow(
icon: Icons.logout_rounded,
iconColor: AppColors.textSecondary,
title: '退出登录',
showChevron: false,
onTap: () => _logout(context, ref),
),
],
),
const SizedBox(height: 14),
_LogoutButton(onPressed: () => _logout(context, ref)),
],
),
),
@@ -53,37 +79,37 @@ class ProfilePage extends ConsumerWidget {
}
Future<void> _logout(BuildContext context, WidgetRef ref) async {
final ok = await showDialog<bool>(
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
builder: (dialogContext) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: AppRadius.lgBorder),
title: const Text('退出登录'),
content: const Text('确定退出当前账号?'),
content: const Text('确定退出当前账号'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
child: const Text('确定', style: TextStyle(color: AppColors.error)),
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('退出'),
),
],
),
);
if (ok == true) {
await ref.read(authProvider.notifier).logout();
goRoute(ref, 'login');
}
if (confirmed != true || !context.mounted) return;
await ref.read(authProvider.notifier).logout();
goRoute(ref, 'login');
}
}
class _AccountCard extends StatelessWidget {
class _AccountSummary extends StatelessWidget {
final String name;
final String phone;
final String? avatarUrl;
const _AccountCard({
const _AccountSummary({
required this.name,
required this.phone,
required this.avatarUrl,
@@ -91,17 +117,31 @@ class _AccountCard extends StatelessWidget {
@override
Widget build(BuildContext context) => Container(
padding: AppSpacing.panel,
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
border: Border.all(color: AppColors.border, width: 1.1),
boxShadow: AppShadows.soft,
),
child: Row(
children: [
_Avatar(avatarUrl: avatarUrl),
const SizedBox(width: 14),
Container(
width: 60,
height: 60,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: AppModuleVisuals.health.lightColor,
borderRadius: AppRadius.lgBorder,
),
child: avatarUrl?.isNotEmpty == true
? Image.network(
avatarUrl!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) =>
const _AvatarFallback(),
)
: const _AvatarFallback(),
),
const SizedBox(width: 15),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -113,11 +153,11 @@ class _AccountCard extends StatelessWidget {
style: AppTextStyles.summaryTitle.copyWith(fontSize: 20),
),
const SizedBox(height: 5),
Text(
phone,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listSubtitle,
Text(phone, style: AppTextStyles.listSubtitle),
const SizedBox(height: 5),
const Text(
'头像由账号系统统一管理',
style: TextStyle(fontSize: 12, color: AppColors.textHint),
),
],
),
@@ -127,103 +167,124 @@ class _AccountCard extends StatelessWidget {
);
}
class _Avatar extends StatelessWidget {
final String? avatarUrl;
const _Avatar({required this.avatarUrl});
class _AvatarFallback extends StatelessWidget {
const _AvatarFallback();
@override
Widget build(BuildContext context) => Container(
width: 58,
height: 58,
decoration: BoxDecoration(
gradient: AppModuleVisuals.health.gradient,
borderRadius: AppRadius.lgBorder,
),
clipBehavior: Clip.antiAlias,
child: avatarUrl != null && avatarUrl!.isNotEmpty
? Image.network(avatarUrl!, fit: BoxFit.cover)
: const Icon(Icons.person_rounded, color: Colors.white, size: 34),
Widget build(BuildContext context) => Icon(
Icons.person_rounded,
color: AppModuleVisuals.health.color,
size: 34,
);
}
class _ActionTile extends StatelessWidget {
class _SectionTitle extends StatelessWidget {
final String text;
const _SectionTitle(this.text);
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: Text(
text,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: AppColors.textSecondary,
),
),
);
}
class _SettingsGroup extends StatelessWidget {
final List<Widget> children;
const _SettingsGroup({required this.children});
@override
Widget build(BuildContext context) => Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
),
child: Column(
children: [
for (var i = 0; i < children.length; i++) ...[
children[i],
if (i != children.length - 1)
const Padding(
padding: EdgeInsets.only(left: 62),
child: Divider(height: 1, color: AppColors.borderLight),
),
],
],
),
);
}
class _ActionRow extends StatelessWidget {
final IconData icon;
final Color iconColor;
final String title;
final String subtitle;
final AppModuleVisual visual;
final String? subtitle;
final bool showChevron;
final VoidCallback onTap;
const _ActionTile({
const _ActionRow({
required this.icon,
required this.iconColor,
required this.title,
required this.subtitle,
required this.visual,
this.subtitle,
this.showChevron = true,
required this.onTap,
});
@override
Widget build(BuildContext context) => Material(
color: Colors.white,
borderRadius: AppRadius.lgBorder,
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.lgBorder,
child: Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: AppRadius.lgBorder,
border: Border.all(color: AppColors.border, width: 1.1),
boxShadow: AppShadows.soft,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 14),
child: Row(
children: [
Container(
width: 46,
height: 46,
width: 36,
height: 36,
decoration: BoxDecoration(
gradient: visual.gradient,
borderRadius: AppRadius.mdBorder,
color: iconColor.withValues(alpha: 0.10),
borderRadius: AppRadius.smBorder,
),
child: Icon(icon, color: Colors.white, size: 24),
child: Icon(icon, color: iconColor, size: 20),
),
const SizedBox(width: 13),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: AppTextStyles.listTitle),
const SizedBox(height: 4),
Text(
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTextStyles.listSubtitle,
title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
color: AppColors.textPrimary,
),
),
if (subtitle != null) ...[
const SizedBox(height: 3),
Text(subtitle!, style: AppTextStyles.listSubtitle),
],
],
),
),
const Icon(Icons.chevron_right_rounded, color: AppColors.textHint),
if (showChevron)
const Icon(
Icons.chevron_right_rounded,
color: AppColors.textHint,
),
],
),
),
),
);
}
class _LogoutButton extends StatelessWidget {
final VoidCallback onPressed;
const _LogoutButton({required this.onPressed});
@override
Widget build(BuildContext context) => TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
foregroundColor: AppColors.error,
padding: const EdgeInsets.symmetric(vertical: 14),
textStyle: AppTextStyles.button,
),
child: const Text('退出登录'),
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_theme.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/navigation_provider.dart';
import '../../widgets/ai_content.dart';
import '../../widgets/app_error_state.dart';
import '../../widgets/common_widgets.dart';
import 'report_pages.dart';
/// AI 解读页:从服务器获取真实报告数据
@@ -26,14 +29,18 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
@override
Widget build(BuildContext context) {
final analysis = ref.watch(reportProvider.select((s) => s.currentAnalysis));
final reports = ref.watch(reportProvider.select((s) => s.reports));
final reportState = ref.watch(reportProvider);
final analysis = reportState.currentAnalysis;
final reports = reportState.reports;
final reportItem = reports.where((r) => r.id == widget.id).firstOrNull;
if (analysis == null) {
if (reportState.isLoadingDetail) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.arrow_back), onPressed: () => popRoute(ref)),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: const Text('报告解读'),
),
body: const Center(
@@ -42,10 +49,30 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
);
}
if (analysis == null) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: const Text('报告解读'),
),
body: AppErrorState(
title: '报告详情加载失败',
subtitle: reportState.detailError ?? '暂时无法读取这份报告',
onRetry: () =>
ref.read(reportProvider.notifier).fetchReportDetail(widget.id),
),
);
}
final displayType = _displayName(analysis.reportType);
final aiStatus = reportItem?.aiStatus ?? analysis.aiStatus;
final reviewStatus = reportItem?.reviewStatus ?? analysis.reviewStatus;
final fileUrl = reportItem?.fileUrl ?? analysis.fileUrl;
final fileType = reportItem?.type ?? analysis.fileType;
final isPdf = isPdfReport(fileType, fileUrl ?? '');
final isReviewed = reviewStatus == 'Reviewed';
final isAnalyzing = aiStatus == 'Analyzing';
final isFailed = aiStatus == 'Failed';
@@ -73,6 +100,10 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (reportState.detailError != null) ...[
_detailErrorBanner(reportState.detailError!),
const SizedBox(height: 12),
],
if (fileUrl != null && fileUrl.isNotEmpty) ...[
SizedBox(
width: double.infinity,
@@ -80,16 +111,26 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
onPressed: () => pushRoute(
ref,
'reportOriginal',
params: {'url': fileUrl, 'title': displayType},
params: {
'url': fileUrl,
'title': displayType,
'fileType': fileType,
},
),
icon: Icon(
isPdf
? Icons.picture_as_pdf_outlined
: Icons.image_outlined,
size: 18,
),
icon: const Icon(Icons.image_outlined, size: 18),
label: const Text('查看原始报告'),
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.primary,
side: const BorderSide(color: AppColors.primaryLight),
foregroundColor: AppColors.textPrimary,
backgroundColor: Colors.white,
side: const BorderSide(color: AppColors.border),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
borderRadius: AppRadius.mdBorder,
),
),
),
@@ -99,17 +140,26 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
if (isAnalyzing || isFailed) ...[
_analysisStateCard(
isFailed
? (analysis.summary.isNotEmpty ? analysis.summary : 'AI 分析失败,请重新上传或稍后重试')
: 'AI 正在分析报告,请稍后刷新查看',
? (analysis.summary.isNotEmpty
? analysis.summary
: 'AI 分析失败,请重新上传或稍后重试')
: (reportState.pollingTimedOut
? '分析时间比预期更长,您可以稍后返回此页查看'
: 'AI 正在分析报告,请稍后刷新查看'),
isFailed: isFailed,
busy: reportState.reanalyzingReportId == widget.id,
onRetry: isFailed
? () => ref.read(reportProvider.notifier).reanalyzeReport(widget.id)
? () => ref
.read(reportProvider.notifier)
.reanalyzeReport(widget.id)
: null,
),
const SizedBox(height: 20),
],
// 指标分析
if (!isAnalyzing && !isFailed && analysis.indicators.isNotEmpty) ...[
if (!isAnalyzing &&
!isFailed &&
analysis.indicators.isNotEmpty) ...[
_sectionTitle('指标分析'),
const SizedBox(height: 8),
Container(
@@ -147,8 +197,8 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
// 医生审核意见
_sectionTitle('医生审核意见'),
const SizedBox(height: 8),
if (isReviewed)
_doctorReviewCard(reportItem!)
if (isReviewed && reportItem != null)
_doctorReviewCard(reportItem)
else
Container(
padding: const EdgeInsets.all(16),
@@ -171,7 +221,10 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
Spacer(),
Text(
'AI 预解读',
style: TextStyle(fontSize: 14, color: AppColors.textHint),
style: TextStyle(
fontSize: 14,
color: AppColors.textHint,
),
),
],
),
@@ -184,19 +237,16 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
);
}
BoxDecoration _cardDeco() => BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.border),
boxShadow: AppColors.cardShadowLight,
);
BoxDecoration _cardDeco() =>
BoxDecoration(color: Colors.white, borderRadius: AppRadius.lgBorder);
Widget _analysisStateCard(
String message, {
required bool isFailed,
bool busy = false,
VoidCallback? onRetry,
}) {
final color = isFailed ? AppColors.error : AppColors.primary;
final color = isFailed ? AppColors.errorText : AppColors.primary;
return Container(
padding: const EdgeInsets.all(16),
decoration: _cardDeco(),
@@ -217,7 +267,9 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
style: TextStyle(
fontSize: 16,
height: 1.6,
color: isFailed ? AppColors.error : AppColors.textPrimary,
color: isFailed
? AppColors.errorText
: AppColors.textPrimary,
fontWeight: FontWeight.w600,
),
),
@@ -228,18 +280,10 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
const SizedBox(height: 14),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: onRetry,
icon: const Icon(Icons.refresh, size: 18),
label: const Text('重新分析'),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primary,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: AppGradientOutlineButton(
label: busy ? '正在重新分析...' : '重新分析',
loading: busy,
onPressed: busy ? null : onRetry,
),
),
],
@@ -248,6 +292,32 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
);
}
Widget _detailErrorBanner(String message) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.errorLight,
borderRadius: AppRadius.mdBorder,
),
child: Row(
children: [
const Icon(Icons.error_outline, color: AppColors.errorText, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
message,
style: const TextStyle(
color: AppColors.errorText,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
],
),
);
}
Widget _sectionTitle(String text) => Row(
children: [
Container(
@@ -272,9 +342,9 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
Widget _indicatorRow(Indicator ind) {
final (color, icon) = switch (ind.status) {
'high' => (AppColors.error, Icons.arrow_upward),
'low' => (AppColors.warning, Icons.arrow_downward),
_ => (AppColors.success, Icons.check_circle),
'high' => (AppColors.errorText, Icons.arrow_upward),
'low' => (AppColors.warningText, Icons.arrow_downward),
_ => (AppColors.successText, Icons.check_circle),
};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
@@ -341,7 +411,7 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.cardInner,
borderRadius: BorderRadius.circular(12),
borderRadius: AppRadius.mdBorder,
),
child: Text(
report.doctorComment!,
@@ -360,7 +430,7 @@ class _AiAnalysisPageState extends ConsumerState<AiAnalysisPage> {
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.cardInner,
borderRadius: BorderRadius.circular(12),
borderRadius: AppRadius.mdBorder,
),
child: Text(
report.doctorRecommendation!,

View File

@@ -6,15 +6,22 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/app_colors.dart';
import '../../core/app_design_tokens.dart';
import '../../core/app_module_visuals.dart';
import '../../core/app_theme.dart';
import '../../core/api_client.dart' show baseUrl;
import '../../core/api_client.dart' show ApiException, baseUrl;
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';
import '../../widgets/common_widgets.dart';
import '../../widgets/enterprise_widgets.dart';
import '../../widgets/app_error_state.dart';
import '../../widgets/app_empty_state.dart';
import '../../widgets/app_toast.dart';
const _reportPageColor = AppColors.report;
const _reportPageSoft = Color(0xFFF0F0FF);
final reportProvider = NotifierProvider<ReportNotifier, ReportState>(
ReportNotifier.new,
@@ -27,12 +34,25 @@ Duration? reportAnalysisPollDelay(int attempt) {
return const Duration(seconds: 12);
}
bool isPdfReport(String fileType, String url) {
return fileType.toLowerCase() == 'pdf' ||
Uri.tryParse(url)?.path.toLowerCase().endsWith('.pdf') == true;
}
class ReportState {
final List<ReportItem> reports;
final String? uploadingImage;
final bool isAnalyzing;
final ReportAnalysis? currentAnalysis;
final String? uploadError;
final bool isLoadingReports;
final bool isRefreshingReports;
final String? reportsError;
final String? deletingReportId;
final bool isLoadingDetail;
final String? detailError;
final String? reanalyzingReportId;
final bool pollingTimedOut;
ReportState({
this.reports = const [],
@@ -40,6 +60,14 @@ class ReportState {
this.isAnalyzing = false,
this.currentAnalysis,
this.uploadError,
this.isLoadingReports = true,
this.isRefreshingReports = false,
this.reportsError,
this.deletingReportId,
this.isLoadingDetail = false,
this.detailError,
this.reanalyzingReportId,
this.pollingTimedOut = false,
});
ReportState copyWith({
@@ -48,9 +76,21 @@ class ReportState {
bool? isAnalyzing,
ReportAnalysis? currentAnalysis,
String? uploadError,
bool? isLoadingReports,
bool? isRefreshingReports,
String? reportsError,
String? deletingReportId,
bool? isLoadingDetail,
String? detailError,
String? reanalyzingReportId,
bool? pollingTimedOut,
bool clearUploadingImage = false,
bool clearCurrentAnalysis = false,
bool clearUploadError = false,
bool clearReportsError = false,
bool clearDeletingReportId = false,
bool clearDetailError = false,
bool clearReanalyzingReportId = false,
}) {
return ReportState(
reports: reports ?? this.reports,
@@ -62,6 +102,20 @@ class ReportState {
? null
: currentAnalysis ?? this.currentAnalysis,
uploadError: clearUploadError ? null : uploadError ?? this.uploadError,
isLoadingReports: isLoadingReports ?? this.isLoadingReports,
isRefreshingReports: isRefreshingReports ?? this.isRefreshingReports,
reportsError: clearReportsError
? null
: reportsError ?? this.reportsError,
deletingReportId: clearDeletingReportId
? null
: deletingReportId ?? this.deletingReportId,
isLoadingDetail: isLoadingDetail ?? this.isLoadingDetail,
detailError: clearDetailError ? null : detailError ?? this.detailError,
reanalyzingReportId: clearReanalyzingReportId
? null
: reanalyzingReportId ?? this.reanalyzingReportId,
pollingTimedOut: pollingTimedOut ?? this.pollingTimedOut,
);
}
}
@@ -111,6 +165,7 @@ class ReportAnalysis {
final String aiStatus;
final String reviewStatus;
final String? fileUrl;
final String fileType;
ReportAnalysis({
required this.reportId,
@@ -121,6 +176,7 @@ class ReportAnalysis {
this.aiStatus = 'Analyzing',
this.reviewStatus = 'Pending',
this.fileUrl,
this.fileType = 'Image',
});
}
@@ -151,7 +207,19 @@ class ReportNotifier extends Notifier<ReportState> {
return ReportState();
}
Future<void> loadReports() async {
Future<void> loadReports({bool refresh = false}) async {
if (refresh) {
_pollTimer?.cancel();
_pollTimer = null;
_pollAttempt = 0;
}
final initialLoad = state.reports.isEmpty && !refresh;
state = state.copyWith(
isLoadingReports: initialLoad,
isRefreshingReports: !initialLoad,
clearReportsError: true,
pollingTimedOut: refresh ? false : state.pollingTimedOut,
);
try {
final api = ref.read(apiClientProvider);
final res = await api.get('/api/reports');
@@ -184,10 +252,20 @@ class ReportNotifier extends Notifier<ReportState> {
reviewedAt: DateTime.tryParse(m['reviewedAt']?.toString() ?? ''),
);
}).toList();
state = state.copyWith(reports: reports);
state = state.copyWith(
reports: reports,
isLoadingReports: false,
isRefreshingReports: false,
clearReportsError: true,
);
_syncAnalysisPolling(reports);
} catch (e) {
debugPrint('[Report] 加载报告列表失败: $e');
state = state.copyWith(
isLoadingReports: false,
isRefreshingReports: false,
reportsError: _errorMessage(e, '报告加载失败,请检查网络后重试'),
);
}
}
@@ -197,24 +275,40 @@ class ReportNotifier extends Notifier<ReportState> {
_pollTimer?.cancel();
_pollTimer = null;
_pollAttempt = 0;
if (state.pollingTimedOut) {
state = state.copyWith(pollingTimedOut: false);
}
return;
}
if (_pollTimer != null) return;
final delay = reportAnalysisPollDelay(++_pollAttempt);
if (delay == null) return;
if (delay == null) {
if (!state.pollingTimedOut) {
state = state.copyWith(pollingTimedOut: true);
}
return;
}
_pollTimer = Timer(delay, () {
_pollTimer = null;
loadReports();
});
}
void fetchReportDetail(String reportId) async {
Future<void> fetchReportDetail(String reportId) async {
state = state.copyWith(
isLoadingDetail: true,
clearCurrentAnalysis: true,
clearDetailError: true,
);
try {
final api = ref.read(apiClientProvider);
final res = await api.get('/api/reports/$reportId');
final m = (res.data['data'] as Map<String, dynamic>?) ?? {};
if (m.isEmpty) {
state = state.copyWith(currentAnalysis: _emptyAnalysis(reportId));
state = state.copyWith(
isLoadingDetail: false,
detailError: '没有找到这份报告,请返回后刷新列表',
);
return;
}
final indicators = _parseIndicators(m['aiIndicators']?.toString());
@@ -232,23 +326,21 @@ class ReportNotifier extends Notifier<ReportState> {
aiStatus: m['aiStatus']?.toString() ?? _deriveAiStatus(m),
reviewStatus: m['reviewStatus']?.toString() ?? _deriveReviewStatus(m),
fileUrl: m['fileUrl']?.toString(),
fileType: m['fileType']?.toString() ?? 'Image',
);
state = state.copyWith(
currentAnalysis: analysis,
isLoadingDetail: false,
clearDetailError: true,
);
} catch (e) {
state = state.copyWith(
isLoadingDetail: false,
detailError: _errorMessage(e, '报告详情加载失败,请稍后重试'),
);
state = state.copyWith(currentAnalysis: analysis);
} catch (_) {
state = state.copyWith(currentAnalysis: _emptyAnalysis(reportId));
}
}
ReportAnalysis _emptyAnalysis(String reportId) => ReportAnalysis(
reportId: reportId,
reportType: '检查报告',
indicators: [],
summary: '暂无数据,请下拉刷新重试',
status: 'AnalysisFailed',
aiStatus: 'Failed',
reviewStatus: 'Pending',
);
String _deriveAiStatus(Map<String, dynamic> m) {
final status = m['status']?.toString();
if (status == 'Analyzing') return 'Analyzing';
@@ -278,7 +370,7 @@ class ReportNotifier extends Notifier<ReportState> {
}
}
void uploadImage(String path) async {
Future<void> uploadImage(String path) async {
state = state.copyWith(
uploadingImage: path,
isAnalyzing: true,
@@ -310,7 +402,7 @@ class ReportNotifier extends Notifier<ReportState> {
clearUploadingImage: true,
clearUploadError: true,
);
loadReports();
await loadReports();
} catch (e) {
debugPrint('[Report] 上传失败: $e');
state = state.copyWith(
@@ -321,63 +413,138 @@ class ReportNotifier extends Notifier<ReportState> {
}
}
void uploadFile(String path) => uploadImage(path);
Future<void> uploadFile(String path) => uploadImage(path);
void viewAnalysis(String reportId) {
fetchReportDetail(reportId);
}
Future<void> deleteReport(String id) async {
if (id.isEmpty || state.deletingReportId != null) return;
state = state.copyWith(deletingReportId: id);
try {
await ref.read(apiClientProvider).delete('/api/reports/$id');
loadReports();
final remaining = state.reports
.where((report) => report.id != id)
.toList();
state = state.copyWith(reports: remaining, clearDeletingReportId: true);
_syncAnalysisPolling(remaining);
} catch (e) {
debugPrint('[Report] 删除失败: $e');
state = state.copyWith(clearDeletingReportId: true);
throw Exception(_errorMessage(e, '删除失败,请稍后重试'));
}
}
Future<void> reanalyzeReport(String id) async {
if (state.reanalyzingReportId != null) return;
state = state.copyWith(reanalyzingReportId: id, clearDetailError: true);
try {
final res = await ref
.read(apiClientProvider)
.post('/api/reports/$id/reanalyze');
final data = res.data;
if (data is Map && data['code'] != 0) {
state = state.copyWith(
uploadError: data['message']?.toString() ?? '重新分析失败',
);
return;
throw Exception(data['message']?.toString() ?? '重新分析失败');
}
state = state.copyWith(
clearCurrentAnalysis: true,
clearUploadError: true,
);
await loadReports();
fetchReportDetail(id);
await fetchReportDetail(id);
} catch (e) {
debugPrint('[Report] 重新分析失败: $e');
state = state.copyWith(uploadError: '重新分析失败,请稍后重试');
state = state.copyWith(detailError: _errorMessage(e, '重新分析失败,请稍后重试'));
} finally {
state = state.copyWith(clearReanalyzingReportId: true);
}
}
void clearAnalysis() {
state = state.copyWith(clearCurrentAnalysis: true);
state = state.copyWith(
clearCurrentAnalysis: true,
clearDetailError: true,
isLoadingDetail: false,
);
}
String _errorMessage(Object error, String fallback) {
if (error is ApiException && error.message.trim().isNotEmpty) {
return error.message;
}
final raw = error.toString().replaceFirst('Exception: ', '').trim();
return raw.isEmpty ? fallback : raw;
}
}
/// 报告列表页
class ReportListPage extends ConsumerWidget {
const ReportListPage({super.key});
class ReportListPage extends ConsumerStatefulWidget {
final bool openUploadOnEnter;
static const _reportVisual = AppModuleVisuals.report;
static const _reportBlue = AppColors.report;
static const _reportCyan = Color(0xFF60A5FA);
const ReportListPage({super.key, this.openUploadOnEnter = false});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<ReportListPage> createState() => _ReportListPageState();
}
class _ReportListPageState extends ConsumerState<ReportListPage> {
static const _reportVisual = AppModuleVisuals.report;
static const _reportBlue = _reportPageColor;
static const _reportAccent = _reportPageColor;
@override
void initState() {
super.initState();
if (widget.openUploadOnEnter) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _showUploadOptions(context, ref);
});
}
}
Future<void> _confirmDelete(ReportItem report) async {
if (ref.read(reportProvider).deletingReportId != null) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('删除报告'),
content: Text('确定删除“${report.title}”吗?删除后无法恢复。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(foregroundColor: AppColors.errorText),
child: const Text('删除'),
),
],
),
);
if (confirmed != true || !mounted) return;
try {
await ref.read(reportProvider.notifier).deleteReport(report.id);
if (mounted) {
AppToast.show(context, '报告已删除', type: AppToastType.success);
}
} catch (error) {
if (mounted) {
AppToast.show(
context,
error.toString().replaceFirst('Exception: ', ''),
type: AppToastType.error,
);
}
}
}
@override
Widget build(BuildContext context) {
final state = ref.watch(reportProvider);
if (state.isAnalyzing) {
if (state.isLoadingReports && state.reports.isEmpty) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
@@ -386,21 +553,25 @@ class ReportListPage extends ConsumerWidget {
),
title: const Text('报告管理'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(color: _reportBlue),
const SizedBox(height: 16),
Text(
state.uploadingImage == null ? 'AI 正在分析报告...' : '正在上传报告...',
style: const TextStyle(
fontSize: 16,
color: AppColors.textSecondary,
),
),
],
body: const Center(
child: CircularProgressIndicator(color: _reportBlue),
),
);
}
if (state.reportsError != null && state.reports.isEmpty) {
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: const Text('报告管理'),
),
body: AppErrorState(
title: '报告加载失败',
subtitle: state.reportsError,
onRetry: () => ref.read(reportProvider.notifier).loadReports(),
),
);
}
@@ -416,32 +587,62 @@ class ReportListPage extends ConsumerWidget {
),
floatingActionButton: _buildUploadButton(context, ref),
body: RefreshIndicator(
onRefresh: () async => ref.read(reportProvider.notifier).loadReports(),
onRefresh: () =>
ref.read(reportProvider.notifier).loadReports(refresh: true),
child: ListView(
padding: const EdgeInsets.all(16),
children: [
if (state.isRefreshingReports) ...[
const LinearProgressIndicator(
minHeight: 2,
color: _reportBlue,
backgroundColor: Colors.transparent,
),
const SizedBox(height: 10),
],
EnterpriseHeader(
title: '报告处理概览',
subtitle: '上传检查报告后自动进行 AI 结构化解读',
icon: _reportVisual.icon,
color: _reportBlue,
accent: _reportCyan,
accent: _reportAccent,
showIcon: false,
stats: [
EnterpriseStat(
label: '报告总数',
value: '${state.reports.length}',
icon: Icons.folder_copy_outlined,
),
EnterpriseStat(
label: '待处理',
label: 'AI 分析中',
value:
'${state.reports.where((r) => r.aiStatus == 'Analyzing' || r.reviewStatus != 'Reviewed').length}',
icon: Icons.pending_actions_outlined,
'${state.reports.where((r) => r.aiStatus == 'Analyzing').length}',
),
EnterpriseStat(
label: '待医生审核',
value:
'${state.reports.where((r) => r.reviewStatus != 'Reviewed').length}',
),
],
),
const SizedBox(height: 10),
if (state.isAnalyzing) ...[
_buildInfoBanner(
state.uploadingImage == null ? '报告已上传AI 正在分析' : '正在上传报告,请稍候',
Icons.cloud_upload_outlined,
),
const SizedBox(height: 12),
],
if (state.pollingTimedOut) ...[
_buildInfoBanner(
'分析时间比预期更长,可稍后下拉刷新查看结果',
Icons.schedule_outlined,
),
const SizedBox(height: 12),
],
if (state.reportsError != null) ...[
_buildUploadError(state.reportsError!),
const SizedBox(height: 12),
],
if (state.uploadError != null) ...[
_buildUploadError(state.uploadError!),
const SizedBox(height: 12),
@@ -454,18 +655,19 @@ class ReportListPage extends ConsumerWidget {
for (var i = 0; i < state.reports.length; i++)
SwipeDeleteTile(
key: Key(state.reports[i].id),
onDelete: () => ref
.read(reportProvider.notifier)
.deleteReport(state.reports[i].id),
onDelete: () => _confirmDelete(state.reports[i]),
onTap: () => pushRoute(
ref,
'aiAnalysis',
params: {'id': state.reports[i].id},
),
margin: EdgeInsets.zero,
borderRadius: BorderRadius.zero,
enabled: state.deletingReportId == null,
child: _buildReportRow(
state.reports[i],
showDivider: i < state.reports.length - 1,
deleting: state.deletingReportId == state.reports[i].id,
),
),
],
@@ -480,20 +682,46 @@ class ReportListPage extends ConsumerWidget {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.error.withValues(alpha: 0.08),
color: AppColors.errorLight,
borderRadius: AppRadius.mdBorder,
border: Border.all(color: AppColors.error.withValues(alpha: 0.22)),
border: Border.all(color: AppColors.errorText.withValues(alpha: 0.18)),
),
child: Row(
children: [
const Icon(Icons.error_outline, color: AppColors.error, size: 20),
const Icon(Icons.error_outline, color: AppColors.errorText, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
message,
style: const TextStyle(
fontSize: 14,
color: AppColors.error,
color: AppColors.errorText,
fontWeight: FontWeight.w600,
),
),
),
],
),
);
}
Widget _buildInfoBanner(String message, IconData icon) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _reportBlue.withValues(alpha: 0.07),
borderRadius: AppRadius.mdBorder,
),
child: Row(
children: [
Icon(icon, color: _reportBlue, size: 20),
const SizedBox(width: 9),
Expanded(
child: Text(
message,
style: const TextStyle(
fontSize: 14,
color: AppColors.textPrimary,
fontWeight: FontWeight.w600,
),
),
@@ -504,11 +732,9 @@ class ReportListPage extends ConsumerWidget {
}
Widget _buildUploadButton(BuildContext context, WidgetRef ref) {
return FloatingActionButton(
return AppCreateFab(
tooltip: '上传健康报告',
onPressed: () => _showUploadOptions(context, ref),
backgroundColor: _reportBlue,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: const Icon(Icons.add, size: 28, color: Colors.white),
);
}
@@ -516,20 +742,23 @@ class ReportListPage extends ConsumerWidget {
showModalBottomSheet(
context: context,
backgroundColor: Colors.white,
showDragHandle: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.xl)),
),
builder: (ctx) => SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Wrap(
padding: const EdgeInsets.fromLTRB(20, 2, 20, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ListTile(
leading: const Icon(
Icons.camera_alt_outlined,
color: _reportBlue,
),
title: const Text('拍照上传', style: TextStyle(fontSize: 17)),
const Text('上传健康报告', style: AppTextStyles.sectionTitle),
const SizedBox(height: 10),
_ReportUploadOption(
icon: LucideIcons.camera,
label: '拍照上传',
onTap: () async {
Navigator.pop(ctx);
final picker = ImagePicker();
@@ -542,12 +771,13 @@ class ReportListPage extends ConsumerWidget {
}
},
),
ListTile(
leading: const Icon(
Icons.photo_library_outlined,
color: _reportCyan,
),
title: const Text('从相册选择', style: TextStyle(fontSize: 17)),
const Padding(
padding: EdgeInsets.only(left: 50),
child: Divider(height: 1, color: AppColors.divider),
),
_ReportUploadOption(
icon: LucideIcons.images,
label: '从相册选择',
onTap: () async {
Navigator.pop(ctx);
final picker = ImagePicker();
@@ -560,12 +790,13 @@ class ReportListPage extends ConsumerWidget {
}
},
),
ListTile(
leading: const Icon(
Icons.picture_as_pdf_outlined,
color: _reportBlue,
),
title: const Text('上传 PDF', style: TextStyle(fontSize: 17)),
const Padding(
padding: EdgeInsets.only(left: 50),
child: Divider(height: 1, color: AppColors.divider),
),
_ReportUploadOption(
icon: LucideIcons.fileText,
label: '上传 PDF',
onTap: () async {
Navigator.pop(ctx);
final result = await FilePicker.platform.pickFiles(
@@ -587,39 +818,19 @@ class ReportListPage extends ConsumerWidget {
}
Widget _buildEmptyState(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: _reportBlue.withValues(alpha: 0.08),
borderRadius: AppRadius.pillBorder,
),
child: Icon(_reportVisual.icon, size: 44, color: _reportBlue),
),
const SizedBox(height: 20),
const Text(
'暂无检查报告',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 8),
const Text(
'点击右下角按钮上传报告',
style: TextStyle(fontSize: 16, color: AppColors.textHint),
),
],
),
return AppEmptyState(
icon: _reportVisual.icon,
iconColor: _reportVisual.color,
title: '暂无检查报告',
subtitle: '点击右下角按钮上传报告',
);
}
Widget _buildReportRow(ReportItem report, {required bool showDivider}) {
Widget _buildReportRow(
ReportItem report, {
required bool showDivider,
required bool deleting,
}) {
final displayTitle = (report.title == 'Other' || report.title == 'other')
? '检查报告'
: report.title;
@@ -663,6 +874,8 @@ class ReportListPage extends ConsumerWidget {
_formatDate(report.uploadedAt),
style: AppTextStyles.listSubtitle,
),
const SizedBox(height: 6),
_buildStatusBadges(report),
if (report.aiStatus == 'Failed') ...[
const SizedBox(height: 4),
Text(
@@ -672,7 +885,7 @@ class ReportListPage extends ConsumerWidget {
style: const TextStyle(
fontSize: 13,
height: 1.35,
color: AppColors.error,
color: AppColors.errorText,
fontWeight: FontWeight.w600,
),
),
@@ -681,13 +894,18 @@ class ReportListPage extends ConsumerWidget {
),
),
const SizedBox(width: 8),
_buildStatusBadge(report),
const SizedBox(width: 8),
const Icon(
Icons.chevron_right,
size: 21,
color: AppColors.textHint,
),
if (deleting)
const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
const Icon(
Icons.chevron_right,
size: 21,
color: AppColors.textHint,
),
],
),
),
@@ -706,31 +924,7 @@ class ReportListPage extends ConsumerWidget {
);
}
Widget _buildStatusBadge(ReportItem report) {
final (label, bg, fg) = switch (report.status) {
_ when report.reviewStatus == 'Reviewed' => (
'已审核',
AppColors.successLight,
AppColors.success,
),
_ when report.aiStatus == 'Analyzing' => (
'分析中',
_reportBlue.withValues(alpha: 0.08),
_reportBlue,
),
_ when report.aiStatus == 'Failed' => (
'分析失败',
AppColors.error.withValues(alpha: 0.08),
AppColors.error,
),
_ when report.aiStatus == 'Succeeded' => (
'待审核',
AppColors.warningLight,
AppColors.warning,
),
_ => ('分析中', _reportBlue.withValues(alpha: 0.08), _reportBlue),
};
Widget _statusBadge(String label, Color bg, Color fg) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
@@ -745,6 +939,30 @@ class ReportListPage extends ConsumerWidget {
);
}
Widget _buildStatusBadges(ReportItem report) {
final aiBadge = switch (report.aiStatus) {
'Succeeded' => _statusBadge(
'AI 已分析',
AppColors.successLight,
AppColors.successText,
),
'Failed' => _statusBadge(
'AI 分析失败',
AppColors.error.withValues(alpha: 0.08),
AppColors.errorText,
),
_ => _statusBadge(
'AI 分析中',
_reportBlue.withValues(alpha: 0.08),
_reportBlue,
),
};
final reviewBadge = report.reviewStatus == 'Reviewed'
? _statusBadge('医生已审核', AppColors.successLight, AppColors.successText)
: _statusBadge('待医生审核', AppColors.warningLight, AppColors.warningText);
return Wrap(spacing: 6, runSpacing: 4, children: [aiBadge, reviewBadge]);
}
String _failureSummary(ReportItem report) {
final summary = report.analysisSummary?.trim();
if (summary != null && summary.isNotEmpty) {
@@ -791,43 +1009,79 @@ String _catTitle(String c) => switch (c) {
_ => '检查报告',
};
class ReportOriginalPage extends ConsumerWidget {
class ReportOriginalPage extends ConsumerStatefulWidget {
final String url;
final String title;
final String fileType;
const ReportOriginalPage({super.key, required this.url, this.title = '原始报告'});
const ReportOriginalPage({
super.key,
required this.url,
this.title = '原始报告',
this.fileType = 'Image',
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final imageUrl = _absoluteUrl(url);
ConsumerState<ReportOriginalPage> createState() => _ReportOriginalPageState();
}
class _ReportOriginalPageState extends ConsumerState<ReportOriginalPage> {
int _reloadToken = 0;
@override
Widget build(BuildContext context) {
final rawUrl = widget.url.trim();
final fileUrl = rawUrl.isEmpty ? null : _absoluteUrl(rawUrl);
return GradientScaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => popRoute(ref),
),
title: Text(title),
title: Text(widget.title),
),
body: Center(
child: InteractiveViewer(
minScale: 0.7,
maxScale: 4,
child: Image.network(
imageUrl,
fit: BoxFit.contain,
errorBuilder: (_, _, _) => const Padding(
padding: EdgeInsets.all(24),
child: Text(
'原始报告图片加载失败',
style: TextStyle(color: AppColors.textSecondary),
),
),
body: fileUrl == null
? AppErrorState(title: '无法打开原始报告', subtitle: '报告文件地址为空,请返回后刷新列表')
: isPdfReport(widget.fileType, fileUrl)
? _buildPdf(fileUrl)
: _buildImage(fileUrl),
);
}
Widget _buildImage(String imageUrl) {
return Center(
child: InteractiveViewer(
minScale: 0.7,
maxScale: 4,
child: Image.network(
imageUrl,
key: ValueKey('$imageUrl-$_reloadToken'),
fit: BoxFit.contain,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(
child: CircularProgressIndicator(color: AppColors.report),
);
},
errorBuilder: (_, _, _) => AppErrorState(
title: '原始报告加载失败',
subtitle: '请检查网络后重试',
onRetry: () => setState(() => _reloadToken++),
),
),
),
);
}
Widget _buildPdf(String _) {
return AppEmptyState(
icon: AppModuleVisuals.report.icon,
iconColor: AppModuleVisuals.report.color,
title: '暂不支持预览 PDF',
subtitle: '当前版本优先支持图片报告PDF 预览将在后续版本接入',
);
}
String _absoluteUrl(String value) {
if (value.startsWith('http://') || value.startsWith('https://')) {
return value;
@@ -838,3 +1092,55 @@ class ReportOriginalPage extends ConsumerWidget {
return '$baseUrl/$value';
}
}
class _ReportUploadOption extends StatelessWidget {
final IconData icon;
final String label;
final VoidCallback onTap;
const _ReportUploadOption({
required this.icon,
required this.label,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return InkWell(
borderRadius: AppRadius.mdBorder,
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 13),
child: Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: _reportPageSoft,
borderRadius: AppRadius.smBorder,
),
child: Icon(icon, size: 20, color: _reportPageColor),
),
const SizedBox(width: 12),
Expanded(
child: Text(
label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppColors.textPrimary,
),
),
),
const Icon(
LucideIcons.chevronRight,
size: 18,
color: AppColors.textHint,
),
],
),
),
);
}
}

View File

@@ -0,0 +1,107 @@
enum HealthReminderMetric { bloodPressure, heartRate, glucose, spo2, weight }
extension HealthReminderMetricX on HealthReminderMetric {
String get label => switch (this) {
HealthReminderMetric.bloodPressure => '血压',
HealthReminderMetric.heartRate => '心率',
HealthReminderMetric.glucose => '血糖',
HealthReminderMetric.spo2 => '血氧',
HealthReminderMetric.weight => '体重',
};
String get backendField => switch (this) {
HealthReminderMetric.bloodPressure => 'healthRecordReminderBloodPressure',
HealthReminderMetric.heartRate => 'healthRecordReminderHeartRate',
HealthReminderMetric.glucose => 'healthRecordReminderGlucose',
HealthReminderMetric.spo2 => 'healthRecordReminderSpO2',
HealthReminderMetric.weight => 'healthRecordReminderWeight',
};
}
class NotificationPrefs {
final bool pushEnabled;
final bool medicationReminder;
final bool followUpReminder;
final bool doctorReply;
final bool abnormalAlert;
final bool dndEnabled;
final int dndStartMinutes;
final int dndEndMinutes;
final bool healthRecordReminder;
final Set<HealthReminderMetric> enabledHealthMetrics;
const NotificationPrefs({
required this.pushEnabled,
required this.medicationReminder,
required this.followUpReminder,
required this.doctorReply,
required this.abnormalAlert,
required this.dndEnabled,
required this.dndStartMinutes,
required this.dndEndMinutes,
required this.healthRecordReminder,
required this.enabledHealthMetrics,
});
factory NotificationPrefs.fromJson(Map<dynamic, dynamic> json) {
final metrics = <HealthReminderMetric>{};
for (final metric in HealthReminderMetric.values) {
if ((json[metric.backendField] as bool?) ?? true) metrics.add(metric);
}
return NotificationPrefs(
pushEnabled: (json['pushEnabled'] as bool?) ?? true,
medicationReminder: (json['medicationReminder'] as bool?) ?? true,
followUpReminder: (json['followUpReminder'] as bool?) ?? true,
doctorReply: (json['doctorReply'] as bool?) ?? false,
abnormalAlert: (json['abnormalAlert'] as bool?) ?? true,
dndEnabled: (json['dndEnabled'] as bool?) ?? false,
dndStartMinutes: (json['dndStartMinutes'] as num?)?.toInt() ?? 22 * 60,
dndEndMinutes: (json['dndEndMinutes'] as num?)?.toInt() ?? 8 * 60,
healthRecordReminder: (json['healthRecordReminder'] as bool?) ?? true,
enabledHealthMetrics: Set.unmodifiable(metrics),
);
}
}
class NotificationPrefsViewState {
final NotificationPrefs? prefs;
final bool loading;
final String? loadError;
final Set<String> savingKeys;
const NotificationPrefsViewState({
this.prefs,
this.loading = false,
this.loadError,
this.savingKeys = const {},
});
NotificationPrefsViewState copyWith({
NotificationPrefs? prefs,
bool? loading,
String? loadError,
bool clearLoadError = false,
Set<String>? savingKeys,
}) => NotificationPrefsViewState(
prefs: prefs ?? this.prefs,
loading: loading ?? this.loading,
loadError: clearLoadError ? null : loadError ?? this.loadError,
savingKeys: savingKeys ?? this.savingKeys,
);
}
String healthMetricSummary(Set<HealthReminderMetric> metrics) {
if (metrics.isEmpty) return '至少选择一项';
if (metrics.length == HealthReminderMetric.values.length) return '全部指标';
return HealthReminderMetric.values
.where(metrics.contains)
.map((metric) => metric.label)
.join('');
}
Map<String, bool> healthMetricUpdatePayload(
Set<HealthReminderMetric> metrics,
) => {
for (final metric in HealthReminderMetric.values)
metric.backendField: metrics.contains(metric),
};

File diff suppressed because it is too large Load Diff

View File

@@ -13,11 +13,11 @@ class SettingsPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
backgroundColor: const Color(0xFFF6F8FC),
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
scrolledUnderElevation: 0.5,
scrolledUnderElevation: 0,
surfaceTintColor: Colors.transparent,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
@@ -33,105 +33,116 @@ class SettingsPage extends ConsumerWidget {
),
centerTitle: true,
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 18, 16, 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_SettingsGroup(
children: [
_SettingsTile(
icon: LucideIcons.bluetooth,
title: '蓝牙设备',
onTap: () => pushRoute(ref, 'devices'),
),
_SettingsTile(
icon: LucideIcons.bell,
title: '消息通知',
onTap: () => pushRoute(ref, 'notificationPrefs'),
),
_SettingsTile(
icon: LucideIcons.info,
title: '关于小脉健康',
onTap: () =>
pushRoute(ref, 'staticText', params: {'type': 'about'}),
),
_SettingsTile(
icon: LucideIcons.shield,
title: '隐私协议',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'privacy'},
body: ColoredBox(
color: AppColors.background,
child: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 18, 16, 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_SettingsGroup(
children: [
_SettingsTile(
icon: LucideIcons.bluetooth,
title: '蓝牙设备',
onTap: () => pushRoute(ref, 'devices'),
),
),
_SettingsTile(
icon: Icons.fact_check_outlined,
title: '个人信息收集清单',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'personalInfoList'},
_SettingsTile(
icon: LucideIcons.bell,
title: '消息通知',
onTap: () => pushRoute(ref, 'notificationPrefs'),
),
),
_SettingsTile(
icon: Icons.hub_outlined,
title: '第三方 SDK 共享清单',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'thirdPartySdkList'},
_SettingsTile(
icon: LucideIcons.info,
title: '关于小脉健康',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'about'},
),
),
_SettingsTile(
icon: LucideIcons.shield,
title: '隐私协议',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'privacy'},
),
),
_SettingsTile(
icon: Icons.fact_check_outlined,
title: '个人信息收集清单',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'personalInfoList'},
),
),
_SettingsTile(
icon: Icons.hub_outlined,
title: '第三方 SDK 共享清单',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'thirdPartySdkList'},
),
),
_SettingsTile(
icon: Icons.description_outlined,
title: '服务协议',
onTap: () => pushRoute(
ref,
'staticText',
params: {'type': 'terms'},
),
),
],
),
const SizedBox(height: 24),
OutlinedButton.icon(
onPressed: () => _deleteAccount(context, ref),
icon: const Icon(LucideIcons.trash, size: 19),
label: const Text('删除账号'),
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.error,
side: BorderSide(
color: AppColors.error.withValues(alpha: 0.34),
),
backgroundColor: Colors.white,
minimumSize: const Size.fromHeight(52),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
),
shape: RoundedRectangleBorder(
borderRadius: AppRadius.lgBorder,
),
),
_SettingsTile(
icon: Icons.description_outlined,
title: '服务协议',
onTap: () =>
pushRoute(ref, 'staticText', params: {'type': 'terms'}),
),
],
),
const SizedBox(height: 24),
OutlinedButton.icon(
onPressed: () => _deleteAccount(context, ref),
icon: const Icon(LucideIcons.trash, size: 19),
label: const Text('删除账号'),
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.error,
side: BorderSide(
color: AppColors.error.withValues(alpha: 0.34),
),
backgroundColor: Colors.white,
minimumSize: const Size.fromHeight(52),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: () => _logout(context, ref),
icon: const Icon(LucideIcons.logOut, size: 19),
label: const Text('退出登录'),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.error,
foregroundColor: Colors.white,
minimumSize: const Size.fromHeight(52),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: () => _logout(context, ref),
icon: const Icon(LucideIcons.logOut, size: 19),
label: const Text('退出登录'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: AppColors.textPrimary,
elevation: 0,
side: const BorderSide(color: AppColors.borderLight),
minimumSize: const Size.fromHeight(52),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
),
shape: RoundedRectangleBorder(
borderRadius: AppRadius.lgBorder,
),
),
),
),
],
],
),
),
),
),