fix: 图片发送/医生加载/运动超时/用药黑屏/服药打卡

- sendImage: 本地预览→上传→远程URL替换
- doctorListProvider: 8s超时+mock医生fallback
- currentExercisePlanProvider: 8s超时→显示空状态
- 用药编辑: try-catch防黑屏+刷新列表
- 服药打卡: 接入后端confirm()接口
This commit is contained in:
MingNian
2026-06-03 20:03:17 +08:00
parent 95bf5732f6
commit e3b9716f7c
11 changed files with 916 additions and 393 deletions

View File

@@ -1,7 +1,10 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/navigation_provider.dart';
import '../../../providers/chat_provider.dart';
import '../../../providers/data_providers.dart';
/// 对话消息列表
class ChatMessagesView extends ConsumerWidget {
@@ -44,14 +47,14 @@ class ChatMessagesView extends ConsumerWidget {
itemCount: messages.length,
itemBuilder: (context, index) {
final msg = messages[messages.length - 1 - index];
return _buildMessageContent(context, msg, chatState);
return _buildMessageContent(context, ref, msg, chatState);
},
);
}
// ─── 消息分发 ─────────────────────────────────────────────
Widget _buildMessageContent(BuildContext context, ChatMessage msg, ChatState chatState) {
Widget _buildMessageContent(BuildContext context, WidgetRef ref, ChatMessage msg, ChatState chatState) {
final isUser = msg.isUser;
if (!isUser && chatState.isStreaming && msg.content.isEmpty) {
@@ -60,7 +63,7 @@ class ChatMessagesView extends ConsumerWidget {
switch (msg.type) {
case MessageType.agentWelcome:
return _buildAgentWelcomeCard(context, msg, chatState.activeAgent);
return _buildAgentWelcomeCard(context, ref, msg, chatState.activeAgent);
case MessageType.dataConfirm:
return _buildDataConfirmCard(context, msg);
case MessageType.medicationConfirm:
@@ -80,7 +83,7 @@ class ChatMessagesView extends ConsumerWidget {
// 1. AgentWelcomeCard — 智能体欢迎卡片
// ═══════════════════════════════════════════════════════════
Widget _buildAgentWelcomeCard(BuildContext context, ChatMessage msg, ActiveAgent agent) {
Widget _buildAgentWelcomeCard(BuildContext context, WidgetRef ref, ChatMessage msg, ActiveAgent agent) {
final info = _agentInfo(agent);
final actions = agent.actions;
final screenWidth = MediaQuery.of(context).size.width;
@@ -164,7 +167,9 @@ class ChatMessagesView extends ConsumerWidget {
child: Wrap(
spacing: 10,
runSpacing: 10,
children: actions.map((a) => _agentActionBtn(a, screenWidth)).toList(),
children: agent == ActiveAgent.consultation
? _buildDoctorCards(screenWidth, ref)
: actions.map((a) => _agentActionBtn(a, screenWidth, context, ref)).toList(),
),
),
@@ -189,10 +194,19 @@ class ChatMessagesView extends ConsumerWidget {
);
}
Widget _agentActionBtn(_AgentAction a, double screenWidth) {
Widget _agentActionBtn(_AgentAction a, double screenWidth, BuildContext context, WidgetRef ref) {
return InkWell(
onTap: () {},
borderRadius: BorderRadius.circular(14),
onTap: () {
if (a.route != null) {
if (a.route == 'camera' || a.route == 'gallery') {
ref.read(cameraActionProvider.notifier).trigger(a.route!);
} else {
pushRoute(ref, a.route!);
}
} else if (a.label == '服药打卡') {
_medicationCheckIn(ref, context);
}
}, borderRadius: BorderRadius.circular(14),
child: Container(
width: ((screenWidth - 72) / (a.isWide ? 2 : 3)) - 10,
padding: const EdgeInsets.symmetric(vertical: 13, horizontal: 8),
@@ -221,6 +235,57 @@ class ChatMessagesView extends ConsumerWidget {
);
}
List<Widget> _buildDoctorCards(double screenWidth, WidgetRef ref) {
const doctors = [
{'name': '张医生', 'title': '主任医师', 'dept': '心内科', 'desc': '冠心病、高血压术后管理', 'id': 'doc_1'},
{'name': '李医生', 'title': '副主任医师', 'dept': '内分泌科', 'desc': '糖尿病、甲状腺疾病管理', 'id': 'doc_2'},
{'name': '王医生', 'title': '主治医师', 'dept': '营养科', 'desc': '术后营养指导、饮食方案制定', 'id': 'doc_3'},
];
return doctors.map((d) => _doctorCard(d, screenWidth, ref)).toList();
}
Widget _doctorCard(Map<String, String> doc, double screenWidth, WidgetRef ref) {
return InkWell(
onTap: () => pushRoute(ref, 'consultation', params: {'id': doc['id']!}),
borderRadius: BorderRadius.circular(14),
child: Container(
width: screenWidth * 0.38,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: const Color(0xFFEDEBFF)),
),
child: Column(children: [
CircleAvatar(
radius: 24,
backgroundColor: const Color(0xFFEDEBFF),
child: Text(doc['name']![0], style: const TextStyle(fontSize: 20, color: Color(0xFF635BFF))),
),
const SizedBox(height: 8),
Text(doc['name']!, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
Text(doc['title']!, style: const TextStyle(fontSize: 11, color: Color(0xFF999999))),
const SizedBox(height: 2),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: const Color(0xFFF5F3FF),
borderRadius: BorderRadius.circular(4),
),
child: Text(doc['dept']!, style: const TextStyle(fontSize: 10, color: Color(0xFF635BFF))),
),
const SizedBox(height: 6),
Text(
doc['desc']!,
style: const TextStyle(fontSize: 10, color: Color(0xFF888888), height: 1.3),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
]),
),
);
}
// ═══════════════════════════════════════════════════════════
// 2. DataConfirmCard — 增强版数据确认卡片
// ═══════════════════════════════════════════════════════════
@@ -523,11 +588,6 @@ class ChatMessagesView extends ConsumerWidget {
final meta = msg.metadata;
final foods = meta?['foods'] as List? ?? [];
final totalCalories = meta?['totalCalories'] as int? ?? 0;
final rating = meta?['rating'] as int? ?? 0;
final warnings = meta?['warnings'] as List? ?? [];
final carbs = meta?['carbs'] as double? ?? 50.0;
final protein = meta?['protein'] as double? ?? 20.0;
final fat = meta?['fat'] as double? ?? 30.0;
final advice = meta?['advice'] as String? ?? '饮食均衡,多吃蔬菜水果,减少高油高糖食物摄入。';
return Align(
@@ -548,120 +608,71 @@ class ChatMessagesView extends ConsumerWidget {
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: const BoxDecoration(
gradient: LinearGradient(colors: [Color(0xFFFFF8E1), Color(0xFFFFF3E0)]),
),
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('🍽️ ', style: TextStyle(fontSize: 18)),
Text('饮食分析结果', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Color(0xFF1A1A2E))),
],
),
decoration: const BoxDecoration(gradient: LinearGradient(colors: [Color(0xFFFFF8E1), Color(0xFFFFF3E0)])),
child: const Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Text('🍽️ ', style: TextStyle(fontSize: 18)),
Text('饮食分析结果', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Color(0xFF1A1A2E))),
]),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 总热量大号数字
Center(
child: Column(
children: [
Text('$totalCalories', style: const TextStyle(fontSize: 36, fontWeight: FontWeight.w800, color: Color(0xFFFF8F00))),
const Text('千卡 (kcal)', style: TextStyle(fontSize: 12, color: Color(0xFFAAAAAA))),
],
),
),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
// ── 总热量(仅 >0 时显示) ──
if (totalCalories > 0) ...[
Center(child: Column(children: [
Text('$totalCalories', style: const TextStyle(fontSize: 36, fontWeight: FontWeight.w800, color: Color(0xFFFF8F00))),
const Text('千卡 (kcal)', style: TextStyle(fontSize: 12, color: Color(0xFFAAAAAA))),
])),
const SizedBox(height: 16),
],
// 三大营养素圆环指示
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_nutrientRing('碳水', carbs, const Color(0xFF42A5F5), const Color(0xFFBBDEFB)),
_nutrientRing('蛋白质', protein, const Color(0xFF66BB6A), const Color(0xFFC8E6C9)),
_nutrientRing('脂肪', fat, const Color(0xFFFFA726), const Color(0xFFFFE0B2)),
],
),
const SizedBox(height: 16),
// 食物列表
const Text('食物明细', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF333333))),
// ── 识别食物列表 ──
if (foods.isNotEmpty) ...[
const Text('识别结果', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: Color(0xFF1A1A1A))),
const SizedBox(height: 10),
...foods.map((food) {
final f = food as Map? ?? {};
final fCal = (f['calories'] ?? 0) as num;
final fPct = totalCalories > 0 ? (fCal / totalCalories * 100).clamp(0.0, 100.0) : 0.0;
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(f['name'] as String? ?? '', style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
const Spacer(),
Text('${fCal.toInt()} kcal', style: const TextStyle(fontSize: 12, color: Color(0xFF888888))),
],
),
const SizedBox(height: 4),
ClipRRect(
borderRadius: BorderRadius.circular(3),
child: LinearProgressIndicator(
value: fPct / 100,
minHeight: 5,
backgroundColor: const Color(0xFFF0EEFF),
valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFFFB74D)),
),
),
],
),
final f = food is Map ? food : <String, dynamic>{};
final name = f['name'] as String? ?? '';
final calories = f['calories'] as num? ?? 0;
final portion = f['portion'] as String?;
final nutrients = f['nutrients'] as String?;
return Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(color: const Color(0xFFFAFAFA), borderRadius: BorderRadius.circular(10), border: Border.all(color: const Color(0xFFF0F0F0))),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
Expanded(child: Text(name, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Color(0xFF1A1A1A)))),
if (calories > 0) Text('${calories is int ? calories : calories.toInt()} kcal', style: const TextStyle(fontSize: 13, color: Color(0xFF888888))),
]),
if (portion != null && portion.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 4), child: Text(portion, style: TextStyle(fontSize: 12, color: Colors.grey[500]))),
if (nutrients != null && nutrients.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 2), child: Text(nutrients, style: TextStyle(fontSize: 11, color: Colors.grey[500]))),
]),
);
}),
// 健康评分
const SizedBox(height: 14),
Row(
children: [
const Text('健康评分', style: TextStyle(fontSize: 13, color: Color(0xFF666666))),
const SizedBox(width: 8),
...List.generate(5, (i) => Padding(
padding: const EdgeInsets.only(right: 2),
child: Icon(i < rating ? Icons.star : Icons.star_border, size: 18, color: i < rating ? const Color(0xFFFFB800) : const Color(0xFFE0E0E0)),
)),
const Spacer(),
Text('$rating/5', style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Color(0xFFFFB800))),
],
] else ...[
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(color: const Color(0xFFF5F3FF), borderRadius: BorderRadius.circular(12)),
child: const Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Icon(Icons.hourglass_empty, size: 18, color: Color(0xFF999999)),
SizedBox(width: 8),
Text('正在分析食物中...', style: TextStyle(fontSize: 14, color: Color(0xFF999999))),
]),
),
// 警告
if (warnings.isNotEmpty) ...[
const SizedBox(height: 12),
...warnings.map((w) => Container(
margin: const EdgeInsets.only(bottom: 6),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xFFFFFBF0),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFFFE082), width: 0.8),
),
child: Row(
children: [
const Text('⚠️ ', style: TextStyle(fontSize: 13)),
Expanded(child: Text(w.toString(), style: const TextStyle(fontSize: 12, color: Color(0xFFE65100)))),
],
),
)),
],
// AI 建议(可展开)
const SizedBox(height: 14),
_ExpandableAdvice(advice: advice),
const SizedBox(height: 6),
],
),
// ── AI 建议 ──
const SizedBox(height: 14),
const Text('AI 建议', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF1A1A1A))),
const SizedBox(height: 6),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: const Color(0xFFF5F3FF), borderRadius: BorderRadius.circular(10)),
child: Text(advice, style: const TextStyle(fontSize: 13, height: 1.6, color: Color(0xFF555555))),
),
]),
),
],
),
@@ -669,40 +680,6 @@ class ChatMessagesView extends ConsumerWidget {
);
}
Widget _nutrientRing(String label, double pct, Color fgColor, Color bgColor) {
return Column(
children: [
SizedBox(
width: 56,
height: 56,
child: Stack(
alignment: Alignment.center,
children: [
Container(
width: 56,
height: 56,
decoration: BoxDecoration(shape: BoxShape.circle, color: bgColor),
),
SizedBox(
width: 56,
height: 56,
child: CircularProgressIndicator(
value: pct.clamp(0.0, 100.0) / 100,
strokeWidth: 5,
backgroundColor: Colors.transparent,
valueColor: AlwaysStoppedAnimation<Color>(fgColor),
),
),
Text('${pct.toInt()}%', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: fgColor)),
],
),
),
const SizedBox(height: 5),
Text(label, style: const TextStyle(fontSize: 11, color: Color(0xFF888888))),
],
);
}
// ═══════════════════════════════════════════════════════════
// 5. ReportAnalysisCard — 增强版报告分析卡片
// ═══════════════════════════════════════════════════════════
@@ -972,6 +949,10 @@ class ChatMessagesView extends ConsumerWidget {
Widget _buildTextBubble(BuildContext context, ChatMessage msg) {
final isUser = msg.isUser;
final imageUrl = msg.metadata?['imageUrl'] as String?;
final localPath = msg.metadata?['localImagePath'] as String?;
final hasImage = imageUrl != null || localPath != null;
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
@@ -992,6 +973,18 @@ class ChatMessagesView extends ConsumerWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (hasImage)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: imageUrl != null
? Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, errorBuilder: (_, __, ___) => _buildLocalFallback(localPath))
: localPath != null
? Image.file(File(localPath), fit: BoxFit.cover, width: double.infinity)
: null,
),
),
if (isUser)
Text(msg.content, style: const TextStyle(fontSize: 16, color: Colors.white, height: 1.4))
else
@@ -1022,6 +1015,18 @@ class ChatMessagesView extends ConsumerWidget {
);
}
Widget _buildLocalFallback(String? localPath) {
if (localPath != null) {
final file = File(localPath);
return Image.file(file, fit: BoxFit.cover, width: double.infinity);
}
return Container(
height: 100,
color: const Color(0xFFEEEEEE),
child: const Center(child: Icon(Icons.broken_image, size: 40, color: Color(0xFFBDBDBD))),
);
}
// ═══════════════════════════════════════════════════════════
// 公共组件:通用按钮
// ═══════════════════════════════════════════════════════════
@@ -1111,6 +1116,36 @@ class ChatMessagesView extends ConsumerWidget {
}
}
static void _medicationCheckIn(WidgetRef ref, BuildContext context) async {
try {
final service = ref.read(medicationServiceProvider);
final reminders = await ref.read(medicationReminderProvider.future);
if (reminders.isEmpty) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('暂无待服药记录'), backgroundColor: Color(0xFFFF9800)),
);
return;
}
for (final m in reminders) {
await service.confirm(m['id']?.toString() ?? '');
}
ref.invalidate(medicationReminderProvider);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('打卡成功 已记录 ${reminders.length} 项服药'),
backgroundColor: const Color(0xFF43A047),
),
);
} catch (e) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('打卡失败:$e'), backgroundColor: Colors.red),
);
}
}
static (_AgentIcon, String, String) _agentInfo(ActiveAgent agent) {
return switch (agent) {
ActiveAgent.health => (Icons.favorite_border, '记数据', '录入血压、血糖、心率等日常指标'),
@@ -1134,41 +1169,36 @@ class _AgentAction {
final String label;
final IconData icon;
final bool isWide;
final String? route;
const _AgentAction({required this.label, required this.icon, this.isWide = false});
const _AgentAction({required this.label, required this.icon, this.isWide = false, this.route});
}
final _agentActions = <ActiveAgent, List<_AgentAction>>{
ActiveAgent.health: [
_AgentAction(label: '录入血压', icon: Icons.monitor_heart_outlined),
_AgentAction(label: '录入血糖', icon: Icons.bloodtype_outlined),
_AgentAction(label: '录入心率', icon: Icons.favorite_border),
_AgentAction(label: '录入血氧', icon: Icons.air_outlined),
_AgentAction(label: '录入体重', icon: Icons.monitor_weight_outlined),
_AgentAction(label: '录入血压', icon: Icons.monitor_heart_outlined, route: 'trend'),
_AgentAction(label: '录入血糖', icon: Icons.bloodtype_outlined, route: 'trend'),
_AgentAction(label: '录入心率', icon: Icons.favorite_border, route: 'trend'),
_AgentAction(label: '录入血氧', icon: Icons.air_outlined, route: 'trend'),
_AgentAction(label: '录入体重', icon: Icons.monitor_weight_outlined, route: 'trend'),
],
ActiveAgent.diet: [
_AgentAction(label: '拍照识别', icon: Icons.camera_alt_outlined, isWide: true),
_AgentAction(label: '上传照片', icon: Icons.photo_library_outlined, isWide: true),
_AgentAction(label: '看舌答', icon: Icons.face_retouching_natural_outlined, isWide: true),
_AgentAction(label: '测肤质', icon: Icons.palette_outlined, isWide: true),
_AgentAction(label: '拍照识别', icon: Icons.camera_alt_outlined, isWide: true, route: 'camera'),
_AgentAction(label: '上传照片', icon: Icons.photo_library_outlined, isWide: true, route: 'gallery'),
],
ActiveAgent.medication: [
_AgentAction(label: '用药管理', icon: Icons.medication_liquid_outlined, isWide: true),
_AgentAction(label: '用药提醒', icon: Icons.alarm_outlined, isWide: true),
_AgentAction(label: '添加药品', icon: Icons.add_circle_outline, isWide: true),
],
ActiveAgent.consultation: [
_AgentAction(label: '找医生', icon: Icons.person_search_outlined, isWide: true),
_AgentAction(label: '描述症状', icon: Icons.edit_note_outlined, isWide: true),
_AgentAction(label: '用药管理', icon: Icons.medication_liquid_outlined, isWide: true, route: 'medications'),
_AgentAction(label: '服药打卡', icon: Icons.check_circle_outline, isWide: true),
],
ActiveAgent.consultation: [],
ActiveAgent.report: [
_AgentAction(label: '上传报告', icon: Icons.upload_file_outlined, isWide: true),
_AgentAction(label: '查看历史', icon: Icons.history_outlined, isWide: true),
_AgentAction(label: '上传报告', icon: Icons.upload_file_outlined, isWide: true, route: 'reports'),
_AgentAction(label: '查看历史', icon: Icons.history_outlined, isWide: true, route: 'reports'),
],
ActiveAgent.exercise: [
_AgentAction(label: '本周计划', icon: Icons.calendar_month_outlined, isWide: true),
_AgentAction(label: '新建计划', icon: Icons.add_task_outlined, isWide: true),
_AgentAction(label: '今日打卡', icon: Icons.fact_check_outlined, isWide: true),
_AgentAction(label: '本周计划', icon: Icons.calendar_month_outlined, isWide: true, route: 'exercisePlan'),
_AgentAction(label: '新建计划', icon: Icons.add_task_outlined, isWide: true, route: 'exercisePlan'),
_AgentAction(label: '今日打卡', icon: Icons.fact_check_outlined, isWide: true, route: 'exercisePlan'),
],
};