feat: 增加全家庭智能药箱功能,支持扫码识别(追溯码/GS1/条形码)、出厂有效期与开封保质期双轨追踪及局域网多设备同步

This commit is contained in:
shen
2026-10-27 23:56:47 -07:00
parent ba32e29682
commit 113794fa4b
15 changed files with 2934 additions and 9 deletions
+129
View File
@@ -5,11 +5,13 @@ import '../models/canister.dart';
import '../models/dose_record.dart';
import '../models/app_settings.dart';
import '../services/storage_service.dart';
import '../models/medicine_item.dart';
import 'session_screen.dart';
import 'history_screen.dart';
import 'settings_screen.dart';
import 'plan_config_screen.dart';
import 'lan_sync_screen.dart';
import 'medicine_cabinet_screen.dart';
import '../services/sync_service.dart';
import '../services/active_session_service.dart';
@@ -284,6 +286,22 @@ class _HomeScreenState extends State<HomeScreen> {
],
),
actions: [
IconButton(
icon: const Icon(Icons.medical_services_outlined, color: Color(0xFF059669)),
tooltip: '家庭药箱',
visualDensity: VisualDensity.compact,
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => MedicineCabinetScreen(
storageService: widget.storageService,
syncService: SyncService(widget.storageService),
),
),
);
_loadData();
},
),
IconButton(
icon: const Icon(Icons.sync, color: Color(0xFF2563EB)),
tooltip: '局域网同步',
@@ -352,6 +370,11 @@ class _HomeScreenState extends State<HomeScreen> {
const SizedBox(height: 20),
// 模块 3.5:家庭智能药箱看板入口
_buildFamilyMedicineCabinetCard(),
const SizedBox(height: 20),
// 模块 4:最近吸入记录底栏
_buildLastRecordFooter(),
],
@@ -360,6 +383,112 @@ class _HomeScreenState extends State<HomeScreen> {
);
}
// 3.5 家庭智能药箱入口卡片
Widget _buildFamilyMedicineCabinetCard() {
final medicines = widget.storageService.getMedicines();
final dangerCount = medicines.where((m) =>
m.healthStatus == MedicineHealthStatus.overdueInUse ||
m.healthStatus == MedicineHealthStatus.expired).length;
final soonCount = medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length;
Color badgeBg = const Color(0xFFEFF6FF);
Color badgeColor = const Color(0xFF2563EB);
String badgeText = '${medicines.length} 种在库';
if (dangerCount > 0) {
badgeBg = const Color(0xFFFEF2F2);
badgeColor = const Color(0xFFEF4444);
badgeText = '⚠️ $dangerCount 种已超期/过期';
} else if (soonCount > 0) {
badgeBg = const Color(0xFFFEF3C7);
badgeColor = const Color(0xFFD97706);
badgeText = '🟡 $soonCount 种即将到期';
}
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: dangerCount > 0 ? Colors.red.shade300 : const Color(0xFFE2E8F0)),
),
child: InkWell(
onTap: () async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => MedicineCabinetScreen(
storageService: widget.storageService,
syncService: SyncService(widget.storageService),
),
),
);
_loadData();
},
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFFECFDF5),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.medical_services_outlined,
color: Color(0xFF059669),
size: 24,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Text(
'家庭智能药箱',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFF0F172A),
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: badgeBg,
borderRadius: BorderRadius.circular(6),
),
child: Text(
badgeText,
style: TextStyle(
color: badgeColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 3),
const Text(
'出厂有效期与开封保质期智能监控 · 扫码即识',
style: TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
),
const Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey),
],
),
),
),
);
}
// 0. 进行中雾化实时悬浮卡片 (返回主页不中断计时)
Widget _buildActiveSessionBanner() {
final step = _sessionService.currentStep;
+739
View File
@@ -0,0 +1,739 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/medicine_item.dart';
import '../services/medicine_parser_service.dart';
import '../services/storage_service.dart';
import '../services/sync_service.dart';
import 'medicine_edit_dialog.dart';
import 'medicine_scan_screen.dart';
class MedicineCabinetScreen extends StatefulWidget {
final StorageService storageService;
final SyncService syncService;
const MedicineCabinetScreen({
super.key,
required this.storageService,
required this.syncService,
});
@override
State<MedicineCabinetScreen> createState() => _MedicineCabinetScreenState();
}
class _MedicineCabinetScreenState extends State<MedicineCabinetScreen> {
List<MedicineItem> _medicines = [];
String _selectedFilter = '全部';
String _searchQuery = '';
bool _isSyncing = false;
final List<String> _filters = [
'全部',
'常温药箱',
'冰箱冷藏',
'宝宝专用',
'已开封',
'⚠️ 需处理',
];
@override
void initState() {
super.initState();
_loadMedicines();
}
void _loadMedicines() {
setState(() {
_medicines = widget.storageService.getMedicines();
});
}
Future<void> _performSync() async {
if (_isSyncing) return;
setState(() => _isSyncing = true);
final res = await widget.syncService.performSync();
if (mounted) {
setState(() => _isSyncing = false);
_loadMedicines();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(res.message),
backgroundColor: res.success ? const Color(0xFF059669) : Colors.red,
duration: const Duration(seconds: 3),
),
);
}
}
Future<void> _openScan() async {
final result = await Navigator.of(context).push<ScannedMedicineInfo>(
MaterialPageRoute(builder: (_) => const MedicineScanScreen()),
);
if (result != null && mounted) {
final savedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => MedicineEditDialog(scannedInfo: result),
);
if (savedItem != null) {
await widget.storageService.saveMedicine(savedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已添加药品:${savedItem.name}')),
);
}
}
}
}
Future<void> _addNewMedicine() async {
final savedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => const MedicineEditDialog(),
);
if (savedItem != null) {
await widget.storageService.saveMedicine(savedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已添加药品:${savedItem.name}')),
);
}
}
}
Future<void> _editMedicine(MedicineItem item) async {
final updatedItem = await showDialog<MedicineItem>(
context: context,
builder: (_) => MedicineEditDialog(initialItem: item),
);
if (updatedItem != null) {
await widget.storageService.saveMedicine(updatedItem);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已更新药品:${updatedItem.name}')),
);
}
}
}
Future<void> _deleteMedicine(MedicineItem item) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('确认下架/删除该药品?'),
content: Text('确定将【${item.name}】移出药箱吗?该操作将同步至所有设备。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('确认删除', style: TextStyle(color: Colors.white)),
),
],
),
);
if (confirmed == true) {
await widget.storageService.deleteMedicine(item.id);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已移出药品:${item.name}')),
);
}
}
}
Future<void> _openMedicineCard(MedicineItem item) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('确认开封打卡?'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('药品:${item.name}'),
const SizedBox(height: 8),
Text(
'推荐开封保质期限:${item.shelfLifeDaysAfterOpening ?? 60} 天',
style: const TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2563EB)),
),
const SizedBox(height: 8),
const Text(
'打卡后将自动开启开封保质期倒计时,全家设备实时同步。',
style: TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF2563EB)),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('确认开封', style: TextStyle(color: Colors.white)),
),
],
),
);
if (confirmed == true) {
final deviceName = await SyncService.getDeviceName();
await widget.storageService.openMedicine(item.id, deviceName: deviceName);
_loadMedicines();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('【${item.name}】已成功打卡开封!')),
);
}
}
}
List<MedicineItem> get _filteredMedicines {
return _medicines.where((m) {
// 搜索关键字匹配
if (_searchQuery.isNotEmpty) {
final q = _searchQuery.toLowerCase();
final matchName = m.name.toLowerCase().contains(q);
final matchSpec = m.spec.toLowerCase().contains(q);
final matchNotes = m.notes.toLowerCase().contains(q);
if (!matchName && !matchSpec && !matchNotes) return false;
}
// 标签筛选
switch (_selectedFilter) {
case '常温药箱':
return m.storageLocation.contains('常温');
case '冰箱冷藏':
return m.storageLocation.contains('冷藏') || m.storageLocation.contains('冰箱');
case '宝宝专用':
return m.targetUser.contains('宝宝');
case '已开封':
return m.isOpened;
case '⚠️ 需处理':
return m.healthStatus == MedicineHealthStatus.expiringSoon ||
m.healthStatus == MedicineHealthStatus.overdueInUse ||
m.healthStatus == MedicineHealthStatus.expired;
case '全部':
default:
return true;
}
}).toList();
}
@override
Widget build(BuildContext context) {
// 统计指标
final totalCount = _medicines.length;
final safeCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.safe).length;
final soonCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length;
final dangerCount = _medicines.where((m) =>
m.healthStatus == MedicineHealthStatus.overdueInUse ||
m.healthStatus == MedicineHealthStatus.expired).length;
final displayList = _filteredMedicines;
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
appBar: AppBar(
title: const Text('家庭智能药箱', style: TextStyle(fontWeight: FontWeight.bold)),
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF0F172A),
elevation: 0.5,
actions: [
IconButton(
icon: _isSyncing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync, color: Color(0xFF2563EB)),
tooltip: '局域网全家同步',
onPressed: _isSyncing ? null : _performSync,
),
IconButton(
icon: const Icon(Icons.qr_code_scanner, color: Color(0xFF2563EB)),
tooltip: '扫码录药',
onPressed: _openScan,
),
],
),
body: Column(
children: [
// 1. 顶部健康看板统计卡片
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
color: Colors.white,
child: Row(
children: [
_buildStatMetric(
label: '在库药品',
count: totalCount,
color: const Color(0xFF334155),
isSelected: _selectedFilter == '全部',
onTap: () => setState(() => _selectedFilter = '全部'),
),
_buildStatMetric(
label: '安全正常',
count: safeCount,
color: const Color(0xFF10B981),
isSelected: false,
onTap: () => setState(() => _selectedFilter = '全部'),
),
_buildStatMetric(
label: '临期预警',
count: soonCount,
color: const Color(0xFFF59E0B),
isSelected: _selectedFilter == '⚠️ 需处理',
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
),
_buildStatMetric(
label: '超期/过期',
count: dangerCount,
color: const Color(0xFFEF4444),
isSelected: _selectedFilter == '⚠️ 需处理',
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
),
],
),
),
// 2. 搜索框与过滤器标签
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: Colors.white,
child: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: '搜索药品名、规格、适应症...',
prefixIcon: const Icon(Icons.search, size: 20, color: Colors.grey),
isDense: true,
filled: true,
fillColor: const Color(0xFFF1F5F9),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(vertical: 8),
),
onChanged: (val) => setState(() => _searchQuery = val.trim()),
),
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: _filters.map((f) {
final selected = _selectedFilter == f;
return Padding(
padding: const EdgeInsets.only(right: 8),
child: ChoiceChip(
label: Text(f),
selected: selected,
selectedColor: const Color(0xFF2563EB),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _selectedFilter = f);
},
),
);
}).toList(),
),
),
],
),
),
// 3. 药品列表
Expanded(
child: displayList.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.inventory_2_outlined, size: 56, color: Colors.grey.shade400),
const SizedBox(height: 12),
Text(
_searchQuery.isNotEmpty ? '没有找到符合的药品' : '药箱里还没有此类药品',
style: TextStyle(color: Colors.grey.shade600),
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _openScan,
icon: const Icon(Icons.qr_code_scanner),
label: const Text('扫描药品条码/追溯码录入'),
),
],
),
)
: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: displayList.length,
itemBuilder: (ctx, idx) {
return _buildMedicineCard(displayList[idx]);
},
),
),
],
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton.small(
heroTag: 'fab_manual',
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF2563EB),
tooltip: '手动添加药品',
onPressed: _addNewMedicine,
child: const Icon(Icons.edit_note),
),
const SizedBox(height: 10),
FloatingActionButton.extended(
heroTag: 'fab_scan',
backgroundColor: const Color(0xFF2563EB),
foregroundColor: Colors.white,
icon: const Icon(Icons.qr_code_scanner),
label: const Text('扫码录药'),
onPressed: _openScan,
),
],
),
);
}
Widget _buildStatMetric({
required String label,
required int count,
required Color color,
required bool isSelected,
required VoidCallback onTap,
}) {
return Expanded(
child: GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
color: isSelected ? color.withValues(alpha: 0.1) : Colors.transparent,
borderRadius: BorderRadius.circular(8),
),
child: Column(
children: [
Text(
count.toString(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 2),
Text(
label,
style: const TextStyle(fontSize: 11, color: Colors.black54),
),
],
),
),
),
);
}
Widget _buildMedicineCard(MedicineItem item) {
final dateFormat = DateFormat('yyyy/MM/dd');
final isDanger = item.healthStatus == MedicineHealthStatus.overdueInUse ||
item.healthStatus == MedicineHealthStatus.expired;
final isWarning = item.healthStatus == MedicineHealthStatus.expiringSoon;
Color borderColor = Colors.grey.shade200;
if (isDanger) borderColor = Colors.red.shade300;
if (isWarning) borderColor = Colors.amber.shade300;
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(color: borderColor, width: isDanger ? 1.5 : 1),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 卡片头部:图标、名称、状态 Badge 与操作菜单
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: item.category.icon == Icons.air
? const Color(0xFFEFF6FF)
: const Color(0xFFF1F5F9),
borderRadius: BorderRadius.circular(10),
),
child: Icon(item.category.icon, color: const Color(0xFF2563EB), size: 22),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFF0F172A),
),
),
if (item.spec.isNotEmpty)
Text(
'规格: ${item.spec}',
style: const TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: item.healthStatusColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(6),
),
child: Text(
item.healthStatusLabel,
style: TextStyle(
color: item.healthStatusColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 20, color: Colors.grey),
onSelected: (val) {
if (val == 'edit') _editMedicine(item);
if (val == 'delete') _deleteMedicine(item);
},
itemBuilder: (ctx) => [
const PopupMenuItem(value: 'edit', child: Text('编辑药品')),
const PopupMenuItem(
value: 'delete',
child: Text('移出药箱', style: TextStyle(color: Colors.red)),
),
],
),
],
),
const SizedBox(height: 10),
// 存放标签与成员胶囊
Wrap(
spacing: 6,
children: [
_buildTagChip(
icon: item.storageLocation.contains('冷藏')
? Icons.ac_unit
: Icons.inventory_2_outlined,
text: item.storageLocation,
color: item.storageLocation.contains('冷藏')
? const Color(0xFF0284C7)
: const Color(0xFF64748B),
),
_buildTagChip(
icon: Icons.person_outline,
text: item.targetUser,
color: const Color(0xFFD97706),
),
if (item.barcode != null && item.barcode!.isNotEmpty)
_buildTagChip(
icon: Icons.qr_code,
text: item.barcode!.length > 13
? '追溯码 ${item.barcode!.substring(0, 6)}...'
: item.barcode!,
color: const Color(0xFF64748B),
),
],
),
const SizedBox(height: 12),
// 出厂保质期与开封情况
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(8),
),
child: Column(
children: [
Row(
children: [
const Icon(Icons.event_outlined, size: 14, color: Colors.black54),
const SizedBox(width: 4),
Text(
'出厂有效期至: ${dateFormat.format(item.expiryDate)}',
style: const TextStyle(fontSize: 12, color: Colors.black87),
),
const Spacer(),
Text(
item.daysUntilExpiry >= 0
? '剩 ${item.daysUntilExpiry} 天'
: '已过期 ${-item.daysUntilExpiry} 天',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: item.daysUntilExpiry <= 30 ? Colors.red : const Color(0xFF059669),
),
),
],
),
// 若已开封
if (item.isOpened && item.openedAt != null) ...[
const SizedBox(height: 6),
Row(
children: [
const Icon(Icons.lock_open, size: 14, color: Color(0xFF2563EB)),
const SizedBox(width: 4),
Text(
'已开封 (${dateFormat.format(item.openedAt!)})',
style: const TextStyle(fontSize: 12, color: Color(0xFF2563EB)),
),
const Spacer(),
if (item.shelfLifeDaysAfterOpening != null) ...[
Text(
(item.daysUntilInUseExpiry ?? 0) >= 0
? '开封保质剩 ${item.daysUntilInUseExpiry} 天'
: '开封超期 ${-(item.daysUntilInUseExpiry ?? 0)} 天',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: (item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.red : const Color(0xFF2563EB),
),
),
],
],
),
if (item.shelfLifeDaysAfterOpening != null) ...[
const SizedBox(height: 6),
LinearProgressIndicator(
value: (item.daysSinceOpened ?? 0) / item.shelfLifeDaysAfterOpening!,
backgroundColor: Colors.grey.shade200,
valueColor: AlwaysStoppedAnimation<Color>(
(item.daysUntilInUseExpiry ?? 0) < 0
? Colors.red
: ((item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.amber : const Color(0xFF2563EB)),
),
minHeight: 4,
borderRadius: BorderRadius.circular(2),
),
],
],
],
),
),
// 未开封一键打卡按钮
if (!item.isOpened) ...[
const SizedBox(height: 10),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF2563EB),
side: const BorderSide(color: Color(0xFF93C5FD)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
padding: const EdgeInsets.symmetric(vertical: 8),
),
onPressed: () => _openMedicineCard(item),
icon: const Icon(Icons.check_circle_outline, size: 16),
label: const Text('点击打卡开封 (开启保质倒计时)'),
),
),
],
// 危险警告提醒条 (超期或过期)
if (isDanger) ...[
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFFEF2F2),
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
const Icon(Icons.warning_amber_rounded, size: 16, color: Colors.red),
const SizedBox(width: 6),
Expanded(
child: Text(
item.healthStatus == MedicineHealthStatus.overdueInUse
? '已超出开封后推荐使用期限,易滋生细菌/失效,建议丢弃更换。'
: '已超出出厂有效期,严禁继续使用!',
style: const TextStyle(color: Colors.red, fontSize: 11, fontWeight: FontWeight.w600),
),
),
],
),
),
],
// 适应症备注
if (item.notes.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
'备忘: ${item.notes}',
style: const TextStyle(fontSize: 11, color: Colors.black54),
),
],
],
),
),
);
}
Widget _buildTagChip({
required IconData icon,
required String text,
required Color color,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 12, color: color),
const SizedBox(width: 3),
Text(
text,
style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.w500),
),
],
),
);
}
}
+589
View File
@@ -0,0 +1,589 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import '../models/medicine_item.dart';
import '../services/medicine_parser_service.dart';
class MedicineEditDialog extends StatefulWidget {
final MedicineItem? initialItem;
final ScannedMedicineInfo? scannedInfo;
const MedicineEditDialog({
super.key,
this.initialItem,
this.scannedInfo,
});
@override
State<MedicineEditDialog> createState() => _MedicineEditDialogState();
}
class _MedicineEditDialogState extends State<MedicineEditDialog> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _nameController;
late TextEditingController _specController;
late TextEditingController _barcodeController;
late TextEditingController _batchNumberController;
late TextEditingController _shelfLifeDaysController;
late TextEditingController _notesController;
late MedicineCategory _category;
late String _storageLocation;
late String _targetUser;
late DateTime _expiryDate;
DateTime? _productionDate;
late bool _isOpened;
DateTime? _openedAt;
final List<String> _commonLocations = [
'常温药箱',
'冰箱冷藏 (2-8℃)',
'随身急救包',
'卧室床头',
];
final List<String> _commonUsers = [
'宝宝',
'全家',
'爸爸',
'妈妈',
'老人',
];
@override
void initState() {
super.initState();
final init = widget.initialItem;
final scan = widget.scannedInfo;
final now = DateTime.now();
_nameController = TextEditingController(
text: init?.name ?? scan?.name ?? '',
);
_specController = TextEditingController(
text: init?.spec ?? scan?.spec ?? '',
);
_barcodeController = TextEditingController(
text: init?.barcode ?? scan?.barcode ?? '',
);
_batchNumberController = TextEditingController(
text: init?.batchNumber ?? scan?.batchNumber ?? '',
);
_category = init?.category ?? scan?.category ?? MedicineCategory.oralLiquid;
_storageLocation = init?.storageLocation ?? scan?.storageLocation ?? '常温药箱';
_targetUser = init?.targetUser ?? scan?.targetUser ?? '宝宝';
_expiryDate = init?.expiryDate ??
scan?.expiryDate ??
DateTime(now.year + 2, now.month, now.day);
_productionDate = init?.productionDate ?? scan?.productionDate;
final defaultShelfLife = _category.defaultShelfLifeDaysAfterOpening;
final initShelfLife = init?.shelfLifeDaysAfterOpening ??
scan?.shelfLifeDaysAfterOpening ??
defaultShelfLife;
_shelfLifeDaysController = TextEditingController(
text: initShelfLife != null ? initShelfLife.toString() : '',
);
_isOpened = init?.isOpened ?? false;
_openedAt = init?.openedAt ?? (_isOpened ? now : null);
_notesController = TextEditingController(
text: init?.notes ?? scan?.notes ?? '',
);
}
@override
void dispose() {
_nameController.dispose();
_specController.dispose();
_barcodeController.dispose();
_batchNumberController.dispose();
_shelfLifeDaysController.dispose();
_notesController.dispose();
super.dispose();
}
void _onCategoryChanged(MedicineCategory newCat) {
setState(() {
_category = newCat;
final defaultDays = newCat.defaultShelfLifeDaysAfterOpening;
if (defaultDays != null && _shelfLifeDaysController.text.isEmpty) {
_shelfLifeDaysController.text = defaultDays.toString();
}
});
}
Future<void> _pickExpiryDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _expiryDate,
firstDate: DateTime(2020),
lastDate: DateTime(2035),
helpText: '选择药品出厂有效期至',
);
if (picked != null) {
setState(() => _expiryDate = picked);
}
}
Future<void> _pickProductionDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _productionDate ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now(),
helpText: '选择药品生产日期 (选填)',
);
if (picked != null) {
setState(() => _productionDate = picked);
}
}
Future<void> _pickOpenedDate() async {
final picked = await showDatePicker(
context: context,
initialDate: _openedAt ?? DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now(),
helpText: '选择开封日期',
);
if (picked != null) {
setState(() => _openedAt = picked);
}
}
void _save() {
if (!_formKey.currentState!.validate()) return;
final nowUtc = DateTime.now().toUtc();
final shelfLife = int.tryParse(_shelfLifeDaysController.text.trim());
final item = MedicineItem(
id: widget.initialItem?.id ?? const Uuid().v4(),
name: _nameController.text.trim(),
category: _category,
spec: _specController.text.trim(),
storageLocation: _storageLocation,
targetUser: _targetUser,
barcode: _barcodeController.text.trim().isNotEmpty ? _barcodeController.text.trim() : null,
batchNumber: _batchNumberController.text.trim().isNotEmpty ? _batchNumberController.text.trim() : null,
productionDate: _productionDate,
expiryDate: _expiryDate,
shelfLifeDaysAfterOpening: shelfLife,
isOpened: _isOpened,
openedAt: _isOpened ? (_openedAt ?? DateTime.now()) : null,
openedByDevice: widget.initialItem?.openedByDevice,
notes: _notesController.text.trim(),
isDeleted: false,
updatedAt: nowUtc,
);
Navigator.of(context).pop(item);
}
@override
Widget build(BuildContext context) {
final isEditing = widget.initialItem != null;
final dateFormat = DateFormat('yyyy年MM月dd日');
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
child: Container(
constraints: const BoxConstraints(maxWidth: 520, maxHeight: 720),
child: Column(
children: [
// 标题栏
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
decoration: const BoxDecoration(
color: Color(0xFF2563EB),
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Row(
children: [
Icon(
isEditing ? Icons.edit_note : Icons.add_circle_outline,
color: Colors.white,
),
const SizedBox(width: 10),
Text(
isEditing ? '编辑家庭药品' : '录入新药品',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white70),
onPressed: () => Navigator.pop(context),
),
],
),
),
// 表单内容
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 1. 药品名称
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: '药品名称 *',
hintText: '如 美林 (布洛芬混悬液)',
prefixIcon: Icon(Icons.medication),
border: OutlineInputBorder(),
),
validator: (v) => (v == null || v.trim().isEmpty) ? '请输入药品名称' : null,
),
const SizedBox(height: 16),
// 2. 剂型类别
const Text(
'剂型类别 (自动联动开封保质天数):',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 6,
children: MedicineCategory.values.map((cat) {
final selected = _category == cat;
return ChoiceChip(
label: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(cat.icon, size: 16, color: selected ? Colors.white : Colors.black87),
const SizedBox(width: 4),
Text(cat.label),
],
),
selected: selected,
selectedColor: const Color(0xFF2563EB),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) _onCategoryChanged(cat);
},
);
}).toList(),
),
const SizedBox(height: 16),
// 3. 规格与条码
Row(
children: [
Expanded(
child: TextFormField(
controller: _specController,
decoration: const InputDecoration(
labelText: '规格/容量',
hintText: '如 100ml / 60喷',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
controller: _barcodeController,
decoration: const InputDecoration(
labelText: '条码/追溯码',
hintText: '69码或20位码',
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 16),
// 4. 存放位置
const Text(
'存放位置:',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _commonLocations.map((loc) {
final selected = _storageLocation == loc;
return ChoiceChip(
label: Text(loc),
selected: selected,
selectedColor: const Color(0xFF059669),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _storageLocation = loc);
},
);
}).toList(),
),
const SizedBox(height: 16),
// 5. 适用成员
const Text(
'适用成员:',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: _commonUsers.map((user) {
final selected = _targetUser == user;
return ChoiceChip(
label: Text(user),
selected: selected,
selectedColor: const Color(0xFFD97706),
labelStyle: TextStyle(
color: selected ? Colors.white : Colors.black87,
fontSize: 12,
),
onSelected: (val) {
if (val) setState(() => _targetUser = user);
},
);
}).toList(),
),
const SizedBox(height: 20),
const Divider(),
const SizedBox(height: 10),
// 6. 出厂有效期至 (核心)
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'出厂有效期至 *',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
const SizedBox(height: 4),
InkWell(
onTap: _pickExpiryDate,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.event, color: Color(0xFF2563EB), size: 18),
const SizedBox(width: 8),
Text(
dateFormat.format(_expiryDate),
style: const TextStyle(fontWeight: FontWeight.w600),
),
],
),
),
),
],
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'生产日期 (选填)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
),
const SizedBox(height: 4),
InkWell(
onTap: _pickProductionDate,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.calendar_today_outlined, size: 16, color: Colors.grey),
const SizedBox(width: 8),
Text(
_productionDate != null
? dateFormat.format(_productionDate!)
: '点击选填',
style: TextStyle(
color: _productionDate != null ? Colors.black87 : Colors.grey,
),
),
],
),
),
),
],
),
),
],
),
const SizedBox(height: 16),
// 7. 生产批号与开封后保质期
Row(
children: [
Expanded(
child: TextFormField(
controller: _batchNumberController,
decoration: const InputDecoration(
labelText: '生产批号 (选填)',
hintText: '如 LOT A123',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
controller: _shelfLifeDaysController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '开封后可用天数',
hintText: '如 28 或 60',
suffixText: '天',
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 16),
// 8. 是否已开封打卡
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _isOpened ? const Color(0xFFEFF6FF) : const Color(0xFFF8FAFC),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: _isOpened ? const Color(0xFF93C5FD) : Colors.grey.shade300,
),
),
child: Column(
children: [
Row(
children: [
Icon(
_isOpened ? Icons.lock_open : Icons.lock_outline,
color: _isOpened ? const Color(0xFF2563EB) : Colors.grey,
),
const SizedBox(width: 8),
const Text(
'当前是否已开封使用:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const Spacer(),
Switch(
value: _isOpened,
activeTrackColor: const Color(0xFF2563EB),
onChanged: (val) {
setState(() {
_isOpened = val;
if (val && _openedAt == null) {
_openedAt = DateTime.now();
}
});
},
),
],
),
if (_isOpened) ...[
const Divider(),
Row(
children: [
const Text('开封日期:', style: TextStyle(fontSize: 13)),
const Spacer(),
TextButton.icon(
onPressed: _pickOpenedDate,
icon: const Icon(Icons.edit_calendar, size: 16),
label: Text(
_openedAt != null ? dateFormat.format(_openedAt!) : '今天',
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
],
],
),
),
const SizedBox(height: 16),
// 9. 用药备注
TextFormField(
controller: _notesController,
maxLines: 2,
decoration: const InputDecoration(
labelText: '适应症/用药备忘',
hintText: '如:38.5℃以上发热使用,间隔4~6小时',
border: OutlineInputBorder(),
),
),
],
),
),
),
),
// 底部操作按钮
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration(
color: Colors.grey.shade50,
border: Border(top: BorderSide(color: Colors.grey.shade200)),
borderRadius: const BorderRadius.vertical(bottom: Radius.circular(20)),
),
child: Row(
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Colors.grey)),
),
const Spacer(),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2563EB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
onPressed: _save,
icon: const Icon(Icons.check),
label: Text(isEditing ? '保存修改' : '确认录入'),
),
],
),
),
],
),
),
);
}
}
+241
View File
@@ -0,0 +1,241 @@
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../services/medicine_parser_service.dart';
class MedicineScanScreen extends StatefulWidget {
const MedicineScanScreen({super.key});
@override
State<MedicineScanScreen> createState() => _MedicineScanScreenState();
}
class _MedicineScanScreenState extends State<MedicineScanScreen> {
final MobileScannerController _controller = MobileScannerController(
detectionSpeed: DetectionSpeed.normal,
facing: CameraFacing.back,
torchEnabled: false,
);
bool _isProcessing = false;
bool _isTorchOn = false;
final TextEditingController _manualInputController = TextEditingController();
@override
void dispose() {
_controller.dispose();
_manualInputController.dispose();
super.dispose();
}
Future<void> _handleBarcodeDetected(String rawCode) async {
if (_isProcessing) return;
setState(() => _isProcessing = true);
try {
final info = await MedicineParserService.parseRawBarcode(rawCode);
if (mounted) {
Navigator.of(context).pop(info);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('解析条码失败: $e')),
);
setState(() => _isProcessing = false);
}
}
}
void _showManualInputDialog() {
_manualInputController.clear();
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('手动输入条形码/追溯码'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'支持输入 13 位商品条形码 (如 69...) 或 20 位中国药品电子监管码:',
style: TextStyle(fontSize: 13, color: Colors.black54),
),
const SizedBox(height: 12),
TextField(
controller: _manualInputController,
keyboardType: TextInputType.number,
autofocus: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: '如 6921147600010 或 8188...',
labelText: '条码编号',
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('取消'),
),
ElevatedButton(
onPressed: () {
final text = _manualInputController.text.trim();
if (text.isNotEmpty) {
Navigator.pop(ctx);
_handleBarcodeDetected(text);
}
},
child: const Text('识别'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
title: const Text('扫描药品条码/追溯码'),
backgroundColor: Colors.black87,
foregroundColor: Colors.white,
actions: [
IconButton(
icon: Icon(
_isTorchOn ? Icons.flash_on : Icons.flash_off,
color: _isTorchOn ? Colors.amber : Colors.white,
),
tooltip: '开关手电筒',
onPressed: () {
setState(() => _isTorchOn = !_isTorchOn);
_controller.toggleTorch();
},
),
IconButton(
icon: const Icon(Icons.keyboard_outlined),
tooltip: '手动输入条码',
onPressed: _showManualInputDialog,
),
],
),
body: Stack(
alignment: Alignment.center,
children: [
MobileScanner(
controller: _controller,
onDetect: (capture) {
final barcodes = capture.barcodes;
for (final barcode in barcodes) {
final val = barcode.rawValue;
if (val != null && val.isNotEmpty) {
_handleBarcodeDetected(val);
break;
}
}
},
errorBuilder: (context, error) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.camera_alt_outlined, color: Colors.white54, size: 64),
const SizedBox(height: 16),
Text(
'无法打开摄像头: ${error.errorDetails?.message ?? "无权限或设备不支持"}',
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70),
),
const SizedBox(height: 20),
ElevatedButton.icon(
icon: const Icon(Icons.edit_note),
label: const Text('手动输入条形码'),
onPressed: _showManualInputDialog,
),
],
),
),
);
},
),
// 扫描取景框覆盖层
IgnorePointer(
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.white24, width: 1),
),
child: Stack(
children: [
Center(
child: Container(
width: 280,
height: 200,
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFF2563EB), width: 2.5),
borderRadius: BorderRadius.circular(16),
),
),
),
],
),
),
),
// 底部操作引导提示
Positioned(
bottom: 40,
left: 20,
right: 20,
child: Column(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(20),
),
child: const Text(
'请将药盒上的【20位追溯码】或【条形码】对准框内',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 13),
),
),
const SizedBox(height: 12),
TextButton.icon(
onPressed: _showManualInputDialog,
icon: const Icon(Icons.edit, color: Colors.white70, size: 16),
label: const Text(
'扫不出来?点击手动输入',
style: TextStyle(color: Colors.white70, fontSize: 13),
),
),
],
),
),
if (_isProcessing)
Container(
color: Colors.black54,
child: const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(color: Colors.white),
SizedBox(height: 16),
Text(
'正在查询药品信息...',
style: TextStyle(color: Colors.white, fontSize: 14),
),
],
),
),
),
],
),
);
}
}