mirror of
https://github.com/vleeuwenmenno/supplements.git
synced 2025-12-08 14:05:56 +00:00
Compare commits
9 Commits
v1.0.7+300
...
5684a197e7
| Author | SHA1 | Date | |
|---|---|---|---|
|
5684a197e7
|
|||
|
7828e48d9d
|
|||
|
99711d56ec
|
|||
|
6bd80780e6
|
|||
|
7c63eb473b
|
|||
|
666008f05d
|
|||
|
6a2085f4e6
|
|||
|
62debb6a7c
|
|||
|
f7966ce587
|
14
.kilocode/mcp.json
Normal file
14
.kilocode/mcp.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"context7": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": [
|
||||||
|
"-y",
|
||||||
|
"@upstash/context7-mcp"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"DEFAULT_MINIMUM_TOKENS": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,35 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // Import this
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||||
import 'package:supplements/logging.dart';
|
import 'package:supplements/logging.dart';
|
||||||
|
|
||||||
import 'providers/settings_provider.dart';
|
import 'providers/settings_provider.dart';
|
||||||
import 'providers/simple_sync_provider.dart';
|
import 'providers/simple_sync_provider.dart';
|
||||||
import 'providers/supplement_provider.dart';
|
import 'providers/supplement_provider.dart';
|
||||||
import 'screens/home_screen.dart';
|
import 'screens/home_screen.dart';
|
||||||
import 'screens/profile_setup_screen.dart';
|
|
||||||
import 'services/notification_router.dart';
|
import 'services/notification_router.dart';
|
||||||
import 'services/simple_notification_service.dart';
|
import 'services/simple_notification_service.dart';
|
||||||
|
|
||||||
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||||
|
|
||||||
|
// Top-level function to handle notification responses in the background
|
||||||
|
@pragma('vm:entry-point')
|
||||||
|
void notificationTapBackground(NotificationResponse notificationResponse) {
|
||||||
|
// handle action here
|
||||||
|
printLog('Background notification action tapped: ${notificationResponse.actionId}');
|
||||||
|
NotificationRouter.instance.handleNotificationResponse(notificationResponse);
|
||||||
|
}
|
||||||
|
|
||||||
void main() async {
|
void main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
// Initialize SimpleNotificationService early
|
||||||
|
await SimpleNotificationService.instance.initialize(
|
||||||
|
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
|
||||||
|
);
|
||||||
|
|
||||||
final settingsProvider = SettingsProvider();
|
final settingsProvider = SettingsProvider();
|
||||||
await settingsProvider.initialize();
|
await settingsProvider.initialize();
|
||||||
|
|
||||||
@@ -31,7 +46,7 @@ class MyApp extends StatelessWidget {
|
|||||||
return MultiProvider(
|
return MultiProvider(
|
||||||
providers: [
|
providers: [
|
||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider(
|
||||||
create: (context) => SupplementProvider()..initialize(),
|
create: (context) => SupplementProvider()..initialize(context),
|
||||||
),
|
),
|
||||||
ChangeNotifierProvider.value(
|
ChangeNotifierProvider.value(
|
||||||
value: settingsProvider,
|
value: settingsProvider,
|
||||||
@@ -48,9 +63,11 @@ class MyApp extends StatelessWidget {
|
|||||||
final supplementProvider = context.read<SupplementProvider>();
|
final supplementProvider = context.read<SupplementProvider>();
|
||||||
|
|
||||||
// Initialize notification router with the app's navigator
|
// Initialize notification router with the app's navigator
|
||||||
|
// This is done here because navigatorKey is only available after MaterialApp is built
|
||||||
NotificationRouter.instance.initialize(navigatorKey);
|
NotificationRouter.instance.initialize(navigatorKey);
|
||||||
|
|
||||||
// If the app was launched via a notification, route to the proper dialog
|
// If the app was launched via a notification, route to the proper dialog
|
||||||
|
// This needs to be called after the router is initialized with the navigatorKey
|
||||||
SimpleNotificationService.instance.getLaunchDetails().then((details) {
|
SimpleNotificationService.instance.getLaunchDetails().then((details) {
|
||||||
NotificationRouter.instance.handleAppLaunchDetails(details);
|
NotificationRouter.instance.handleAppLaunchDetails(details);
|
||||||
});
|
});
|
||||||
@@ -76,27 +93,19 @@ class MyApp extends StatelessWidget {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return MaterialApp(
|
return ShadApp(
|
||||||
navigatorKey: navigatorKey,
|
navigatorKey: navigatorKey,
|
||||||
title: 'Supplements Tracker',
|
title: 'Supplements Tracker',
|
||||||
theme: ThemeData(
|
theme: ShadThemeData(
|
||||||
colorScheme: ColorScheme.fromSeed(
|
|
||||||
seedColor: Colors.blue,
|
|
||||||
brightness: Brightness.light,
|
brightness: Brightness.light,
|
||||||
|
colorScheme: const ShadZincColorScheme.light(),
|
||||||
),
|
),
|
||||||
useMaterial3: true,
|
darkTheme: ShadThemeData(
|
||||||
),
|
|
||||||
darkTheme: ThemeData(
|
|
||||||
colorScheme: ColorScheme.fromSeed(
|
|
||||||
seedColor: Colors.blue,
|
|
||||||
brightness: Brightness.dark,
|
brightness: Brightness.dark,
|
||||||
),
|
colorScheme: const ShadZincColorScheme.dark(),
|
||||||
useMaterial3: true,
|
|
||||||
),
|
),
|
||||||
themeMode: settingsProvider.themeMode,
|
themeMode: settingsProvider.themeMode,
|
||||||
home: (settingsProvider.age == null || settingsProvider.gender == null)
|
home: const HomeScreen(),
|
||||||
? const ProfileSetupScreen()
|
|
||||||
: const HomeScreen(),
|
|
||||||
debugShowCheckedModeBanner: false,
|
debugShowCheckedModeBanner: false,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,10 +10,6 @@ enum ThemeOption {
|
|||||||
class SettingsProvider extends ChangeNotifier {
|
class SettingsProvider extends ChangeNotifier {
|
||||||
ThemeOption _themeOption = ThemeOption.system;
|
ThemeOption _themeOption = ThemeOption.system;
|
||||||
|
|
||||||
// Profile fields
|
|
||||||
DateTime? _dateOfBirth;
|
|
||||||
String? _gender;
|
|
||||||
|
|
||||||
// Time range settings (stored as hours, 0-23)
|
// Time range settings (stored as hours, 0-23)
|
||||||
int _morningStart = 5;
|
int _morningStart = 5;
|
||||||
int _morningEnd = 10;
|
int _morningEnd = 10;
|
||||||
@@ -24,7 +20,13 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
int _nightStart = 23;
|
int _nightStart = 23;
|
||||||
int _nightEnd = 4;
|
int _nightEnd = 4;
|
||||||
|
|
||||||
|
// Notifications
|
||||||
|
int _snoozeMinutes = 10;
|
||||||
|
|
||||||
|
// Notification retry settings
|
||||||
|
bool _notificationRetryEnabled = true;
|
||||||
|
int _notificationRetryCount = 3;
|
||||||
|
int _notificationRetryDelayMinutes = 5;
|
||||||
|
|
||||||
// Auto-sync settings
|
// Auto-sync settings
|
||||||
bool _autoSyncEnabled = false;
|
bool _autoSyncEnabled = false;
|
||||||
@@ -32,19 +34,6 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
|
|
||||||
ThemeOption get themeOption => _themeOption;
|
ThemeOption get themeOption => _themeOption;
|
||||||
|
|
||||||
// Profile getters
|
|
||||||
DateTime? get dateOfBirth => _dateOfBirth;
|
|
||||||
String? get gender => _gender;
|
|
||||||
int? get age {
|
|
||||||
if (_dateOfBirth == null) return null;
|
|
||||||
final now = DateTime.now();
|
|
||||||
int years = now.year - _dateOfBirth!.year;
|
|
||||||
final hasHadBirthday = (now.month > _dateOfBirth!.month) ||
|
|
||||||
(now.month == _dateOfBirth!.month && now.day >= _dateOfBirth!.day);
|
|
||||||
if (!hasHadBirthday) years--;
|
|
||||||
return years;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Time range getters
|
// Time range getters
|
||||||
int get morningStart => _morningStart;
|
int get morningStart => _morningStart;
|
||||||
int get morningEnd => _morningEnd;
|
int get morningEnd => _morningEnd;
|
||||||
@@ -55,7 +44,13 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
int get nightStart => _nightStart;
|
int get nightStart => _nightStart;
|
||||||
int get nightEnd => _nightEnd;
|
int get nightEnd => _nightEnd;
|
||||||
|
|
||||||
|
// Notifications
|
||||||
|
int get snoozeMinutes => _snoozeMinutes;
|
||||||
|
|
||||||
|
// Notification retry getters
|
||||||
|
bool get notificationRetryEnabled => _notificationRetryEnabled;
|
||||||
|
int get notificationRetryCount => _notificationRetryCount;
|
||||||
|
int get notificationRetryDelayMinutes => _notificationRetryDelayMinutes;
|
||||||
|
|
||||||
// Auto-sync getters
|
// Auto-sync getters
|
||||||
bool get autoSyncEnabled => _autoSyncEnabled;
|
bool get autoSyncEnabled => _autoSyncEnabled;
|
||||||
@@ -87,13 +82,6 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
final themeIndex = prefs.getInt('theme_option') ?? 0;
|
final themeIndex = prefs.getInt('theme_option') ?? 0;
|
||||||
_themeOption = ThemeOption.values[themeIndex];
|
_themeOption = ThemeOption.values[themeIndex];
|
||||||
|
|
||||||
// Load profile fields
|
|
||||||
final dobString = prefs.getString('date_of_birth');
|
|
||||||
if (dobString != null) {
|
|
||||||
_dateOfBirth = DateTime.tryParse(dobString);
|
|
||||||
}
|
|
||||||
_gender = prefs.getString('gender');
|
|
||||||
|
|
||||||
// Load time range settings
|
// Load time range settings
|
||||||
_morningStart = prefs.getInt('morning_start') ?? 5;
|
_morningStart = prefs.getInt('morning_start') ?? 5;
|
||||||
_morningEnd = prefs.getInt('morning_end') ?? 10;
|
_morningEnd = prefs.getInt('morning_end') ?? 10;
|
||||||
@@ -104,7 +92,13 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
_nightStart = prefs.getInt('night_start') ?? 23;
|
_nightStart = prefs.getInt('night_start') ?? 23;
|
||||||
_nightEnd = prefs.getInt('night_end') ?? 4;
|
_nightEnd = prefs.getInt('night_end') ?? 4;
|
||||||
|
|
||||||
|
// Load snooze setting
|
||||||
|
_snoozeMinutes = prefs.getInt('snooze_minutes') ?? 10;
|
||||||
|
|
||||||
|
// Load notification retry settings
|
||||||
|
_notificationRetryEnabled = prefs.getBool('notification_retry_enabled') ?? true;
|
||||||
|
_notificationRetryCount = prefs.getInt('notification_retry_count') ?? 3;
|
||||||
|
_notificationRetryDelayMinutes = prefs.getInt('notification_retry_delay_minutes') ?? 5;
|
||||||
|
|
||||||
// Load auto-sync settings
|
// Load auto-sync settings
|
||||||
_autoSyncEnabled = prefs.getBool('auto_sync_enabled') ?? false;
|
_autoSyncEnabled = prefs.getBool('auto_sync_enabled') ?? false;
|
||||||
@@ -122,8 +116,6 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> setDateOfBirthAndGender(DateTime dateOfBirth, String gender) async {
|
Future<void> setDateOfBirthAndGender(DateTime dateOfBirth, String gender) async {
|
||||||
_dateOfBirth = dateOfBirth;
|
|
||||||
_gender = gender;
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
@@ -269,7 +261,49 @@ class SettingsProvider extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Notifications setters
|
||||||
|
Future<void> setSnoozeMinutes(int minutes) async {
|
||||||
|
const allowed = [5, 10, 15, 20];
|
||||||
|
if (!allowed.contains(minutes)) {
|
||||||
|
throw ArgumentError('Snooze minutes must be one of ${allowed.join(", ")}');
|
||||||
|
}
|
||||||
|
_snoozeMinutes = minutes;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setInt('snooze_minutes', minutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setNotificationRetryEnabled(bool enabled) async {
|
||||||
|
_notificationRetryEnabled = enabled;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool('notification_retry_enabled', enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setNotificationRetryCount(int count) async {
|
||||||
|
if (count < 0 || count > 10) {
|
||||||
|
throw ArgumentError('Retry count must be between 0 and 10');
|
||||||
|
}
|
||||||
|
_notificationRetryCount = count;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setInt('notification_retry_count', count);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setNotificationRetryDelayMinutes(int minutes) async {
|
||||||
|
const allowed = [1, 2, 3, 5, 10, 15, 20, 30];
|
||||||
|
if (!allowed.contains(minutes)) {
|
||||||
|
throw ArgumentError('Retry delay must be one of ${allowed.join(", ")} minutes');
|
||||||
|
}
|
||||||
|
_notificationRetryDelayMinutes = minutes;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setInt('notification_retry_delay_minutes', minutes);
|
||||||
|
}
|
||||||
|
|
||||||
// Auto-sync setters
|
// Auto-sync setters
|
||||||
Future<void> setAutoSyncEnabled(bool enabled) async {
|
Future<void> setAutoSyncEnabled(bool enabled) async {
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ import 'dart:async';
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
import 'package:supplements/logging.dart';
|
import 'package:supplements/logging.dart';
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../models/supplement_intake.dart';
|
import '../models/supplement_intake.dart';
|
||||||
|
import '../providers/settings_provider.dart';
|
||||||
import '../services/database_helper.dart';
|
import '../services/database_helper.dart';
|
||||||
import '../services/database_sync_service.dart';
|
import '../services/database_sync_service.dart';
|
||||||
import '../services/simple_notification_service.dart';
|
import '../services/simple_notification_service.dart';
|
||||||
@@ -27,6 +29,9 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
// Callback for triggering sync when data changes
|
// Callback for triggering sync when data changes
|
||||||
VoidCallback? _onDataChanged;
|
VoidCallback? _onDataChanged;
|
||||||
|
|
||||||
|
// Context for accessing other providers
|
||||||
|
BuildContext? _context;
|
||||||
|
|
||||||
List<Supplement> get supplements => _supplements;
|
List<Supplement> get supplements => _supplements;
|
||||||
List<Map<String, dynamic>> get todayIntakes => _todayIntakes;
|
List<Map<String, dynamic>> get todayIntakes => _todayIntakes;
|
||||||
List<Map<String, dynamic>> get monthlyIntakes => _monthlyIntakes;
|
List<Map<String, dynamic>> get monthlyIntakes => _monthlyIntakes;
|
||||||
@@ -42,11 +47,12 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
_onDataChanged?.call();
|
_onDataChanged?.call();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> initialize() async {
|
Future<void> initialize([BuildContext? context]) async {
|
||||||
if (_initialized) {
|
if (_initialized) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_initialized = true;
|
_initialized = true;
|
||||||
|
_context = context;
|
||||||
|
|
||||||
// Add this provider as an observer for app lifecycle changes
|
// Add this provider as an observer for app lifecycle changes
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
@@ -87,7 +93,7 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
|
|
||||||
if (currentDate != lastCheckDate) {
|
if (currentDate != lastCheckDate) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
printLog('Date changed detected: ${lastCheckDate} -> ${currentDate}');
|
printLog('Date changed detected: $lastCheckDate -> $currentDate');
|
||||||
printLog('Refreshing today\'s intakes for new day...');
|
printLog('Refreshing today\'s intakes for new day...');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,7 +141,21 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await _notificationService.scheduleDailyGroupedRemindersSafe(_supplements);
|
SettingsProvider? settingsProvider;
|
||||||
|
if (_context != null && _context!.mounted) {
|
||||||
|
try {
|
||||||
|
settingsProvider = Provider.of<SettingsProvider>(_context!, listen: false);
|
||||||
|
} catch (e) {
|
||||||
|
if (kDebugMode) {
|
||||||
|
printLog('📱 Could not access SettingsProvider: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await _notificationService.scheduleDailyGroupedRemindersSafe(
|
||||||
|
_supplements,
|
||||||
|
settingsProvider: settingsProvider,
|
||||||
|
);
|
||||||
await _notificationService.getPendingNotifications();
|
await _notificationService.getPendingNotifications();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
@@ -175,9 +195,6 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
printLog('Adding supplement: ${supplement.name}');
|
printLog('Adding supplement: ${supplement.name}');
|
||||||
final id = await _databaseHelper.insertSupplement(supplement);
|
final id = await _databaseHelper.insertSupplement(supplement);
|
||||||
printLog('Supplement inserted with ID: $id');
|
printLog('Supplement inserted with ID: $id');
|
||||||
final newSupplement = supplement.copyWith(id: id);
|
|
||||||
|
|
||||||
// Notifications will be rescheduled in grouped mode after reloading supplements
|
|
||||||
|
|
||||||
await loadSupplements();
|
await loadSupplements();
|
||||||
printLog('Supplements reloaded, count: ${_supplements.length}');
|
printLog('Supplements reloaded, count: ${_supplements.length}');
|
||||||
@@ -370,6 +387,24 @@ class SupplementProvider with ChangeNotifier, WidgetsBindingObserver {
|
|||||||
return _todayIntakes.where((intake) => intake['supplement_id'] == supplementId).length;
|
return _todayIntakes.where((intake) => intake['supplement_id'] == supplementId).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the most recent intake for a supplement today
|
||||||
|
Map<String, dynamic>? getMostRecentIntake(int supplementId) {
|
||||||
|
final supplementIntakes = _todayIntakes
|
||||||
|
.where((intake) => intake['supplement_id'] == supplementId)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
if (supplementIntakes.isEmpty) return null;
|
||||||
|
|
||||||
|
// Sort by takenAt time (most recent first)
|
||||||
|
supplementIntakes.sort((a, b) {
|
||||||
|
final aTime = DateTime.parse(a['takenAt']);
|
||||||
|
final bTime = DateTime.parse(b['takenAt']);
|
||||||
|
return bTime.compareTo(aTime); // Descending order
|
||||||
|
});
|
||||||
|
|
||||||
|
return supplementIntakes.first;
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, double> get dailyIngredientIntake {
|
Map<String, double> get dailyIngredientIntake {
|
||||||
final Map<String, double> ingredientIntake = {};
|
final Map<String, double> ingredientIntake = {};
|
||||||
|
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
Expanded(
|
Expanded(
|
||||||
flex: 1,
|
flex: 1,
|
||||||
child: DropdownButtonFormField<String>(
|
child: DropdownButtonFormField<String>(
|
||||||
value: controller.selectedUnit,
|
initialValue: controller.selectedUnit,
|
||||||
decoration: const InputDecoration(
|
decoration: const InputDecoration(
|
||||||
labelText: 'Unit',
|
labelText: 'Unit',
|
||||||
border: OutlineInputBorder(),
|
border: OutlineInputBorder(),
|
||||||
@@ -317,7 +317,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
Expanded(
|
Expanded(
|
||||||
flex: 1,
|
flex: 1,
|
||||||
child: DropdownButtonFormField<String>(
|
child: DropdownButtonFormField<String>(
|
||||||
value: _selectedUnitType,
|
initialValue: _selectedUnitType,
|
||||||
decoration: const InputDecoration(
|
decoration: const InputDecoration(
|
||||||
labelText: 'Type',
|
labelText: 'Type',
|
||||||
border: OutlineInputBorder(),
|
border: OutlineInputBorder(),
|
||||||
@@ -342,7 +342,7 @@ class _AddSupplementScreenState extends State<AddSupplementScreen> {
|
|||||||
// Show ingredients summary
|
// Show ingredients summary
|
||||||
if (_ingredientControllers.isNotEmpty && _ingredientControllers.any((c) => c.nameController.text.isNotEmpty && (double.tryParse(c.amountController.text) ?? 0) > 0))
|
if (_ingredientControllers.isNotEmpty && _ingredientControllers.any((c) => c.nameController.text.isNotEmpty && (double.tryParse(c.amountController.text) ?? 0) > 0))
|
||||||
Card(
|
Card(
|
||||||
color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
|
color: Theme.of(context).colorScheme.primaryContainer.withValues(alpha: 0.3),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
child: Column(
|
child: Column(
|
||||||
|
|||||||
@@ -164,9 +164,9 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
child: Container(
|
child: Container(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(16),
|
borderRadius: BorderRadius.circular(16),
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
|
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
|
||||||
border: Border.all(
|
border: Border.all(
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.2),
|
||||||
width: 1,
|
width: 1,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -180,7 +180,7 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.all(8),
|
padding: const EdgeInsets.all(8),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.1),
|
||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
),
|
),
|
||||||
child: Icon(
|
child: Icon(
|
||||||
@@ -262,7 +262,7 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
|
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -284,7 +284,7 @@ class _ArchivedSupplementCard extends StatelessWidget {
|
|||||||
return Container(
|
return Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.1),
|
||||||
borderRadius: BorderRadius.circular(6),
|
borderRadius: BorderRadius.circular(6),
|
||||||
),
|
),
|
||||||
child: Text(
|
child: Text(
|
||||||
|
|||||||
415
lib/screens/debug_notifications_screen.dart
Normal file
415
lib/screens/debug_notifications_screen.dart
Normal file
@@ -0,0 +1,415 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:supplements/providers/supplement_provider.dart';
|
||||||
|
import 'package:supplements/services/notification_debug_store.dart';
|
||||||
|
import 'package:supplements/services/simple_notification_service.dart';
|
||||||
|
|
||||||
|
class DebugNotificationsScreen extends StatefulWidget {
|
||||||
|
const DebugNotificationsScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DebugNotificationsScreen> createState() => _DebugNotificationsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DebugNotificationsScreenState extends State<DebugNotificationsScreen> {
|
||||||
|
bool _loading = true;
|
||||||
|
List<PendingNotificationRequest> _pending = const [];
|
||||||
|
List<NotificationLogEntry> _logEntries = const [];
|
||||||
|
final Map<int, String> _supplementNameCache = {};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch pending from plugin
|
||||||
|
final pending = await SimpleNotificationService.instance.getPendingNotifications();
|
||||||
|
|
||||||
|
// Fetch log from local store
|
||||||
|
final logs = await NotificationDebugStore.instance.getAll();
|
||||||
|
|
||||||
|
// Optionally resolve supplement names for single payloads
|
||||||
|
await _resolveSupplementNames(pending, logs);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_pending = pending;
|
||||||
|
_logEntries = logs.reversed.toList(); // newest first
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _resolveSupplementNames(
|
||||||
|
List<PendingNotificationRequest> pending,
|
||||||
|
List<NotificationLogEntry> logs,
|
||||||
|
) async {
|
||||||
|
final ctx = context;
|
||||||
|
if (!mounted) return;
|
||||||
|
final provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
|
// Use existing list; attempt load if empty
|
||||||
|
if (provider.supplements.isEmpty) {
|
||||||
|
try {
|
||||||
|
await provider.loadSupplements();
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect potential IDs
|
||||||
|
final Set<int> ids = {};
|
||||||
|
for (final p in pending) {
|
||||||
|
final id = _extractSingleIdFromPayload(p.payload);
|
||||||
|
if (id != null) ids.add(id);
|
||||||
|
}
|
||||||
|
for (final e in logs) {
|
||||||
|
if (e.singleId != null) ids.add(e.singleId!);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build cache
|
||||||
|
for (final id in ids) {
|
||||||
|
try {
|
||||||
|
final s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
_supplementNameCache[id] = s.name;
|
||||||
|
} catch (_) {
|
||||||
|
// leave missing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int? _extractSingleIdFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map && map['type'] == 'single') {
|
||||||
|
final v = map['id'];
|
||||||
|
if (v is int) return v;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _extractGroupTimeFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map && map['type'] == 'group') {
|
||||||
|
final v = map['time'];
|
||||||
|
if (v is String) return v;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _extractKindFromPayload(String? payload) {
|
||||||
|
if (payload == null || payload.isEmpty) return 'unknown';
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map) {
|
||||||
|
final meta = map['meta'];
|
||||||
|
if (meta is Map && meta['kind'] is String) return meta['kind'] as String;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTime? _estimateScheduledAtFromPayload(String? payload) {
|
||||||
|
// For snooze with meta.createdAt/delayMin we can compute when.
|
||||||
|
if (payload == null || payload.isEmpty) return null;
|
||||||
|
try {
|
||||||
|
final map = jsonDecode(payload);
|
||||||
|
if (map is Map) {
|
||||||
|
final meta = map['meta'];
|
||||||
|
if (meta is Map) {
|
||||||
|
final kind = meta['kind'];
|
||||||
|
if (kind == 'snooze') {
|
||||||
|
final createdAt = meta['createdAt'];
|
||||||
|
final delayMin = meta['delayMin'];
|
||||||
|
if (createdAt is int && delayMin is int) {
|
||||||
|
return DateTime.fromMillisecondsSinceEpoch(createdAt)
|
||||||
|
.add(Duration(minutes: delayMin));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// For daily group we can compute next HH:mm
|
||||||
|
if (map['type'] == 'group' && map['time'] is String) {
|
||||||
|
final timeKey = map['time'] as String;
|
||||||
|
final parts = timeKey.split(':');
|
||||||
|
if (parts.length == 2) {
|
||||||
|
final hour = int.tryParse(parts[0]) ?? 0;
|
||||||
|
final minute = int.tryParse(parts[1]) ?? 0;
|
||||||
|
final now = DateTime.now();
|
||||||
|
DateTime sched = DateTime(now.year, now.month, now.day, hour, minute);
|
||||||
|
if (!sched.isAfter(now)) {
|
||||||
|
sched = sched.add(const Duration(days: 1));
|
||||||
|
}
|
||||||
|
return sched;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cancelId(int id) async {
|
||||||
|
await SimpleNotificationService.instance.cancelById(id);
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Canceled notification $id')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cancelAll() async {
|
||||||
|
await SimpleNotificationService.instance.cancelAll();
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Canceled all notifications')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _clearLog() async {
|
||||||
|
await NotificationDebugStore.instance.clear();
|
||||||
|
await _load();
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Cleared debug log')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _copyToClipboard(String text) {
|
||||||
|
Clipboard.setData(ClipboardData(text: text));
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Copied to clipboard')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final pendingIds = _pending.map((e) => e.id).toSet();
|
||||||
|
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text('Debug Notifications'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Refresh',
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel All',
|
||||||
|
onPressed: _cancelAll,
|
||||||
|
icon: const Icon(Icons.cancel_schedule_send),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Clear Log',
|
||||||
|
onPressed: _clearLog,
|
||||||
|
icon: const Icon(Icons.delete_sweep),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: _loading
|
||||||
|
? const Center(child: CircularProgressIndicator())
|
||||||
|
: ListView(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
children: [
|
||||||
|
_buildPendingSection(),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_buildTestSnoozeSection(), // Add the test snooze section
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_buildLogSection(pendingIds),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPendingSection() {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Pending (${_pending.length})', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (_pending.isEmpty)
|
||||||
|
const Text('No pending notifications'),
|
||||||
|
for (final p in _pending) _buildPendingTile(p),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildTestSnoozeSection() {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Test Snooze', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
// Trigger a test snooze notification with snooze actions
|
||||||
|
await SimpleNotificationService.instance.showInstant(
|
||||||
|
title: 'Test Snooze Notification',
|
||||||
|
body: 'This is a test notification for snooze.',
|
||||||
|
payload: jsonEncode({
|
||||||
|
"type": "single",
|
||||||
|
"id": 1, // Use a dummy ID for testing
|
||||||
|
"meta": {"kind": "daily"} // Simulate a daily notification
|
||||||
|
}),
|
||||||
|
includeSnoozeActions: true, // Include snooze actions
|
||||||
|
isSingle: true, // This is a single notification
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: Text('Test snooze notification sent!')),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: const Text('Send Test Snooze Notification'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPendingTile(PendingNotificationRequest p) {
|
||||||
|
final kind = _extractKindFromPayload(p.payload);
|
||||||
|
final singleId = _extractSingleIdFromPayload(p.payload);
|
||||||
|
final groupTime = _extractGroupTimeFromPayload(p.payload);
|
||||||
|
final schedAt = _estimateScheduledAtFromPayload(p.payload);
|
||||||
|
|
||||||
|
final forStr = singleId != null
|
||||||
|
? (_supplementNameCache[singleId] != null
|
||||||
|
? '${_supplementNameCache[singleId]} (id=$singleId)'
|
||||||
|
: 'Supplement id=$singleId')
|
||||||
|
: (groupTime != null ? 'Time $groupTime' : 'unknown');
|
||||||
|
|
||||||
|
// Build a clearer subtitle with scheduled time prominently displayed
|
||||||
|
String subtitle = 'Kind: $kind • For: $forStr';
|
||||||
|
if (schedAt != null) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final diff = schedAt.difference(now);
|
||||||
|
String whenStr;
|
||||||
|
if (diff.isNegative) {
|
||||||
|
whenStr = 'Overdue (${schedAt.toLocal().toString().substring(0, 16)})';
|
||||||
|
} else if (diff.inDays > 0) {
|
||||||
|
whenStr = 'In ${diff.inDays}d ${diff.inHours % 24}h (${schedAt.toLocal().toString().substring(0, 16)})';
|
||||||
|
} else if (diff.inHours > 0) {
|
||||||
|
whenStr = 'In ${diff.inHours}h ${diff.inMinutes % 60}m (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
} else if (diff.inMinutes > 0) {
|
||||||
|
whenStr = 'In ${diff.inMinutes}m (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
} else {
|
||||||
|
whenStr = 'Very soon (${schedAt.toLocal().toString().substring(11, 16)})';
|
||||||
|
}
|
||||||
|
subtitle = '$subtitle\n🕒 $whenStr';
|
||||||
|
}
|
||||||
|
// Removed the "else" block that displayed "Schedule time unknown"
|
||||||
|
|
||||||
|
return ListTile(
|
||||||
|
dense: true,
|
||||||
|
title: Text('ID ${p.id} — ${p.title ?? "(no title)"}'),
|
||||||
|
subtitle: Text(subtitle),
|
||||||
|
trailing: Wrap(
|
||||||
|
spacing: 4,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Copy payload',
|
||||||
|
icon: const Icon(Icons.copy),
|
||||||
|
onPressed: () => _copyToClipboard(p.payload ?? ''),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel',
|
||||||
|
icon: const Icon(Icons.cancel),
|
||||||
|
onPressed: () => _cancelId(p.id),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildLogSection(Set<int> pendingIds) {
|
||||||
|
return Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text('Schedule Log (${_logEntries.length})', style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (_logEntries.isEmpty)
|
||||||
|
const Text('No log entries'),
|
||||||
|
for (final e in _logEntries) _buildLogTile(e, pendingIds),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildLogTile(NotificationLogEntry e, Set<int> pendingIds) {
|
||||||
|
final inQueue = pendingIds.contains(e.id);
|
||||||
|
String forStr = 'unknown';
|
||||||
|
if (e.type == 'single') {
|
||||||
|
if (e.singleId != null) {
|
||||||
|
final name = _supplementNameCache[e.singleId!];
|
||||||
|
forStr = name != null ? '$name (id=${e.singleId})' : 'id=${e.singleId}';
|
||||||
|
}
|
||||||
|
} else if (e.type == 'group') {
|
||||||
|
if (e.timeKey != null) {
|
||||||
|
forStr = 'Time ${e.timeKey}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final scheduledAt = DateTime.fromMillisecondsSinceEpoch(e.whenEpochMs).toLocal();
|
||||||
|
final createdAt = DateTime.fromMillisecondsSinceEpoch(e.createdAtEpochMs).toLocal();
|
||||||
|
|
||||||
|
// Format times more clearly
|
||||||
|
final scheduledStr = scheduledAt.toString().substring(0, 16);
|
||||||
|
final createdStr = createdAt.toString().substring(0, 16);
|
||||||
|
|
||||||
|
// Show status and timing info
|
||||||
|
final statusStr = inQueue ? '🟡 Pending' : '✅ Completed/Canceled';
|
||||||
|
|
||||||
|
return ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading: Icon(inQueue ? Icons.pending : Icons.check, color: inQueue ? Colors.amber : Colors.green),
|
||||||
|
title: Text('[${e.kind}] ${e.title} (ID ${e.id})'),
|
||||||
|
subtitle: Text('$statusStr • Type: ${e.type} • For: $forStr\n🕒 Scheduled: $scheduledStr\n📝 Created: $createdStr'),
|
||||||
|
trailing: Wrap(
|
||||||
|
spacing: 4,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Copy payload',
|
||||||
|
icon: const Icon(Icons.copy),
|
||||||
|
onPressed: () => _copyToClipboard(e.payload),
|
||||||
|
),
|
||||||
|
if (inQueue)
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Cancel',
|
||||||
|
icon: const Icon(Icons.cancel),
|
||||||
|
onPressed: () => _cancelId(e.id),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,12 +15,10 @@ class HistoryScreen extends StatefulWidget {
|
|||||||
class _HistoryScreenState extends State<HistoryScreen> {
|
class _HistoryScreenState extends State<HistoryScreen> {
|
||||||
int _selectedMonth = DateTime.now().month;
|
int _selectedMonth = DateTime.now().month;
|
||||||
int _selectedYear = DateTime.now().year;
|
int _selectedYear = DateTime.now().year;
|
||||||
DateTime? _selectedDay;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_selectedDay = DateTime.now(); // Set today as the default selected day
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
||||||
});
|
});
|
||||||
@@ -32,16 +30,33 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Intake History'),
|
title: const Text('Intake History'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.calendar_today),
|
||||||
|
onPressed: _showMonthPicker,
|
||||||
|
tooltip: 'Select Month',
|
||||||
),
|
),
|
||||||
body: _buildCalendarView(),
|
],
|
||||||
|
),
|
||||||
|
body: _buildCompactHistoryView(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildCalendarView() {
|
Widget _buildCompactHistoryView() {
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
|
// Month selector header
|
||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surface,
|
||||||
|
border: Border(
|
||||||
|
bottom: BorderSide(
|
||||||
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.2),
|
||||||
|
width: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
children: [
|
children: [
|
||||||
@@ -55,22 +70,19 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
_selectedMonth--;
|
_selectedMonth--;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
||||||
|
});
|
||||||
},
|
},
|
||||||
icon: const Icon(Icons.chevron_left),
|
icon: const Icon(Icons.chevron_left),
|
||||||
|
iconSize: 20,
|
||||||
),
|
),
|
||||||
InkWell(
|
Text(
|
||||||
onTap: _showMonthPicker,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
|
||||||
child: Text(
|
|
||||||
DateFormat('MMMM yyyy').format(DateTime(_selectedYear, _selectedMonth)),
|
DateFormat('MMMM yyyy').format(DateTime(_selectedYear, _selectedMonth)),
|
||||||
style: const TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 18,
|
fontSize: 16,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.w600,
|
||||||
),
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
@@ -85,76 +97,191 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
_selectedMonth++;
|
_selectedMonth++;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
icon: const Icon(Icons.chevron_right),
|
icon: const Icon(Icons.chevron_right),
|
||||||
|
iconSize: 20,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
// History list
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Consumer<SupplementProvider>(
|
child: Consumer<SupplementProvider>(
|
||||||
builder: (context, provider, child) {
|
builder: (context, provider, child) {
|
||||||
// Group intakes by date
|
if (provider.monthlyIntakes.isEmpty) {
|
||||||
final groupedIntakes = <String, List<Map<String, dynamic>>>{};
|
return Center(
|
||||||
for (final intake in provider.monthlyIntakes) {
|
|
||||||
final date = DateTime.parse(intake['takenAt']);
|
|
||||||
final dateKey = DateFormat('yyyy-MM-dd').format(date);
|
|
||||||
groupedIntakes.putIfAbsent(dateKey, () => []);
|
|
||||||
groupedIntakes[dateKey]!.add(intake);
|
|
||||||
}
|
|
||||||
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final isWideScreen = constraints.maxWidth > 800;
|
|
||||||
|
|
||||||
if (isWideScreen) {
|
|
||||||
// Desktop/tablet layout: side-by-side
|
|
||||||
return Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
// Calendar on the left
|
|
||||||
Expanded(
|
|
||||||
flex: 2,
|
|
||||||
child: Container(
|
|
||||||
margin: const EdgeInsets.all(16),
|
|
||||||
child: _buildCalendar(groupedIntakes),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Selected day details on the right
|
|
||||||
Expanded(
|
|
||||||
flex: 3,
|
|
||||||
child: Container(
|
|
||||||
// add a bit more horizontal spacing between calendar and card
|
|
||||||
margin: const EdgeInsets.fromLTRB(8, 16, 16, 16),
|
|
||||||
child: SingleChildScrollView(
|
|
||||||
child: _buildSelectedDayDetails(groupedIntakes),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Mobile layout: vertical stack
|
|
||||||
return SingleChildScrollView(
|
|
||||||
child: Column(
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
// Calendar
|
Icon(
|
||||||
Container(
|
Icons.history,
|
||||||
margin: const EdgeInsets.symmetric(horizontal: 16),
|
size: 48,
|
||||||
child: _buildCalendar(groupedIntakes),
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
// Selected day details
|
Text(
|
||||||
Container(
|
'No intake history for this month',
|
||||||
margin: const EdgeInsets.symmetric(horizontal: 16),
|
style: TextStyle(
|
||||||
child: _buildSelectedDayDetails(groupedIntakes),
|
fontSize: 16,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sort intakes by date (most recent first)
|
||||||
|
final sortedIntakes = List<Map<String, dynamic>>.from(provider.monthlyIntakes)
|
||||||
|
..sort((a, b) => DateTime.parse(b['takenAt']).compareTo(DateTime.parse(a['takenAt'])));
|
||||||
|
|
||||||
|
return ListView.builder(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
itemCount: sortedIntakes.length,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final intake = sortedIntakes[index];
|
||||||
|
final takenAt = DateTime.parse(intake['takenAt']);
|
||||||
|
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
|
||||||
|
|
||||||
|
// Check if we need a date header
|
||||||
|
final previousIntake = index > 0 ? sortedIntakes[index - 1] : null;
|
||||||
|
final showDateHeader = previousIntake == null ||
|
||||||
|
DateFormat('yyyy-MM-dd').format(DateTime.parse(previousIntake['takenAt'])) !=
|
||||||
|
DateFormat('yyyy-MM-dd').format(takenAt);
|
||||||
|
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (showDateHeader) ...[
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||||
|
child: Text(
|
||||||
|
DateFormat('EEEE, MMMM d').format(takenAt),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
Dismissible(
|
||||||
|
key: Key('intake_${intake['id']}'),
|
||||||
|
direction: DismissDirection.endToStart,
|
||||||
|
background: Container(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
padding: const EdgeInsets.only(right: 20),
|
||||||
|
color: Colors.red.shade400,
|
||||||
|
child: const Icon(
|
||||||
|
Icons.delete,
|
||||||
|
color: Colors.white,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
confirmDismiss: (direction) async {
|
||||||
|
return await showDialog(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
title: const Text('Delete Intake'),
|
||||||
|
content: Text('Delete ${intake['supplementName']} taken at ${DateFormat('HH:mm').format(takenAt)}?'),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(false),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(true),
|
||||||
|
style: TextButton.styleFrom(foregroundColor: Colors.red),
|
||||||
|
child: const Text('Delete'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
onDismissed: (direction) {
|
||||||
|
context.read<SupplementProvider>().deleteIntake(intake['id']);
|
||||||
|
},
|
||||||
|
child: Container(
|
||||||
|
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
|
||||||
|
child: Card(
|
||||||
|
margin: EdgeInsets.zero,
|
||||||
|
elevation: 2,
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () => _deleteIntake(context, intake['id'], intake['supplementName']),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
splashColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.4),
|
||||||
|
highlightColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.3),
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.medication,
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
size: 18,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
intake['supplementName'],
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
'${DateFormat('HH:mm').format(takenAt)} • ${units.toStringAsFixed(units % 1 == 0 ? 0 : 1)} ${intake['supplementUnitType'] ?? 'units'}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (intake['notes'] != null && intake['notes'].toString().isNotEmpty) ...[
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
intake['notes'],
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
fontStyle: FontStyle.italic,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant.withValues(alpha: 0.8),
|
||||||
|
),
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
size: 18,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -187,12 +314,14 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (picked != null) {
|
if (picked != null) {
|
||||||
|
if (!context.mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_selectedMonth = picked.month;
|
_selectedMonth = picked.month;
|
||||||
_selectedYear = picked.year;
|
_selectedYear = picked.year;
|
||||||
_selectedDay = picked; // Set the selected day to the picked date
|
|
||||||
});
|
});
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,13 +339,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await context.read<SupplementProvider>().deleteIntake(intakeId);
|
await context.read<SupplementProvider>().deleteIntake(intakeId);
|
||||||
|
if (!context.mounted) return;
|
||||||
Navigator.of(context).pop();
|
Navigator.of(context).pop();
|
||||||
|
|
||||||
// Force refresh of the UI
|
// Force refresh of the UI
|
||||||
setState(() {});
|
setState(() {});
|
||||||
|
|
||||||
// Force refresh of the current view data
|
// Force refresh of the current view data
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
context.read<SupplementProvider>().loadMonthlyIntakes(_selectedYear, _selectedMonth);
|
||||||
|
});
|
||||||
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
@@ -233,471 +365,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildCalendar(Map<String, List<Map<String, dynamic>>> groupedIntakes) {
|
|
||||||
final firstDayOfMonth = DateTime(_selectedYear, _selectedMonth, 1);
|
|
||||||
final lastDayOfMonth = DateTime(_selectedYear, _selectedMonth + 1, 0);
|
|
||||||
final firstWeekday = firstDayOfMonth.weekday;
|
|
||||||
final daysInMonth = lastDayOfMonth.day;
|
|
||||||
|
|
||||||
// Calculate how many cells we need (including empty ones for alignment)
|
|
||||||
final totalCells = ((daysInMonth + firstWeekday - 1) / 7).ceil() * 7;
|
|
||||||
final weeks = (totalCells / 7).ceil();
|
|
||||||
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final isWideScreen = constraints.maxWidth > 800;
|
|
||||||
// Calculate calendar height based on number of weeks needed
|
|
||||||
final cellHeight = isWideScreen ? 56.0 : 48.0;
|
|
||||||
final calendarContentHeight = (weeks * cellHeight) + 60; // +60 for headers and padding
|
|
||||||
final calendarHeight = isWideScreen ? 400.0 : calendarContentHeight;
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
child: Container(
|
|
||||||
height: calendarHeight,
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
// Calendar header (weekdays)
|
|
||||||
Row(
|
|
||||||
children: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
|
||||||
.map((day) => Expanded(
|
|
||||||
child: Center(
|
|
||||||
child: Text(
|
|
||||||
day,
|
|
||||||
style: TextStyle(
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
fontSize: isWideScreen ? 14 : 12,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
))
|
|
||||||
.toList(),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
// Calendar grid
|
|
||||||
Expanded(
|
|
||||||
child: GridView.builder(
|
|
||||||
shrinkWrap: true,
|
|
||||||
physics: const ClampingScrollPhysics(),
|
|
||||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
|
||||||
crossAxisCount: 7,
|
|
||||||
childAspectRatio: 1.0,
|
|
||||||
mainAxisSpacing: 4,
|
|
||||||
crossAxisSpacing: 4,
|
|
||||||
),
|
|
||||||
itemCount: totalCells,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final dayNumber = index - firstWeekday + 2;
|
|
||||||
|
|
||||||
if (dayNumber < 1 || dayNumber > daysInMonth) {
|
|
||||||
return const SizedBox(); // Empty cell
|
|
||||||
}
|
|
||||||
|
|
||||||
final date = DateTime(_selectedYear, _selectedMonth, dayNumber);
|
|
||||||
final dateKey = DateFormat('yyyy-MM-dd').format(date);
|
|
||||||
final hasIntakes = groupedIntakes.containsKey(dateKey);
|
|
||||||
final intakeCount = hasIntakes ? groupedIntakes[dateKey]!.length : 0;
|
|
||||||
final isSelected = _selectedDay != null &&
|
|
||||||
DateFormat('yyyy-MM-dd').format(_selectedDay!) == dateKey;
|
|
||||||
final isToday = DateFormat('yyyy-MM-dd').format(DateTime.now()) == dateKey;
|
|
||||||
|
|
||||||
return GestureDetector(
|
|
||||||
onTap: () {
|
|
||||||
setState(() {
|
|
||||||
_selectedDay = date;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
child: Container(
|
|
||||||
margin: const EdgeInsets.all(1),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: isSelected
|
|
||||||
? Theme.of(context).colorScheme.primary
|
|
||||||
: hasIntakes
|
|
||||||
? Theme.of(context).colorScheme.primaryContainer
|
|
||||||
: null,
|
|
||||||
border: isToday
|
|
||||||
? Border.all(color: Theme.of(context).colorScheme.secondary, width: 2)
|
|
||||||
: null,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Stack(
|
|
||||||
children: [
|
|
||||||
Center(
|
|
||||||
child: Text(
|
|
||||||
'$dayNumber',
|
|
||||||
style: TextStyle(
|
|
||||||
color: isSelected
|
|
||||||
? Theme.of(context).colorScheme.onPrimary
|
|
||||||
: hasIntakes
|
|
||||||
? Theme.of(context).colorScheme.onPrimaryContainer
|
|
||||||
: Theme.of(context).colorScheme.onSurface,
|
|
||||||
fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
|
|
||||||
fontSize: isWideScreen ? 16 : 14,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (hasIntakes)
|
|
||||||
Positioned(
|
|
||||||
top: 2,
|
|
||||||
right: 2,
|
|
||||||
child: Container(
|
|
||||||
padding: EdgeInsets.all(isWideScreen ? 3 : 2),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: isSelected
|
|
||||||
? Theme.of(context).colorScheme.onPrimary
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
constraints: BoxConstraints(
|
|
||||||
minWidth: isWideScreen ? 18 : 16,
|
|
||||||
minHeight: isWideScreen ? 18 : 16,
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
'$intakeCount',
|
|
||||||
style: TextStyle(
|
|
||||||
color: isSelected
|
|
||||||
? Theme.of(context).colorScheme.primary
|
|
||||||
: Theme.of(context).colorScheme.onPrimary,
|
|
||||||
fontSize: isWideScreen ? 11 : 10,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildSelectedDayDetails(Map<String, List<Map<String, dynamic>>> groupedIntakes) {
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final isWideScreen = constraints.maxWidth > 600;
|
|
||||||
|
|
||||||
if (_selectedDay == null) {
|
|
||||||
return Card(
|
|
||||||
child: Center(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(32),
|
|
||||||
child: Column(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.touch_app,
|
|
||||||
size: isWideScreen ? 64 : 48,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'Tap a date on the calendar to see details',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: isWideScreen ? 18 : 16,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final dateKey = DateFormat('yyyy-MM-dd').format(_selectedDay!);
|
|
||||||
final dayIntakes = groupedIntakes[dateKey] ?? [];
|
|
||||||
|
|
||||||
if (dayIntakes.isEmpty) {
|
|
||||||
return Card(
|
|
||||||
child: Center(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(32),
|
|
||||||
child: Column(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.event_available,
|
|
||||||
size: isWideScreen ? 64 : 48,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'No supplements taken on ${DateFormat('MMM d, yyyy').format(_selectedDay!)}',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: isWideScreen ? 18 : 16,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Card(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primaryContainer,
|
|
||||||
borderRadius: const BorderRadius.only(
|
|
||||||
topLeft: Radius.circular(12),
|
|
||||||
topRight: Radius.circular(12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
DateFormat('EEEE, MMM d, yyyy').format(_selectedDay!),
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: isWideScreen ? 20 : 18,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'${dayIntakes.length} supplement${dayIntakes.length != 1 ? 's' : ''} taken',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: isWideScreen ? 16 : 14,
|
|
||||||
color: Theme.of(context).colorScheme.onPrimaryContainer.withOpacity(0.8),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Padding(
|
|
||||||
padding: EdgeInsets.all(isWideScreen ? 20 : 16),
|
|
||||||
child: Builder(
|
|
||||||
builder: (context) {
|
|
||||||
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
|
|
||||||
// Sort once per render
|
|
||||||
final sortedDayIntakes = List<Map<String, dynamic>>.from(dayIntakes)
|
|
||||||
..sort((a, b) => DateTime.parse(a['takenAt']).compareTo(DateTime.parse(b['takenAt'])));
|
|
||||||
// Helpers
|
|
||||||
String timeCategory(DateTime dt) {
|
|
||||||
final h = dt.hour;
|
|
||||||
if (h >= settingsProvider.morningStart && h <= settingsProvider.morningEnd) return 'morning';
|
|
||||||
if (h >= settingsProvider.afternoonStart && h <= settingsProvider.afternoonEnd) return 'afternoon';
|
|
||||||
if (h >= settingsProvider.eveningStart && h <= settingsProvider.eveningEnd) return 'evening';
|
|
||||||
final ns = settingsProvider.nightStart;
|
|
||||||
final ne = settingsProvider.nightEnd;
|
|
||||||
final inNight = ns <= ne ? (h >= ns && h <= ne) : (h >= ns || h <= ne);
|
|
||||||
return inNight ? 'night' : 'anytime';
|
|
||||||
}
|
|
||||||
String? sectionRange(String cat) {
|
|
||||||
switch (cat) {
|
|
||||||
case 'morning':
|
|
||||||
return settingsProvider.morningRange;
|
|
||||||
case 'afternoon':
|
|
||||||
return settingsProvider.afternoonRange;
|
|
||||||
case 'evening':
|
|
||||||
return settingsProvider.eveningRange;
|
|
||||||
case 'night':
|
|
||||||
return settingsProvider.nightRange;
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Widget headerFor(String cat) {
|
|
||||||
late final IconData icon;
|
|
||||||
late final Color color;
|
|
||||||
late final String title;
|
|
||||||
switch (cat) {
|
|
||||||
case 'morning':
|
|
||||||
icon = Icons.wb_sunny;
|
|
||||||
color = Colors.orange;
|
|
||||||
title = 'Morning';
|
|
||||||
break;
|
|
||||||
case 'afternoon':
|
|
||||||
icon = Icons.light_mode;
|
|
||||||
color = Colors.blue;
|
|
||||||
title = 'Afternoon';
|
|
||||||
break;
|
|
||||||
case 'evening':
|
|
||||||
icon = Icons.nightlight_round;
|
|
||||||
color = Colors.indigo;
|
|
||||||
title = 'Evening';
|
|
||||||
break;
|
|
||||||
case 'night':
|
|
||||||
icon = Icons.bedtime;
|
|
||||||
color = Colors.purple;
|
|
||||||
title = 'Night';
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
icon = Icons.schedule;
|
|
||||||
color = Colors.grey;
|
|
||||||
title = 'Anytime';
|
|
||||||
}
|
|
||||||
final range = sectionRange(cat);
|
|
||||||
return Container(
|
|
||||||
margin: const EdgeInsets.only(bottom: 12),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: color.withOpacity(0.1),
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
border: Border.all(
|
|
||||||
color: color.withOpacity(0.3),
|
|
||||||
width: 1,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: color.withOpacity(0.2),
|
|
||||||
shape: BoxShape.circle,
|
|
||||||
),
|
|
||||||
child: Icon(
|
|
||||||
icon,
|
|
||||||
size: 20,
|
|
||||||
color: color,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
title,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 18,
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
color: color,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (range != null) ...[
|
|
||||||
Text(
|
|
||||||
'($range)',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
color: color.withOpacity(0.8),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Build a non-scrollable list so the card auto-expands to fit content
|
|
||||||
final List<Widget> children = [];
|
|
||||||
for (int index = 0; index < sortedDayIntakes.length; index++) {
|
|
||||||
final intake = sortedDayIntakes[index];
|
|
||||||
final takenAt = DateTime.parse(intake['takenAt']);
|
|
||||||
final units = (intake['unitsTaken'] as num?)?.toDouble() ?? 1.0;
|
|
||||||
final currentCategory = timeCategory(takenAt);
|
|
||||||
final needsHeader = index == 0
|
|
||||||
? true
|
|
||||||
: currentCategory != timeCategory(DateTime.parse(sortedDayIntakes[index - 1]['takenAt']));
|
|
||||||
if (needsHeader) {
|
|
||||||
children.add(headerFor(currentCategory));
|
|
||||||
}
|
|
||||||
children.add(
|
|
||||||
Card(
|
|
||||||
margin: const EdgeInsets.only(bottom: 12),
|
|
||||||
elevation: 2,
|
|
||||||
child: Padding(
|
|
||||||
padding: EdgeInsets.all(isWideScreen ? 16 : 12),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
CircleAvatar(
|
|
||||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
|
||||||
radius: isWideScreen ? 24 : 20,
|
|
||||||
child: Icon(
|
|
||||||
Icons.medication,
|
|
||||||
color: Theme.of(context).colorScheme.onPrimary,
|
|
||||||
size: isWideScreen ? 24 : 20,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SizedBox(width: isWideScreen ? 16 : 12),
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
intake['supplementName'],
|
|
||||||
style: TextStyle(
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
fontSize: isWideScreen ? 16 : 14,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'${units.toStringAsFixed(units % 1 == 0 ? 0 : 1)} ${intake['supplementUnitType'] ?? 'units'} at ${DateFormat('HH:mm').format(takenAt)}',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Theme.of(context).colorScheme.primary,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
fontSize: isWideScreen ? 14 : 12,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (intake['notes'] != null && intake['notes'].toString().isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
intake['notes'],
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: isWideScreen ? 13 : 12,
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
icon: Icon(
|
|
||||||
Icons.delete_outline,
|
|
||||||
color: Colors.red.shade400,
|
|
||||||
size: isWideScreen ? 24 : 20,
|
|
||||||
),
|
|
||||||
onPressed: () => _deleteIntake(context, intake['id'], intake['supplementName']),
|
|
||||||
tooltip: 'Delete intake',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: children,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import 'add_supplement_screen.dart';
|
|||||||
import 'history_screen.dart';
|
import 'history_screen.dart';
|
||||||
import 'settings_screen.dart';
|
import 'settings_screen.dart';
|
||||||
import 'supplements_list_screen.dart';
|
import 'supplements_list_screen.dart';
|
||||||
|
import 'today_schedule_screen.dart';
|
||||||
|
|
||||||
class HomeScreen extends StatefulWidget {
|
class HomeScreen extends StatefulWidget {
|
||||||
const HomeScreen({super.key});
|
const HomeScreen({super.key});
|
||||||
@@ -18,6 +19,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
int _currentIndex = 0;
|
int _currentIndex = 0;
|
||||||
|
|
||||||
final List<Widget> _screens = [
|
final List<Widget> _screens = [
|
||||||
|
const TodayScheduleScreen(),
|
||||||
const SupplementsListScreen(),
|
const SupplementsListScreen(),
|
||||||
const HistoryScreen(),
|
const HistoryScreen(),
|
||||||
const SettingsScreen(),
|
const SettingsScreen(),
|
||||||
@@ -45,11 +47,18 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
type: BottomNavigationBarType.fixed,
|
type: BottomNavigationBarType.fixed,
|
||||||
|
selectedItemColor: Theme.of(context).colorScheme.primary,
|
||||||
|
unselectedItemColor: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.4),
|
||||||
|
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||||
items: const [
|
items: const [
|
||||||
BottomNavigationBarItem(
|
BottomNavigationBarItem(
|
||||||
icon: Icon(Icons.medication),
|
icon: Icon(Icons.medication_liquid_sharp),
|
||||||
label: 'Supplements',
|
label: 'Supplements',
|
||||||
),
|
),
|
||||||
|
BottomNavigationBarItem(
|
||||||
|
icon: Icon(Icons.edit_calendar_rounded),
|
||||||
|
label: 'Edit',
|
||||||
|
),
|
||||||
BottomNavigationBarItem(
|
BottomNavigationBarItem(
|
||||||
icon: Icon(Icons.history),
|
icon: Icon(Icons.history),
|
||||||
label: 'History',
|
label: 'History',
|
||||||
@@ -60,7 +69,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
floatingActionButton: _currentIndex == 0
|
floatingActionButton: _currentIndex == 1
|
||||||
? FloatingActionButton(
|
? FloatingActionButton(
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await Navigator.of(context).push(
|
await Navigator.of(context).push(
|
||||||
|
|||||||
@@ -1,129 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
|
||||||
import 'package:supplements/screens/home_screen.dart';
|
|
||||||
|
|
||||||
import '../providers/settings_provider.dart';
|
|
||||||
|
|
||||||
// Profile setup screen
|
|
||||||
class ProfileSetupScreen extends StatefulWidget {
|
|
||||||
const ProfileSetupScreen({super.key});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ProfileSetupScreen> createState() => _ProfileSetupScreenState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ProfileSetupScreenState extends State<ProfileSetupScreen> {
|
|
||||||
final _formKey = GlobalKey<FormState>();
|
|
||||||
DateTime? _dateOfBirth;
|
|
||||||
String? _gender;
|
|
||||||
|
|
||||||
final List<String> _genders = ['Male', 'Female', 'Other', 'Prefer not to say'];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
final settingsProvider = Provider.of<SettingsProvider>(context, listen: false);
|
|
||||||
_dateOfBirth = settingsProvider.dateOfBirth;
|
|
||||||
_gender = settingsProvider.gender;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _saveProfile() {
|
|
||||||
if (_formKey.currentState!.validate()) {
|
|
||||||
_formKey.currentState!.save();
|
|
||||||
Provider.of<SettingsProvider>(context, listen: false).setDateOfBirthAndGender(_dateOfBirth!, _gender!);
|
|
||||||
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => HomeScreen()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _selectDate(BuildContext context) async {
|
|
||||||
final DateTime? picked = await showDatePicker(
|
|
||||||
context: context,
|
|
||||||
initialDate: _dateOfBirth ?? DateTime.now(),
|
|
||||||
firstDate: DateTime(1900),
|
|
||||||
lastDate: DateTime.now(),
|
|
||||||
);
|
|
||||||
if (picked != null && picked != _dateOfBirth) {
|
|
||||||
setState(() {
|
|
||||||
_dateOfBirth = picked;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Scaffold(
|
|
||||||
appBar: AppBar(
|
|
||||||
title: const Text('Set Up Your Profile'),
|
|
||||||
),
|
|
||||||
body: Padding(
|
|
||||||
padding: const EdgeInsets.all(16.0),
|
|
||||||
child: Form(
|
|
||||||
key: _formKey,
|
|
||||||
child: Column(
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'To provide you with personalized ingredient insights, please provide your date of birth and gender.',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
TextFormField(
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Date of Birth',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
suffixIcon: Icon(Icons.calendar_today),
|
|
||||||
),
|
|
||||||
readOnly: true,
|
|
||||||
controller: TextEditingController(
|
|
||||||
text: _dateOfBirth == null
|
|
||||||
? ''
|
|
||||||
: '${_dateOfBirth!.toLocal()}'.split(' ')[0],
|
|
||||||
),
|
|
||||||
onTap: () => _selectDate(context),
|
|
||||||
validator: (value) {
|
|
||||||
if (_dateOfBirth == null) {
|
|
||||||
return 'Please select your date of birth';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
DropdownButtonFormField<String>(
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Gender',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
value: _gender,
|
|
||||||
items: _genders.map((String gender) {
|
|
||||||
return DropdownMenuItem<String>(
|
|
||||||
value: gender,
|
|
||||||
child: Text(gender),
|
|
||||||
);
|
|
||||||
}).toList(),
|
|
||||||
onChanged: (value) {
|
|
||||||
setState(() {
|
|
||||||
_gender = value;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
validator: (value) {
|
|
||||||
if (value == null || value.isEmpty) {
|
|
||||||
return 'Please select your gender';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
onSaved: (value) {
|
|
||||||
_gender = value;
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
ElevatedButton(
|
|
||||||
onPressed: _saveProfile,
|
|
||||||
child: const Text('Save and Continue'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../providers/settings_provider.dart';
|
import '../providers/settings_provider.dart';
|
||||||
import 'profile_setup_screen.dart';
|
import 'debug_notifications_screen.dart';
|
||||||
import 'simple_sync_settings_screen.dart';
|
import 'simple_sync_settings_screen.dart';
|
||||||
|
|
||||||
class SettingsScreen extends StatelessWidget {
|
class SettingsScreen extends StatelessWidget {
|
||||||
@@ -19,22 +20,25 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
return ListView(
|
return ListView(
|
||||||
padding: const EdgeInsets.all(16.0),
|
padding: const EdgeInsets.all(16.0),
|
||||||
children: [
|
children: [
|
||||||
|
// Debug section (only in debug builds)
|
||||||
|
if (kDebugMode) ...[
|
||||||
Card(
|
Card(
|
||||||
child: ListTile(
|
child: ListTile(
|
||||||
leading: const Icon(Icons.person),
|
leading: const Icon(Icons.bug_report),
|
||||||
title: const Text('Profile'),
|
title: const Text('Debug Notifications'),
|
||||||
subtitle: Text('Date of Birth: ${settingsProvider.dateOfBirth != null ? '${settingsProvider.dateOfBirth!.toLocal()}'.split(' ')[0] : 'Not set'}, Gender: ${settingsProvider.gender ?? 'Not set'}'),
|
subtitle: const Text('View scheduled notifications and debug log'),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () {
|
onTap: () {
|
||||||
Navigator.of(context).push(
|
Navigator.of(context).push(
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
builder: (context) => const ProfileSetupScreen(),
|
builder: (context) => const DebugNotificationsScreen(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
],
|
||||||
Card(
|
Card(
|
||||||
child: ListTile(
|
child: ListTile(
|
||||||
leading: const Icon(Icons.cloud_sync),
|
leading: const Icon(Icons.cloud_sync),
|
||||||
@@ -63,8 +67,6 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
RadioListTile<ThemeOption>(
|
RadioListTile<ThemeOption>(
|
||||||
title: const Text('Follow System'),
|
|
||||||
subtitle: const Text('Use system theme setting'),
|
|
||||||
value: ThemeOption.system,
|
value: ThemeOption.system,
|
||||||
groupValue: settingsProvider.themeOption,
|
groupValue: settingsProvider.themeOption,
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
@@ -72,10 +74,10 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
settingsProvider.setThemeOption(value);
|
settingsProvider.setThemeOption(value);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
title: const Text('Follow System'),
|
||||||
|
subtitle: const Text('Use system theme setting'),
|
||||||
),
|
),
|
||||||
RadioListTile<ThemeOption>(
|
RadioListTile<ThemeOption>(
|
||||||
title: const Text('Light Theme'),
|
|
||||||
subtitle: const Text('Always use light theme'),
|
|
||||||
value: ThemeOption.light,
|
value: ThemeOption.light,
|
||||||
groupValue: settingsProvider.themeOption,
|
groupValue: settingsProvider.themeOption,
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
@@ -83,10 +85,10 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
settingsProvider.setThemeOption(value);
|
settingsProvider.setThemeOption(value);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
title: const Text('Light Theme'),
|
||||||
|
subtitle: const Text('Always use light theme'),
|
||||||
),
|
),
|
||||||
RadioListTile<ThemeOption>(
|
RadioListTile<ThemeOption>(
|
||||||
title: const Text('Dark Theme'),
|
|
||||||
subtitle: const Text('Always use dark theme'),
|
|
||||||
value: ThemeOption.dark,
|
value: ThemeOption.dark,
|
||||||
groupValue: settingsProvider.themeOption,
|
groupValue: settingsProvider.themeOption,
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
@@ -94,13 +96,109 @@ class SettingsScreen extends StatelessWidget {
|
|||||||
settingsProvider.setThemeOption(value);
|
settingsProvider.setThemeOption(value);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
title: const Text('Dark Theme'),
|
||||||
|
subtitle: const Text('Always use dark theme'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
// Reminders settings removed
|
// Notifications
|
||||||
|
Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(16.0),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Notifications',
|
||||||
|
style: Theme.of(context).textTheme.titleMedium,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.snooze),
|
||||||
|
title: const Text('Snooze duration'),
|
||||||
|
subtitle: const Text('Delay for Snooze action'),
|
||||||
|
trailing: DropdownButton<int>(
|
||||||
|
value: settingsProvider.snoozeMinutes,
|
||||||
|
items: const [
|
||||||
|
DropdownMenuItem(value: 5, child: Text('5 min')),
|
||||||
|
DropdownMenuItem(value: 10, child: Text('10 min')),
|
||||||
|
DropdownMenuItem(value: 15, child: Text('15 min')),
|
||||||
|
DropdownMenuItem(value: 20, child: Text('20 min')),
|
||||||
|
],
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value != null) {
|
||||||
|
settingsProvider.setSnoozeMinutes(value);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(),
|
||||||
|
SwitchListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
secondary: const Icon(Icons.repeat),
|
||||||
|
title: const Text('Notification Retries'),
|
||||||
|
subtitle: const Text('Automatically retry missed notifications'),
|
||||||
|
value: settingsProvider.notificationRetryEnabled,
|
||||||
|
onChanged: (value) {
|
||||||
|
settingsProvider.setNotificationRetryEnabled(value);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
if (settingsProvider.notificationRetryEnabled) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.format_list_numbered),
|
||||||
|
title: const Text('Retry count'),
|
||||||
|
subtitle: const Text('Number of retry attempts'),
|
||||||
|
trailing: DropdownButton<int>(
|
||||||
|
value: settingsProvider.notificationRetryCount,
|
||||||
|
items: const [
|
||||||
|
DropdownMenuItem(value: 1, child: Text('1')),
|
||||||
|
DropdownMenuItem(value: 2, child: Text('2')),
|
||||||
|
DropdownMenuItem(value: 3, child: Text('3')),
|
||||||
|
DropdownMenuItem(value: 4, child: Text('4')),
|
||||||
|
DropdownMenuItem(value: 5, child: Text('5')),
|
||||||
|
],
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value != null) {
|
||||||
|
settingsProvider.setNotificationRetryCount(value);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.schedule),
|
||||||
|
title: const Text('Retry delay'),
|
||||||
|
subtitle: const Text('Time between retry attempts'),
|
||||||
|
trailing: DropdownButton<int>(
|
||||||
|
value: settingsProvider.notificationRetryDelayMinutes,
|
||||||
|
items: const [
|
||||||
|
DropdownMenuItem(value: 1, child: Text('1 min')),
|
||||||
|
DropdownMenuItem(value: 2, child: Text('2 min')),
|
||||||
|
DropdownMenuItem(value: 3, child: Text('3 min')),
|
||||||
|
DropdownMenuItem(value: 5, child: Text('5 min')),
|
||||||
|
DropdownMenuItem(value: 10, child: Text('10 min')),
|
||||||
|
DropdownMenuItem(value: 15, child: Text('15 min')),
|
||||||
|
DropdownMenuItem(value: 20, child: Text('20 min')),
|
||||||
|
DropdownMenuItem(value: 30, child: Text('30 min')),
|
||||||
|
],
|
||||||
|
onChanged: (value) {
|
||||||
|
if (value != null) {
|
||||||
|
settingsProvider.setNotificationRetryDelayMinutes(value);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Card(
|
Card(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
@@ -236,9 +334,9 @@ class _TimeRangeSelector extends StatelessWidget {
|
|||||||
return Container(
|
return Container(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: color.withOpacity(0.1),
|
color: color.withValues(alpha: 0.1),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
border: Border.all(color: color.withOpacity(0.3)),
|
border: Border.all(color: color.withValues(alpha: 0.3)),
|
||||||
),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('My Supplements'),
|
title: const Text('Edit Supplements'),
|
||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
actions: [
|
actions: [
|
||||||
Consumer<SimpleSyncProvider>(
|
Consumer<SimpleSyncProvider>(
|
||||||
@@ -100,19 +100,18 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
await provider.loadSupplements();
|
await provider.loadSupplements();
|
||||||
await provider.refreshDailyStatus();
|
await provider.refreshDailyStatus();
|
||||||
},
|
},
|
||||||
child: _buildGroupedSupplementsList(context, provider.supplements, settingsProvider),
|
child: _buildGroupedSupplementsList(context, provider.supplements, settingsProvider, provider),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildGroupedSupplementsList(BuildContext context, List<Supplement> supplements, SettingsProvider settingsProvider) {
|
Widget _buildGroupedSupplementsList(BuildContext context, List<Supplement> supplements, SettingsProvider settingsProvider, SupplementProvider provider) {
|
||||||
final provider = Provider.of<SupplementProvider>(context, listen: false);
|
|
||||||
final groupedSupplements = _groupSupplementsByTimeOfDay(supplements, settingsProvider);
|
final groupedSupplements = _groupSupplementsByTimeOfDay(supplements, settingsProvider);
|
||||||
|
|
||||||
return ListView(
|
return ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 80),
|
||||||
children: [
|
children: [
|
||||||
if (groupedSupplements['morning']!.isNotEmpty) ...[
|
if (groupedSupplements['morning']!.isNotEmpty) ...[
|
||||||
_buildSectionHeader('Morning (${settingsProvider.morningRange})', Icons.wb_sunny, Colors.orange, groupedSupplements['morning']!.length),
|
_buildSectionHeader('Morning (${settingsProvider.morningRange})', Icons.wb_sunny, Colors.orange, groupedSupplements['morning']!.length),
|
||||||
@@ -124,6 +123,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
|
showCompletionStatus: false,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -139,6 +139,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
|
showCompletionStatus: false,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -154,6 +155,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
|
showCompletionStatus: false,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -169,6 +171,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
|
showCompletionStatus: false,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -184,9 +187,11 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
onDelete: () => _deleteSupplement(context, supplement),
|
onDelete: () => _deleteSupplement(context, supplement),
|
||||||
onArchive: () => _archiveSupplement(context, supplement),
|
onArchive: () => _archiveSupplement(context, supplement),
|
||||||
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
onDuplicate: () => context.read<SupplementProvider>().duplicateSupplement(supplement.id!),
|
||||||
|
showCompletionStatus: false,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -196,10 +201,10 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
margin: const EdgeInsets.only(bottom: 12),
|
margin: const EdgeInsets.only(bottom: 12),
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: color.withOpacity(0.1),
|
color: color.withValues(alpha: 0.1),
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
border: Border.all(
|
border: Border.all(
|
||||||
color: color.withOpacity(0.3),
|
color: color.withValues(alpha: 0.3),
|
||||||
width: 1,
|
width: 1,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -208,7 +213,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.all(8),
|
padding: const EdgeInsets.all(8),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: color.withOpacity(0.2),
|
color: color.withValues(alpha: 0.2),
|
||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
),
|
),
|
||||||
child: Icon(
|
child: Icon(
|
||||||
@@ -236,7 +241,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: FontWeight.w500,
|
fontWeight: FontWeight.w500,
|
||||||
color: color.withOpacity(0.8),
|
color: color.withValues(alpha: 0.8),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -246,7 +251,7 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: color.withOpacity(0.15),
|
color: color.withValues(alpha: 0.15),
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
),
|
),
|
||||||
child: Text(
|
child: Text(
|
||||||
@@ -280,267 +285,6 @@ class SupplementsListScreen extends StatelessWidget {
|
|||||||
return grouped;
|
return grouped;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _showTakeDialog(BuildContext context, Supplement supplement) {
|
|
||||||
final unitsController = TextEditingController(text: supplement.numberOfUnits.toString());
|
|
||||||
final notesController = TextEditingController();
|
|
||||||
DateTime selectedDateTime = DateTime.now();
|
|
||||||
bool useCustomTime = false;
|
|
||||||
|
|
||||||
showDialog(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => StatefulBuilder(
|
|
||||||
builder: (context, setState) {
|
|
||||||
return AlertDialog(
|
|
||||||
title: Text('Take ${supplement.name}'),
|
|
||||||
content: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: TextField(
|
|
||||||
controller: unitsController,
|
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: 'Number of ${supplement.unitType}',
|
|
||||||
border: const OutlineInputBorder(),
|
|
||||||
suffixText: supplement.unitType,
|
|
||||||
),
|
|
||||||
onChanged: (value) => setState(() {}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant,
|
|
||||||
borderRadius: BorderRadius.circular(4),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'Total dosage:',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Text(
|
|
||||||
supplement.ingredientsDisplay,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Theme.of(context).colorScheme.onSurface,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
|
|
||||||
// Time selection section
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(
|
|
||||||
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.access_time,
|
|
||||||
size: 16,
|
|
||||||
color: Theme.of(context).colorScheme.primary,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Text(
|
|
||||||
'When did you take it?',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Theme.of(context).colorScheme.primary,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: RadioListTile<bool>(
|
|
||||||
dense: true,
|
|
||||||
contentPadding: EdgeInsets.zero,
|
|
||||||
title: const Text('Just now', style: TextStyle(fontSize: 12)),
|
|
||||||
value: false,
|
|
||||||
groupValue: useCustomTime,
|
|
||||||
onChanged: (value) => setState(() => useCustomTime = value!),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Expanded(
|
|
||||||
child: RadioListTile<bool>(
|
|
||||||
dense: true,
|
|
||||||
contentPadding: EdgeInsets.zero,
|
|
||||||
title: const Text('Custom time', style: TextStyle(fontSize: 12)),
|
|
||||||
value: true,
|
|
||||||
groupValue: useCustomTime,
|
|
||||||
onChanged: (value) => setState(() => useCustomTime = value!),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
if (useCustomTime) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surface,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(
|
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
children: [
|
|
||||||
// Date picker
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.calendar_today,
|
|
||||||
size: 14,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'Date: ${selectedDateTime.day}/${selectedDateTime.month}/${selectedDateTime.year}',
|
|
||||||
style: const TextStyle(fontSize: 12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () async {
|
|
||||||
final date = await showDatePicker(
|
|
||||||
context: context,
|
|
||||||
initialDate: selectedDateTime,
|
|
||||||
firstDate: DateTime.now().subtract(const Duration(days: 7)),
|
|
||||||
lastDate: DateTime.now(),
|
|
||||||
);
|
|
||||||
if (date != null) {
|
|
||||||
setState(() {
|
|
||||||
selectedDateTime = DateTime(
|
|
||||||
date.year,
|
|
||||||
date.month,
|
|
||||||
date.day,
|
|
||||||
selectedDateTime.hour,
|
|
||||||
selectedDateTime.minute,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: const Text('Change', style: TextStyle(fontSize: 10)),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
// Time picker
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.access_time,
|
|
||||||
size: 14,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'Time: ${selectedDateTime.hour.toString().padLeft(2, '0')}:${selectedDateTime.minute.toString().padLeft(2, '0')}',
|
|
||||||
style: const TextStyle(fontSize: 12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: () async {
|
|
||||||
final time = await showTimePicker(
|
|
||||||
context: context,
|
|
||||||
initialTime: TimeOfDay.fromDateTime(selectedDateTime),
|
|
||||||
);
|
|
||||||
if (time != null) {
|
|
||||||
setState(() {
|
|
||||||
selectedDateTime = DateTime(
|
|
||||||
selectedDateTime.year,
|
|
||||||
selectedDateTime.month,
|
|
||||||
selectedDateTime.day,
|
|
||||||
time.hour,
|
|
||||||
time.minute,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: const Text('Change', style: TextStyle(fontSize: 10)),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextField(
|
|
||||||
controller: notesController,
|
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Notes (optional)',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
maxLines: 2,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
ElevatedButton(
|
|
||||||
onPressed: () {
|
|
||||||
final unitsTaken = double.tryParse(unitsController.text) ?? supplement.numberOfUnits.toDouble();
|
|
||||||
// For now, we'll record 0 as total dosage since we're transitioning to ingredients
|
|
||||||
// This will be properly implemented when we add the full ingredient tracking
|
|
||||||
final totalDosageTaken = 0.0;
|
|
||||||
context.read<SupplementProvider>().recordIntake(
|
|
||||||
supplement.id!,
|
|
||||||
totalDosageTaken,
|
|
||||||
unitsTaken: unitsTaken,
|
|
||||||
notes: notesController.text.isNotEmpty ? notesController.text : null,
|
|
||||||
takenAt: useCustomTime ? selectedDateTime : null,
|
|
||||||
);
|
|
||||||
Navigator.of(context).pop();
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text('${supplement.name} recorded!'),
|
|
||||||
backgroundColor: Colors.green,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
child: const Text('Record'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _editSupplement(BuildContext context, Supplement supplement) {
|
void _editSupplement(BuildContext context, Supplement supplement) {
|
||||||
Navigator.of(context).push(
|
Navigator.of(context).push(
|
||||||
MaterialPageRoute(
|
MaterialPageRoute(
|
||||||
|
|||||||
456
lib/screens/today_schedule_screen.dart
Normal file
456
lib/screens/today_schedule_screen.dart
Normal file
@@ -0,0 +1,456 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:popover/popover.dart';
|
||||||
|
|
||||||
|
import '../models/supplement.dart';
|
||||||
|
import '../providers/settings_provider.dart';
|
||||||
|
import '../providers/simple_sync_provider.dart';
|
||||||
|
import '../providers/supplement_provider.dart';
|
||||||
|
import '../services/database_sync_service.dart';
|
||||||
|
import '../widgets/dialogs/take_supplement_dialog.dart';
|
||||||
|
|
||||||
|
class TodayScheduleScreen extends StatelessWidget {
|
||||||
|
const TodayScheduleScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text("My Supplements"),
|
||||||
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
|
actions: [
|
||||||
|
Consumer<SimpleSyncProvider>(
|
||||||
|
builder: (context, syncProvider, child) {
|
||||||
|
if (!syncProvider.isConfigured) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
return IconButton(
|
||||||
|
icon: syncProvider.isSyncing
|
||||||
|
? const SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: syncProvider.status == SyncStatus.completed &&
|
||||||
|
syncProvider.lastSyncTime != null &&
|
||||||
|
DateTime.now().difference(syncProvider.lastSyncTime!).inSeconds < 5
|
||||||
|
? const Icon(Icons.check, color: Colors.green)
|
||||||
|
: const Icon(Icons.sync),
|
||||||
|
onPressed: syncProvider.isSyncing ? null : () {
|
||||||
|
syncProvider.syncDatabase();
|
||||||
|
},
|
||||||
|
tooltip: syncProvider.isSyncing ? 'Syncing...' : 'Force Sync',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: Consumer2<SupplementProvider, SettingsProvider>(
|
||||||
|
builder: (context, provider, settingsProvider, child) {
|
||||||
|
if (provider.isLoading) {
|
||||||
|
return const Center(child: CircularProgressIndicator());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (provider.todayIntakes.isEmpty && provider.supplements.isEmpty) {
|
||||||
|
return Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.schedule,
|
||||||
|
size: 64,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
'No schedule for today',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 18,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
'Add supplements with reminder times to see your schedule',
|
||||||
|
style: TextStyle(
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: () async {
|
||||||
|
await provider.loadSupplements();
|
||||||
|
await provider.refreshDailyStatus();
|
||||||
|
},
|
||||||
|
child: _buildTimelineView(context, provider, settingsProvider),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildTimelineView(BuildContext context, SupplementProvider provider, SettingsProvider settingsProvider) {
|
||||||
|
final scheduledItems = _getScheduledItems(provider.supplements, provider.todayIntakes);
|
||||||
|
final groupedItems = _groupScheduledItemsByTimeOfDay(scheduledItems);
|
||||||
|
|
||||||
|
return ListView(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
children: [
|
||||||
|
if (groupedItems['morning']!.isNotEmpty) ...[
|
||||||
|
_buildTimeSectionHeader('Morning', Icons.wb_sunny, Colors.orange),
|
||||||
|
...groupedItems['morning']!.map((item) => _buildScheduledItem(context, item)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
|
||||||
|
if (groupedItems['afternoon']!.isNotEmpty) ...[
|
||||||
|
_buildTimeSectionHeader('Afternoon', Icons.light_mode, Colors.blue),
|
||||||
|
...groupedItems['afternoon']!.map((item) => _buildScheduledItem(context, item)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
|
||||||
|
if (groupedItems['evening']!.isNotEmpty) ...[
|
||||||
|
_buildTimeSectionHeader('Evening', Icons.nightlight_round, Colors.indigo),
|
||||||
|
...groupedItems['evening']!.map((item) => _buildScheduledItem(context, item)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
|
||||||
|
if (groupedItems['night']!.isNotEmpty) ...[
|
||||||
|
_buildTimeSectionHeader('Night', Icons.bedtime, Colors.purple),
|
||||||
|
...groupedItems['night']!.map((item) => _buildScheduledItem(context, item)),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildTimeSectionHeader(String title, IconData icon, Color color) {
|
||||||
|
return Container(
|
||||||
|
margin: const EdgeInsets.only(bottom: 8, top: 8),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color.withValues(alpha: 0.1),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(icon, size: 16, color: color),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: color,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildScheduledItem(BuildContext context, Map<String, dynamic> item) {
|
||||||
|
final time = item['time'] as String;
|
||||||
|
final supplement = item['supplement'] as Supplement;
|
||||||
|
final status = item['status'] as String;
|
||||||
|
final actualTime = item['actualTime'] as String?;
|
||||||
|
|
||||||
|
final isCompleted = status == 'on_time' || status == 'off_time';
|
||||||
|
final isOnTime = status == 'on_time';
|
||||||
|
|
||||||
|
return Builder(
|
||||||
|
builder: (context) => InkWell(
|
||||||
|
onTap: () {
|
||||||
|
showPopover(
|
||||||
|
context: context,
|
||||||
|
bodyBuilder: (context) => Container(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 150),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.surface,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
border: Border.all(
|
||||||
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
|
||||||
|
width: 1,
|
||||||
|
),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Theme.of(context).colorScheme.shadow.withValues(alpha: 0.1),
|
||||||
|
blurRadius: 8,
|
||||||
|
offset: const Offset(0, 2),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (isCompleted)
|
||||||
|
_buildPopoverItem(
|
||||||
|
context: context,
|
||||||
|
icon: Icons.undo,
|
||||||
|
label: 'Undo Last Taken',
|
||||||
|
onTap: () async {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
final provider = context.read<SupplementProvider>();
|
||||||
|
final mostRecentIntake = provider.getMostRecentIntake(supplement.id!);
|
||||||
|
if (mostRecentIntake != null) {
|
||||||
|
await provider.deleteIntake(mostRecentIntake['id']);
|
||||||
|
// Refresh the schedule after undoing
|
||||||
|
if (context.mounted) {
|
||||||
|
provider.refreshDailyStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
color: Colors.orange,
|
||||||
|
),
|
||||||
|
_buildPopoverItem(
|
||||||
|
context: context,
|
||||||
|
icon: isCompleted ? Icons.add_circle_outline : Icons.medication,
|
||||||
|
label: isCompleted ? 'Take Again' : 'Take',
|
||||||
|
onTap: () async {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
await showTakeSupplementDialog(context, supplement);
|
||||||
|
// Refresh the schedule after taking
|
||||||
|
if (context.mounted) {
|
||||||
|
context.read<SupplementProvider>().refreshDailyStatus();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
direction: PopoverDirection.top,
|
||||||
|
width: 180,
|
||||||
|
height: null,
|
||||||
|
arrowHeight: 0,
|
||||||
|
arrowWidth: 0,
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
shadow: const [],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 150),
|
||||||
|
margin: const EdgeInsets.only(bottom: 6),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: isCompleted
|
||||||
|
? Theme.of(context).colorScheme.surface
|
||||||
|
: Theme.of(context).colorScheme.primary.withValues(alpha: 0.05),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(
|
||||||
|
color: isCompleted
|
||||||
|
? Theme.of(context).colorScheme.outline.withValues(alpha: 0.3)
|
||||||
|
: Theme.of(context).colorScheme.primary.withValues(alpha: 0.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
time,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
color: isCompleted
|
||||||
|
? Theme.of(context).colorScheme.onSurfaceVariant
|
||||||
|
: Theme.of(context).colorScheme.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (actualTime != null && actualTime != time)
|
||||||
|
Text(
|
||||||
|
'Taken: $actualTime',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
supplement.name,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
color: isCompleted
|
||||||
|
? Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.7)
|
||||||
|
: Theme.of(context).colorScheme.onSurface,
|
||||||
|
decoration: isCompleted ? TextDecoration.lineThrough : null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (isCompleted)
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
if (!isOnTime)
|
||||||
|
Icon(
|
||||||
|
Icons.schedule,
|
||||||
|
size: 14,
|
||||||
|
color: Colors.orange,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Icon(
|
||||||
|
Icons.check_circle,
|
||||||
|
size: 16,
|
||||||
|
color: isOnTime ? Colors.green : Colors.orange,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).colorScheme.primary,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'Pending',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
color: Theme.of(context).colorScheme.onPrimary,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPopoverItem({
|
||||||
|
required BuildContext context,
|
||||||
|
required IconData icon,
|
||||||
|
required String label,
|
||||||
|
required VoidCallback onTap,
|
||||||
|
Color? color,
|
||||||
|
}) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
icon,
|
||||||
|
size: 18,
|
||||||
|
color: color ?? Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: color ?? Theme.of(context).colorScheme.onSurface,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Map<String, dynamic>> _getScheduledItems(List<Supplement> supplements, List<Map<String, dynamic>> todayIntakes) {
|
||||||
|
final List<Map<String, dynamic>> scheduledItems = [];
|
||||||
|
|
||||||
|
for (final supplement in supplements) {
|
||||||
|
for (final reminderTime in supplement.reminderTimes) {
|
||||||
|
// Parse reminder time (format: "HH:MM")
|
||||||
|
final parts = reminderTime.split(':');
|
||||||
|
final hour = int.parse(parts[0]);
|
||||||
|
final minute = int.parse(parts[1]);
|
||||||
|
|
||||||
|
// Check if this reminder has been taken today
|
||||||
|
String status = 'pending';
|
||||||
|
String? actualTime;
|
||||||
|
|
||||||
|
for (final intake in todayIntakes) {
|
||||||
|
if (intake['supplement_id'] == supplement.id) {
|
||||||
|
final takenAt = DateTime.parse(intake['takenAt']);
|
||||||
|
final reminderDateTime = DateTime(
|
||||||
|
takenAt.year,
|
||||||
|
takenAt.month,
|
||||||
|
takenAt.day,
|
||||||
|
hour,
|
||||||
|
minute,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check if taken within 1 hour of reminder time
|
||||||
|
final timeDiff = (takenAt.difference(reminderDateTime)).inMinutes.abs();
|
||||||
|
if (timeDiff <= 60) {
|
||||||
|
status = 'on_time';
|
||||||
|
actualTime = '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}';
|
||||||
|
} else {
|
||||||
|
status = 'off_time';
|
||||||
|
actualTime = '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduledItems.add({
|
||||||
|
'time': reminderTime,
|
||||||
|
'supplement': supplement,
|
||||||
|
'status': status,
|
||||||
|
'actualTime': actualTime,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by time
|
||||||
|
scheduledItems.sort((a, b) {
|
||||||
|
final timeA = a['time'] as String;
|
||||||
|
final timeB = b['time'] as String;
|
||||||
|
return timeA.compareTo(timeB);
|
||||||
|
});
|
||||||
|
|
||||||
|
return scheduledItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, List<Map<String, dynamic>>> _groupScheduledItemsByTimeOfDay(List<Map<String, dynamic>> scheduledItems) {
|
||||||
|
final Map<String, List<Map<String, dynamic>>> grouped = {
|
||||||
|
'morning': <Map<String, dynamic>>[],
|
||||||
|
'afternoon': <Map<String, dynamic>>[],
|
||||||
|
'evening': <Map<String, dynamic>>[],
|
||||||
|
'night': <Map<String, dynamic>>[],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (final item in scheduledItems) {
|
||||||
|
final time = item['time'] as String;
|
||||||
|
final parts = time.split(':');
|
||||||
|
final hour = int.parse(parts[0]);
|
||||||
|
|
||||||
|
String category;
|
||||||
|
if (hour >= 6 && hour < 12) {
|
||||||
|
category = 'morning';
|
||||||
|
} else if (hour >= 12 && hour < 18) {
|
||||||
|
category = 'afternoon';
|
||||||
|
} else if (hour >= 18 && hour < 22) {
|
||||||
|
category = 'evening';
|
||||||
|
} else {
|
||||||
|
category = 'night';
|
||||||
|
}
|
||||||
|
|
||||||
|
grouped[category]!.add(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort items by time within each category
|
||||||
|
for (final category in grouped.keys) {
|
||||||
|
grouped[category]!.sort((a, b) {
|
||||||
|
final timeA = a['time'] as String;
|
||||||
|
final timeB = b['time'] as String;
|
||||||
|
return timeA.compareTo(timeB);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return grouped;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -232,7 +232,7 @@ class AutoSyncService {
|
|||||||
if (_consecutiveFailures >= _autoDisableThreshold) {
|
if (_consecutiveFailures >= _autoDisableThreshold) {
|
||||||
_autoDisabledDueToErrors = true;
|
_autoDisabledDueToErrors = true;
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
printLog('AutoSyncService: Auto-sync disabled due to ${_consecutiveFailures} consecutive failures');
|
printLog('AutoSyncService: Auto-sync disabled due to $_consecutiveFailures consecutive failures');
|
||||||
}
|
}
|
||||||
|
|
||||||
// For configuration errors, disable immediately
|
// For configuration errors, disable immediately
|
||||||
|
|||||||
92
lib/services/notification_debug_store.dart
Normal file
92
lib/services/notification_debug_store.dart
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
class NotificationLogEntry {
|
||||||
|
final int id;
|
||||||
|
final String kind; // 'daily' | 'snooze'
|
||||||
|
final String type; // 'single' | 'group'
|
||||||
|
final int whenEpochMs; // exact scheduled time (epoch ms)
|
||||||
|
final int createdAtEpochMs; // when we created the schedule (epoch ms)
|
||||||
|
final String title;
|
||||||
|
final String payload;
|
||||||
|
final int? singleId; // supplement id for single
|
||||||
|
final String? timeKey; // HH:mm for group
|
||||||
|
|
||||||
|
const NotificationLogEntry({
|
||||||
|
required this.id,
|
||||||
|
required this.kind,
|
||||||
|
required this.type,
|
||||||
|
required this.whenEpochMs,
|
||||||
|
required this.createdAtEpochMs,
|
||||||
|
required this.title,
|
||||||
|
required this.payload,
|
||||||
|
this.singleId,
|
||||||
|
this.timeKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'kind': kind,
|
||||||
|
'type': type,
|
||||||
|
'when': whenEpochMs,
|
||||||
|
'createdAt': createdAtEpochMs,
|
||||||
|
'title': title,
|
||||||
|
'payload': payload,
|
||||||
|
'singleId': singleId,
|
||||||
|
'timeKey': timeKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
static NotificationLogEntry fromJson(Map<String, dynamic> map) {
|
||||||
|
return NotificationLogEntry(
|
||||||
|
id: map['id'] is int ? map['id'] as int : int.tryParse('${map['id']}') ?? 0,
|
||||||
|
kind: map['kind'] ?? 'unknown',
|
||||||
|
type: map['type'] ?? 'unknown',
|
||||||
|
whenEpochMs: map['when'] is int ? map['when'] as int : int.tryParse('${map['when']}') ?? 0,
|
||||||
|
createdAtEpochMs: map['createdAt'] is int ? map['createdAt'] as int : int.tryParse('${map['createdAt']}') ?? 0,
|
||||||
|
title: map['title'] ?? '',
|
||||||
|
payload: map['payload'] ?? '',
|
||||||
|
singleId: map['singleId'],
|
||||||
|
timeKey: map['timeKey'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class NotificationDebugStore {
|
||||||
|
NotificationDebugStore._internal();
|
||||||
|
static final NotificationDebugStore instance = NotificationDebugStore._internal();
|
||||||
|
|
||||||
|
static const String _prefsKey = 'notification_log';
|
||||||
|
static const int _maxEntries = 200;
|
||||||
|
|
||||||
|
Future<List<NotificationLogEntry>> getAll() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString(_prefsKey);
|
||||||
|
if (raw == null || raw.isEmpty) return [];
|
||||||
|
try {
|
||||||
|
final list = jsonDecode(raw) as List;
|
||||||
|
return list
|
||||||
|
.map((e) => NotificationLogEntry.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
} catch (_) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> add(NotificationLogEntry entry) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final current = await getAll();
|
||||||
|
current.add(entry);
|
||||||
|
// Cap size
|
||||||
|
final trimmed = current.length > _maxEntries
|
||||||
|
? current.sublist(current.length - _maxEntries)
|
||||||
|
: current;
|
||||||
|
final serialized = jsonEncode(trimmed.map((e) => e.toJson()).toList());
|
||||||
|
await prefs.setString(_prefsKey, serialized);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> clear() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.remove(_prefsKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,9 @@ import 'dart:convert';
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:supplements/logging.dart';
|
import 'package:supplements/logging.dart';
|
||||||
|
import 'package:supplements/services/simple_notification_service.dart';
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
@@ -27,7 +29,25 @@ class NotificationRouter {
|
|||||||
final payloadMap = _decodePayload(response.payload);
|
final payloadMap = _decodePayload(response.payload);
|
||||||
final actionId = response.actionId;
|
final actionId = response.actionId;
|
||||||
printLog('🔔 handleNotificationResponse: actionId=$actionId payload=${response.payload} map=$payloadMap');
|
printLog('🔔 handleNotificationResponse: actionId=$actionId payload=${response.payload} map=$payloadMap');
|
||||||
|
printLog('🔔 handleNotificationResponse: Received actionId: $actionId');
|
||||||
|
printLog('🔔 handleNotificationResponse: Decoded payloadMap: $payloadMap');
|
||||||
|
|
||||||
|
// Cancel retry notifications for any interaction (take, snooze, or tap)
|
||||||
|
await _cancelRetryNotificationsForResponse(payloadMap);
|
||||||
|
|
||||||
|
// Handle Snooze actions without surfacing UI
|
||||||
|
if (actionId == 'snooze_single' || actionId == 'snooze_group') {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final minutes = prefs.getInt('snooze_minutes') ?? 10;
|
||||||
|
await _scheduleSnoozeFromPayload(payloadMap, Duration(minutes: minutes));
|
||||||
|
} catch (e) {
|
||||||
|
printLog('⚠️ Failed to handle snooze action: $e');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default: route to in-app UI for Take actions and normal taps
|
||||||
await _routeFromPayload(payloadMap);
|
await _routeFromPayload(payloadMap);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +96,7 @@ class NotificationRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final context = _navigatorKey!.currentContext!;
|
final context = _navigatorKey!.currentContext!;
|
||||||
|
if (!context.mounted) return;
|
||||||
final provider = context.read<SupplementProvider>();
|
final provider = context.read<SupplementProvider>();
|
||||||
|
|
||||||
if (payload == null) {
|
if (payload == null) {
|
||||||
@@ -96,6 +117,7 @@ class NotificationRouter {
|
|||||||
if (s == null) {
|
if (s == null) {
|
||||||
// Attempt reload once
|
// Attempt reload once
|
||||||
await provider.loadSupplements();
|
await provider.loadSupplements();
|
||||||
|
if (!context.mounted) return;
|
||||||
try {
|
try {
|
||||||
s = provider.supplements.firstWhere((el) => el.id == id);
|
s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
@@ -107,6 +129,7 @@ class NotificationRouter {
|
|||||||
// Ensure we close any existing dialog first
|
// Ensure we close any existing dialog first
|
||||||
_popAnyDialog(context);
|
_popAnyDialog(context);
|
||||||
await showTakeSupplementDialog(context, s, hideTime: false);
|
await showTakeSupplementDialog(context, s, hideTime: false);
|
||||||
|
if (!context.mounted) return;
|
||||||
} else {
|
} else {
|
||||||
printLog('⚠️ Supplement id=$id not found for single-take routing');
|
printLog('⚠️ Supplement id=$id not found for single-take routing');
|
||||||
_showSnack(context, 'Supplement not found');
|
_showSnack(context, 'Supplement not found');
|
||||||
@@ -128,21 +151,135 @@ class NotificationRouter {
|
|||||||
|
|
||||||
_popAnyDialog(context);
|
_popAnyDialog(context);
|
||||||
await showBulkTakeDialog(context, list);
|
await showBulkTakeDialog(context, list);
|
||||||
|
if (!context.mounted) return;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
printLog('⚠️ Unknown payload type: $type');
|
printLog('⚠️ Unknown payload type: $type');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _scheduleSnoozeFromPayload(Map<String, dynamic>? payload, Duration delay) async {
|
||||||
|
if (payload == null) {
|
||||||
|
printLog('⚠️ Snooze requested but payload was null');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to wait for providers to be ready to build rich content.
|
||||||
|
final ready = await _waitUntilReady(timeout: const Duration(seconds: 5));
|
||||||
|
|
||||||
|
SupplementProvider? provider;
|
||||||
|
if (ready) {
|
||||||
|
final ctx = _navigatorKey?.currentContext;
|
||||||
|
if (ctx != null && ctx.mounted) {
|
||||||
|
provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String title = 'Supplement reminder';
|
||||||
|
String body = 'Tap to see details';
|
||||||
|
bool isSingle = false;
|
||||||
|
// Start with a mutable copy of the payload to add meta information
|
||||||
|
final Map<String, dynamic> mutablePayload = Map.from(payload);
|
||||||
|
|
||||||
|
final type = mutablePayload['type'];
|
||||||
|
|
||||||
|
if (type == 'single') {
|
||||||
|
final id = payload['id'];
|
||||||
|
isSingle = true;
|
||||||
|
// Ensure the payload for single snooze is correctly formatted
|
||||||
|
mutablePayload['type'] = 'single';
|
||||||
|
mutablePayload['id'] = id;
|
||||||
|
|
||||||
|
if (id is int && provider != null) {
|
||||||
|
Supplement? s;
|
||||||
|
try {
|
||||||
|
s = provider.supplements.firstWhere((el) => el.id == id);
|
||||||
|
} catch (_) {
|
||||||
|
s = null;
|
||||||
|
}
|
||||||
|
if (s != null) {
|
||||||
|
title = 'Time for ${s.name}';
|
||||||
|
body =
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})';
|
||||||
|
} else {
|
||||||
|
body = 'Tap to take supplement';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (type == 'group') {
|
||||||
|
final timeKey = mutablePayload['time'];
|
||||||
|
if (timeKey is String) {
|
||||||
|
if (provider != null) {
|
||||||
|
final list = provider.supplements
|
||||||
|
.where((s) =>
|
||||||
|
s.isActive && s.reminderTimes.contains(timeKey))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
if (list.length == 1) {
|
||||||
|
final s = list.first;
|
||||||
|
isSingle = true;
|
||||||
|
title = 'Time for ${s.name}';
|
||||||
|
body =
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})';
|
||||||
|
// If a group becomes a single, update the payload type
|
||||||
|
mutablePayload['type'] = 'single';
|
||||||
|
mutablePayload['id'] = s.id;
|
||||||
|
mutablePayload.remove('time'); // Remove time key for single
|
||||||
|
} else if (list.isNotEmpty) {
|
||||||
|
isSingle = false;
|
||||||
|
title = 'Time for ${list.length} supplements';
|
||||||
|
final lines = list
|
||||||
|
.map((s) =>
|
||||||
|
'${s.name} — ${s.numberOfUnits} ${s.unitType} (${s.ingredientsPerUnit})')
|
||||||
|
.toList();
|
||||||
|
body = lines.join('\n');
|
||||||
|
// Ensure payload type is group
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
} else {
|
||||||
|
// Fallback generic group
|
||||||
|
isSingle = false;
|
||||||
|
title = 'Supplement reminder';
|
||||||
|
body = 'Tap to see details';
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Provider not ready; schedule generic group payload
|
||||||
|
isSingle = false;
|
||||||
|
mutablePayload['type'] = 'group';
|
||||||
|
mutablePayload['time'] = timeKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure the payload always has the correct type and ID/time for logging
|
||||||
|
// and re-scheduling. The SimpleNotificationService will add the 'meta' field.
|
||||||
|
final payloadStr = jsonEncode(mutablePayload);
|
||||||
|
|
||||||
|
await SimpleNotificationService.instance.scheduleOneOffReminder(
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
payload: payloadStr,
|
||||||
|
isSingle: isSingle,
|
||||||
|
delay: delay,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Future<bool> _waitUntilReady({required Duration timeout}) async {
|
Future<bool> _waitUntilReady({required Duration timeout}) async {
|
||||||
final start = DateTime.now();
|
final start = DateTime.now();
|
||||||
while (DateTime.now().difference(start) < timeout) {
|
while (DateTime.now().difference(start) < timeout) {
|
||||||
final ctx = _navigatorKey!.currentContext;
|
final key = _navigatorKey;
|
||||||
|
final ctx = key?.currentContext;
|
||||||
if (ctx != null) {
|
if (ctx != null) {
|
||||||
|
if (!ctx.mounted) continue;
|
||||||
|
try {
|
||||||
final provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
final provider = Provider.of<SupplementProvider>(ctx, listen: false);
|
||||||
if (!provider.isLoading) {
|
if (!provider.isLoading) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// Provider not available yet
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await Future.delayed(const Duration(milliseconds: 100));
|
await Future.delayed(const Duration(milliseconds: 100));
|
||||||
}
|
}
|
||||||
@@ -156,8 +293,50 @@ class NotificationRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _showSnack(BuildContext context, String message) {
|
void _showSnack(BuildContext context, String message) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(content: Text(message)),
|
SnackBar(content: Text(message)),
|
||||||
);
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel retry notifications when user responds to any notification.
|
||||||
|
/// This prevents redundant notifications after user interaction.
|
||||||
|
Future<void> _cancelRetryNotificationsForResponse(Map<String, dynamic>? payloadMap) async {
|
||||||
|
if (payloadMap == null) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final type = payloadMap['type'];
|
||||||
|
|
||||||
|
if (type == 'single') {
|
||||||
|
// For single notifications, we need to find the time slot to cancel retries
|
||||||
|
// We can extract this from the meta if it's a retry, or find it from the supplement
|
||||||
|
final meta = payloadMap['meta'] as Map<String, dynamic>?;
|
||||||
|
if (meta != null && meta['originalTime'] != null) {
|
||||||
|
// This is a retry notification, cancel remaining retries for the original time
|
||||||
|
final originalTime = meta['originalTime'] as String;
|
||||||
|
await SimpleNotificationService.instance.cancelRetryNotificationsForTimeSlot(originalTime);
|
||||||
|
printLog('🚫 Cancelled retries for original time slot: $originalTime');
|
||||||
|
} else {
|
||||||
|
// This is an original notification, find the time slot from the supplement
|
||||||
|
final supplementId = payloadMap['id'];
|
||||||
|
if (supplementId is int) {
|
||||||
|
// We need to find which time slots this supplement has and cancel retries for all of them
|
||||||
|
// For now, we'll use the broader cancellation method
|
||||||
|
await SimpleNotificationService.instance.cancelRetryNotificationsForSupplement(supplementId);
|
||||||
|
printLog('🚫 Cancelled retries for supplement ID: $supplementId');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (type == 'group') {
|
||||||
|
// For group notifications, we have the time key directly
|
||||||
|
final timeKey = payloadMap['time'] as String?;
|
||||||
|
if (timeKey != null) {
|
||||||
|
await SimpleNotificationService.instance.cancelRetryNotificationsForTimeSlot(timeKey);
|
||||||
|
printLog('🚫 Cancelled retries for time slot: $timeKey');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
printLog('⚠️ Failed to cancel retry notifications: $e');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
/*
|
|
||||||
Deprecated/removed: notification_service.dart
|
|
||||||
|
|
||||||
This legacy notification service has been intentionally removed.
|
|
||||||
The app now uses a minimal scheduler in:
|
|
||||||
services/simple_notification_service.dart
|
|
||||||
|
|
||||||
All retry/snooze/database-tracking logic has been dropped to keep things simple.
|
|
||||||
This file is left empty to ensure any lingering references fail at compile time,
|
|
||||||
prompting migration to the new SimpleNotificationService.
|
|
||||||
*/
|
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
import 'package:supplements/logging.dart';
|
import 'package:supplements/logging.dart';
|
||||||
|
import 'package:supplements/services/notification_debug_store.dart';
|
||||||
|
import 'package:supplements/services/notification_router.dart';
|
||||||
import 'package:timezone/data/latest.dart' as tzdata;
|
import 'package:timezone/data/latest.dart' as tzdata;
|
||||||
import 'package:timezone/timezone.dart' as tz;
|
import 'package:timezone/timezone.dart' as tz;
|
||||||
import 'dart:convert';
|
|
||||||
import 'package:supplements/services/notification_router.dart';
|
|
||||||
|
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
|
import '../providers/settings_provider.dart';
|
||||||
|
|
||||||
/// A minimal notification scheduler focused purely on:
|
/// A minimal notification scheduler focused purely on:
|
||||||
/// - Initialization
|
/// - Initialization
|
||||||
@@ -33,7 +36,9 @@ class SimpleNotificationService {
|
|||||||
///
|
///
|
||||||
/// Note: This does not request runtime permissions. Call [requestPermissions]
|
/// Note: This does not request runtime permissions. Call [requestPermissions]
|
||||||
/// to prompt the user for notification permissions.
|
/// to prompt the user for notification permissions.
|
||||||
Future<void> initialize() async {
|
Future<void> initialize({
|
||||||
|
DidReceiveBackgroundNotificationResponseCallback? onDidReceiveBackgroundNotificationResponse,
|
||||||
|
}) async {
|
||||||
if (_initialized) return;
|
if (_initialized) return;
|
||||||
|
|
||||||
// Initialize timezone database and set a sane default.
|
// Initialize timezone database and set a sane default.
|
||||||
@@ -52,12 +57,14 @@ class SimpleNotificationService {
|
|||||||
'single',
|
'single',
|
||||||
actions: [
|
actions: [
|
||||||
DarwinNotificationAction.plain('take_single', 'Take'),
|
DarwinNotificationAction.plain('take_single', 'Take'),
|
||||||
|
DarwinNotificationAction.plain('snooze_single', 'Snooze'),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
DarwinNotificationCategory(
|
DarwinNotificationCategory(
|
||||||
'group',
|
'group',
|
||||||
actions: [
|
actions: [
|
||||||
DarwinNotificationAction.plain('take_group', 'Take All'),
|
DarwinNotificationAction.plain('take_group', 'Take All'),
|
||||||
|
DarwinNotificationAction.plain('snooze_group', 'Snooze'),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -77,6 +84,7 @@ class SimpleNotificationService {
|
|||||||
onDidReceiveNotificationResponse: (response) {
|
onDidReceiveNotificationResponse: (response) {
|
||||||
NotificationRouter.instance.handleNotificationResponse(response);
|
NotificationRouter.instance.handleNotificationResponse(response);
|
||||||
},
|
},
|
||||||
|
onDidReceiveBackgroundNotificationResponse: onDidReceiveBackgroundNotificationResponse,
|
||||||
);
|
);
|
||||||
|
|
||||||
_initialized = true;
|
_initialized = true;
|
||||||
@@ -125,8 +133,12 @@ class SimpleNotificationService {
|
|||||||
///
|
///
|
||||||
/// IDs:
|
/// IDs:
|
||||||
/// - Group ID per time slot: 40000 + hour*60 + minute.
|
/// - Group ID per time slot: 40000 + hour*60 + minute.
|
||||||
|
/// - Retry IDs: 50000 + (hour*60 + minute)*100 + retryIndex.
|
||||||
/// - Stable and predictable for cancel/update operations.
|
/// - Stable and predictable for cancel/update operations.
|
||||||
Future<void> scheduleDailyGroupedReminders(List<Supplement> supplements) async {
|
Future<void> scheduleDailyGroupedReminders(
|
||||||
|
List<Supplement> supplements, {
|
||||||
|
SettingsProvider? settingsProvider,
|
||||||
|
}) async {
|
||||||
if (!_initialized) {
|
if (!_initialized) {
|
||||||
await initialize();
|
await initialize();
|
||||||
}
|
}
|
||||||
@@ -181,7 +193,7 @@ class SimpleNotificationService {
|
|||||||
final units = s.numberOfUnits;
|
final units = s.numberOfUnits;
|
||||||
final unitType = s.unitType;
|
final unitType = s.unitType;
|
||||||
final perUnit = s.ingredientsPerUnit;
|
final perUnit = s.ingredientsPerUnit;
|
||||||
return '${s.name} — $units $unitType (${perUnit})';
|
return '${s.name} — $units $unitType ($perUnit)';
|
||||||
}).toList();
|
}).toList();
|
||||||
final body = bodyLines.join('\n');
|
final body = bodyLines.join('\n');
|
||||||
|
|
||||||
@@ -190,9 +202,12 @@ class SimpleNotificationService {
|
|||||||
|
|
||||||
// Use BigTextStyle/InboxStyle for Android to show multiple lines
|
// Use BigTextStyle/InboxStyle for Android to show multiple lines
|
||||||
final bool isSingle = count == 1;
|
final bool isSingle = count == 1;
|
||||||
final String payloadStr = isSingle
|
// Tag payload with origin meta for debug/inspection
|
||||||
? jsonEncode({"type": "single", "id": items.first.id})
|
final Map<String, dynamic> payloadMap = isSingle
|
||||||
: jsonEncode({"type": "group", "time": timeKey});
|
? {"type": "single", "id": items.first.id}
|
||||||
|
: {"type": "group", "time": timeKey};
|
||||||
|
payloadMap["meta"] = {"kind": "daily"};
|
||||||
|
final String payloadStr = jsonEncode(payloadMap);
|
||||||
|
|
||||||
final androidDetails = AndroidNotificationDetails(
|
final androidDetails = AndroidNotificationDetails(
|
||||||
_channelDailyId,
|
_channelDailyId,
|
||||||
@@ -220,6 +235,20 @@ class SimpleNotificationService {
|
|||||||
showsUserInterface: true,
|
showsUserInterface: true,
|
||||||
cancelNotification: true,
|
cancelNotification: true,
|
||||||
),
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -241,7 +270,37 @@ class SimpleNotificationService {
|
|||||||
payload: payloadStr,
|
payload: payloadStr,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Log to debug store
|
||||||
|
final createdAtMs = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
await NotificationDebugStore.instance.add(
|
||||||
|
NotificationLogEntry(
|
||||||
|
id: id,
|
||||||
|
kind: 'daily',
|
||||||
|
type: isSingle ? 'single' : 'group',
|
||||||
|
whenEpochMs: when.millisecondsSinceEpoch,
|
||||||
|
createdAtEpochMs: createdAtMs,
|
||||||
|
title: title,
|
||||||
|
payload: payloadStr,
|
||||||
|
singleId: isSingle ? items.first.id : null,
|
||||||
|
timeKey: isSingle ? null : timeKey,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
printLog('✅ Scheduled group $timeKey with ID $id');
|
printLog('✅ Scheduled group $timeKey with ID $id');
|
||||||
|
|
||||||
|
// Schedule retry notifications if enabled
|
||||||
|
if (settingsProvider != null && settingsProvider.notificationRetryEnabled) {
|
||||||
|
await _scheduleRetryNotifications(
|
||||||
|
timeKey: timeKey,
|
||||||
|
supplements: items,
|
||||||
|
isSingle: isSingle,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
payloadStr: payloadStr,
|
||||||
|
retryCount: settingsProvider.notificationRetryCount,
|
||||||
|
retryDelayMinutes: settingsProvider.notificationRetryDelayMinutes,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log what the system reports as pending
|
// Log what the system reports as pending
|
||||||
@@ -258,13 +317,16 @@ class SimpleNotificationService {
|
|||||||
|
|
||||||
/// Convenience to schedule grouped reminders for today and tomorrow.
|
/// Convenience to schedule grouped reminders for today and tomorrow.
|
||||||
///
|
///
|
||||||
/// For iOS’s 64 limit, we stick to one day for recurring (matchDateTimeComponents)
|
/// For iOS's 64 limit, we stick to one day for recurring (matchDateTimeComponents)
|
||||||
/// which already repeats every day without needing to schedule future dates.
|
/// which already repeats every day without needing to schedule future dates.
|
||||||
/// If you want an extra safety net, you could schedule tomorrow’s one-offs,
|
/// If you want an extra safety net, you could schedule tomorrow's one-offs,
|
||||||
/// but with daily components this is unnecessary and risks hitting iOS limits.
|
/// but with daily components this is unnecessary and risks hitting iOS limits.
|
||||||
Future<void> scheduleDailyGroupedRemindersSafe(List<Supplement> supplements) async {
|
Future<void> scheduleDailyGroupedRemindersSafe(
|
||||||
// For now, just schedule today’s recurring groups.
|
List<Supplement> supplements, {
|
||||||
await scheduleDailyGroupedReminders(supplements);
|
SettingsProvider? settingsProvider,
|
||||||
|
}) async {
|
||||||
|
// For now, just schedule today's recurring groups.
|
||||||
|
await scheduleDailyGroupedReminders(supplements, settingsProvider: settingsProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cancel all scheduled reminders for a given [supplementId].
|
/// Cancel all scheduled reminders for a given [supplementId].
|
||||||
@@ -288,34 +350,204 @@ class SimpleNotificationService {
|
|||||||
await _plugin.cancelAll();
|
await _plugin.cancelAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Cancel a specific notification by ID.
|
||||||
|
Future<void> cancelById(int id) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
await _plugin.cancel(id);
|
||||||
|
}
|
||||||
|
|
||||||
/// Show an immediate notification. Useful for quick diagnostics.
|
/// Show an immediate notification. Useful for quick diagnostics.
|
||||||
Future<void> showInstant({
|
Future<void> showInstant({
|
||||||
required String title,
|
required String title,
|
||||||
required String body,
|
required String body,
|
||||||
String? payload,
|
String? payload,
|
||||||
|
bool includeSnoozeActions = false, // New parameter
|
||||||
|
bool isSingle = true, // New parameter, defaults to single for instant
|
||||||
}) async {
|
}) async {
|
||||||
if (!_initialized) {
|
if (!_initialized) {
|
||||||
await initialize();
|
await initialize();
|
||||||
}
|
}
|
||||||
|
|
||||||
await _plugin.show(
|
final androidDetails = AndroidNotificationDetails(
|
||||||
DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
||||||
title,
|
|
||||||
body,
|
|
||||||
const NotificationDetails(
|
|
||||||
android: AndroidNotificationDetails(
|
|
||||||
'instant_notifications',
|
'instant_notifications',
|
||||||
'Instant Notifications',
|
'Instant Notifications',
|
||||||
channelDescription: 'One-off or immediate notifications',
|
channelDescription: 'One-off or immediate notifications',
|
||||||
importance: Importance.high,
|
importance: Importance.high,
|
||||||
priority: Priority.high,
|
priority: Priority.high,
|
||||||
|
actions: includeSnoozeActions
|
||||||
|
? [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
),
|
),
|
||||||
iOS: DarwinNotificationDetails(),
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [], // No actions by default
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: includeSnoozeActions
|
||||||
|
? (isSingle ? 'single' : 'group')
|
||||||
|
: null, // Use category for actions
|
||||||
|
);
|
||||||
|
|
||||||
|
await _plugin.show(
|
||||||
|
DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
),
|
),
|
||||||
payload: payload,
|
payload: payload,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Schedule a one-off (non-repeating) reminder, typically used for Snooze.
|
||||||
|
Future<void> scheduleOneOffReminder({
|
||||||
|
required String title,
|
||||||
|
required String body,
|
||||||
|
required String payload,
|
||||||
|
required bool isSingle,
|
||||||
|
required Duration delay,
|
||||||
|
}) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
final when = tz.TZDateTime.now(tz.local).add(delay);
|
||||||
|
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
_channelDailyId,
|
||||||
|
_channelDailyName,
|
||||||
|
channelDescription: _channelDailyDescription,
|
||||||
|
importance: Importance.high,
|
||||||
|
priority: Priority.high,
|
||||||
|
styleInformation: BigTextStyleInformation(
|
||||||
|
body,
|
||||||
|
contentTitle: title,
|
||||||
|
htmlFormatContentTitle: false,
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
// Removed cancelNotification: true for debugging
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: isSingle ? 'single' : 'group',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Enrich payload with meta for snooze; also capture linkage for logging
|
||||||
|
Map<String, dynamic>? pmap;
|
||||||
|
try {
|
||||||
|
pmap = jsonDecode(payload) as Map<String, dynamic>;
|
||||||
|
} catch (_) {
|
||||||
|
pmap = null;
|
||||||
|
}
|
||||||
|
final createdAtMs = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
String payloadFinal = payload;
|
||||||
|
int? logSingleId;
|
||||||
|
String? logTimeKey;
|
||||||
|
if (pmap != null) {
|
||||||
|
final meta = {
|
||||||
|
'kind': 'snooze',
|
||||||
|
'createdAt': createdAtMs,
|
||||||
|
'delayMin': delay.inMinutes,
|
||||||
|
};
|
||||||
|
pmap['meta'] = meta;
|
||||||
|
if (pmap['type'] == 'single') {
|
||||||
|
final v = pmap['id'];
|
||||||
|
logSingleId = v is int ? v : null;
|
||||||
|
} else if (pmap['type'] == 'group') {
|
||||||
|
logTimeKey = pmap['time'] as String?;
|
||||||
|
}
|
||||||
|
payloadFinal = jsonEncode(pmap);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _plugin.zonedSchedule(
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
isSingle ? body : 'Tap to see details',
|
||||||
|
when,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
|
),
|
||||||
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
||||||
|
payload: payloadFinal,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log to debug store
|
||||||
|
await NotificationDebugStore.instance.add(
|
||||||
|
NotificationLogEntry(
|
||||||
|
id: id,
|
||||||
|
kind: 'snooze',
|
||||||
|
type: isSingle ? 'single' : 'group',
|
||||||
|
whenEpochMs: when.millisecondsSinceEpoch,
|
||||||
|
createdAtEpochMs: createdAtMs,
|
||||||
|
title: title,
|
||||||
|
payload: payloadFinal,
|
||||||
|
singleId: logSingleId,
|
||||||
|
timeKey: logTimeKey,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
printLog('⏰ Scheduled one-off reminder (id=$id) at $when, isSingle=$isSingle');
|
||||||
|
}
|
||||||
|
|
||||||
Future<NotificationAppLaunchDetails?> getLaunchDetails() async {
|
Future<NotificationAppLaunchDetails?> getLaunchDetails() async {
|
||||||
if (!_initialized) {
|
if (!_initialized) {
|
||||||
await initialize();
|
await initialize();
|
||||||
@@ -356,4 +588,176 @@ class SimpleNotificationService {
|
|||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Schedule retry notifications for a specific time group.
|
||||||
|
Future<void> _scheduleRetryNotifications({
|
||||||
|
required String timeKey,
|
||||||
|
required List<Supplement> supplements,
|
||||||
|
required bool isSingle,
|
||||||
|
required String title,
|
||||||
|
required String body,
|
||||||
|
required String payloadStr,
|
||||||
|
required int retryCount,
|
||||||
|
required int retryDelayMinutes,
|
||||||
|
}) async {
|
||||||
|
if (retryCount <= 0) return;
|
||||||
|
|
||||||
|
final parts = timeKey.split(':');
|
||||||
|
final hour = int.parse(parts[0]);
|
||||||
|
final minute = int.parse(parts[1]);
|
||||||
|
final baseTime = _nextInstanceOfTime(hour, minute);
|
||||||
|
|
||||||
|
for (int retryIndex = 1; retryIndex <= retryCount; retryIndex++) {
|
||||||
|
final retryDelay = Duration(minutes: retryDelayMinutes * retryIndex);
|
||||||
|
final retryTime = baseTime.add(retryDelay);
|
||||||
|
final retryId = 50000 + ((hour * 60) + minute) * 100 + retryIndex;
|
||||||
|
|
||||||
|
// Parse and modify payload to mark as retry
|
||||||
|
Map<String, dynamic> retryPayload;
|
||||||
|
try {
|
||||||
|
retryPayload = Map<String, dynamic>.from(jsonDecode(payloadStr));
|
||||||
|
retryPayload['meta'] = {
|
||||||
|
'kind': 'retry',
|
||||||
|
'originalTime': timeKey,
|
||||||
|
'retryIndex': retryIndex,
|
||||||
|
'retryOf': 40000 + (hour * 60) + minute,
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
retryPayload = {
|
||||||
|
'type': isSingle ? 'single' : 'group',
|
||||||
|
if (isSingle) 'id': supplements.first.id else 'time': timeKey,
|
||||||
|
'meta': {
|
||||||
|
'kind': 'retry',
|
||||||
|
'originalTime': timeKey,
|
||||||
|
'retryIndex': retryIndex,
|
||||||
|
'retryOf': 40000 + (hour * 60) + minute,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
final retryPayloadStr = jsonEncode(retryPayload);
|
||||||
|
final retryTitle = 'Reminder: $title';
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
_channelDailyId,
|
||||||
|
_channelDailyName,
|
||||||
|
channelDescription: _channelDailyDescription,
|
||||||
|
importance: Importance.high,
|
||||||
|
priority: Priority.high,
|
||||||
|
styleInformation: BigTextStyleInformation(
|
||||||
|
body,
|
||||||
|
contentTitle: retryTitle,
|
||||||
|
htmlFormatContentTitle: false,
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_single',
|
||||||
|
'Take',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'take_group',
|
||||||
|
'Take All',
|
||||||
|
showsUserInterface: true,
|
||||||
|
cancelNotification: true,
|
||||||
|
),
|
||||||
|
if (isSingle)
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_single',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
AndroidNotificationAction(
|
||||||
|
'snooze_group',
|
||||||
|
'Snooze',
|
||||||
|
showsUserInterface: false,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final iosDetails = DarwinNotificationDetails(
|
||||||
|
categoryIdentifier: isSingle ? 'single' : 'group',
|
||||||
|
);
|
||||||
|
|
||||||
|
await _plugin.zonedSchedule(
|
||||||
|
retryId,
|
||||||
|
retryTitle,
|
||||||
|
isSingle ? body : 'Tap to see details',
|
||||||
|
retryTime,
|
||||||
|
NotificationDetails(
|
||||||
|
android: androidDetails,
|
||||||
|
iOS: iosDetails,
|
||||||
|
),
|
||||||
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
||||||
|
payload: retryPayloadStr,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log to debug store
|
||||||
|
final createdAtMs = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
await NotificationDebugStore.instance.add(
|
||||||
|
NotificationLogEntry(
|
||||||
|
id: retryId,
|
||||||
|
kind: 'retry',
|
||||||
|
type: isSingle ? 'single' : 'group',
|
||||||
|
whenEpochMs: retryTime.millisecondsSinceEpoch,
|
||||||
|
createdAtEpochMs: createdAtMs,
|
||||||
|
title: retryTitle,
|
||||||
|
payload: retryPayloadStr,
|
||||||
|
singleId: isSingle ? supplements.first.id : null,
|
||||||
|
timeKey: isSingle ? null : timeKey,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
printLog('🔄 Scheduled retry $retryIndex/$retryCount for $timeKey (ID: $retryId) at $retryTime');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel retry notifications for a specific time slot.
|
||||||
|
/// This should be called when a user responds to a notification.
|
||||||
|
Future<void> cancelRetryNotificationsForTimeSlot(String timeKey) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
final parts = timeKey.split(':');
|
||||||
|
if (parts.length != 2) return;
|
||||||
|
|
||||||
|
final hour = int.tryParse(parts[0]);
|
||||||
|
final minute = int.tryParse(parts[1]);
|
||||||
|
if (hour == null || minute == null) return;
|
||||||
|
|
||||||
|
// Calculate base retry ID range for this time slot
|
||||||
|
final baseRetryId = 50000 + ((hour * 60) + minute) * 100;
|
||||||
|
|
||||||
|
// Cancel up to 10 possible retries (generous upper bound)
|
||||||
|
for (int retryIndex = 1; retryIndex <= 10; retryIndex++) {
|
||||||
|
final retryId = baseRetryId + retryIndex;
|
||||||
|
await _plugin.cancel(retryId);
|
||||||
|
printLog('🚫 Cancelled retry notification ID: $retryId for time slot $timeKey');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel retry notifications for a specific supplement ID.
|
||||||
|
/// This iterates through all possible time slots.
|
||||||
|
Future<void> cancelRetryNotificationsForSupplement(int supplementId) async {
|
||||||
|
if (!_initialized) {
|
||||||
|
await initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel retries for all possible time slots (24 hours * 60 minutes)
|
||||||
|
for (int hour = 0; hour < 24; hour++) {
|
||||||
|
for (int minute = 0; minute < 60; minute += 5) { // Assume 5-minute intervals
|
||||||
|
final baseRetryId = 50000 + ((hour * 60) + minute) * 100;
|
||||||
|
for (int retryIndex = 1; retryIndex <= 10; retryIndex++) {
|
||||||
|
final retryId = baseRetryId + retryIndex;
|
||||||
|
await _plugin.cancel(retryId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printLog('🚫 Cancelled all retry notifications for supplement ID: $supplementId');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,10 +51,10 @@ Future<void> showBulkTakeDialog(
|
|||||||
return Container(
|
return Container(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5),
|
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
border: Border.all(
|
border: Border.all(
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -108,7 +108,7 @@ Future<void> showBulkTakeDialog(
|
|||||||
color: Theme.of(context).colorScheme.surface,
|
color: Theme.of(context).colorScheme.surface,
|
||||||
borderRadius: BorderRadius.circular(6),
|
borderRadius: BorderRadius.circular(6),
|
||||||
border: Border.all(
|
border: Border.all(
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||||
|
|
||||||
import '../../models/supplement.dart';
|
import '../../models/supplement.dart';
|
||||||
import '../../providers/supplement_provider.dart';
|
import '../../providers/supplement_provider.dart';
|
||||||
@@ -16,38 +17,32 @@ Future<void> showTakeSupplementDialog(
|
|||||||
DateTime selectedDateTime = DateTime.now();
|
DateTime selectedDateTime = DateTime.now();
|
||||||
bool useCustomTime = false;
|
bool useCustomTime = false;
|
||||||
|
|
||||||
await showDialog(
|
await showShadDialog(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => StatefulBuilder(
|
builder: (context) => StatefulBuilder(
|
||||||
builder: (context, setState) {
|
builder: (context, setState) {
|
||||||
return AlertDialog(
|
return ShadDialog(
|
||||||
title: Text('Take ${supplement.name}'),
|
title: Text('Take ${supplement.name}'),
|
||||||
content: Column(
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: TextField(
|
child: ShadInput(
|
||||||
controller: unitsController,
|
controller: unitsController,
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
decoration: InputDecoration(
|
placeholder: Text('Number of ${supplement.unitType}'),
|
||||||
labelText: 'Number of ${supplement.unitType}',
|
|
||||||
border: const OutlineInputBorder(),
|
|
||||||
suffixText: supplement.unitType,
|
|
||||||
),
|
|
||||||
onChanged: (value) => setState(() {}),
|
onChanged: (value) => setState(() {}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Container(
|
ShadCard(
|
||||||
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(8),
|
padding: const EdgeInsets.all(8),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant,
|
|
||||||
borderRadius: BorderRadius.circular(4),
|
|
||||||
),
|
|
||||||
child: Row(
|
child: Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
children: [
|
children: [
|
||||||
@@ -55,7 +50,7 @@ Future<void> showTakeSupplementDialog(
|
|||||||
'Total dosage:',
|
'Total dosage:',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: ShadTheme.of(context).colorScheme.foreground,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Text(
|
Text(
|
||||||
@@ -63,25 +58,18 @@ Future<void> showTakeSupplementDialog(
|
|||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
color: Theme.of(context).colorScheme.onSurface,
|
color: ShadTheme.of(context).colorScheme.foreground,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
|
||||||
if (!hideTime) ...[
|
if (!hideTime) ...[
|
||||||
// Time selection section
|
ShadCard(
|
||||||
Container(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(
|
|
||||||
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
@@ -90,7 +78,7 @@ Future<void> showTakeSupplementDialog(
|
|||||||
Icon(
|
Icon(
|
||||||
Icons.access_time,
|
Icons.access_time,
|
||||||
size: 16,
|
size: 16,
|
||||||
color: Theme.of(context).colorScheme.primary,
|
color: ShadTheme.of(context).colorScheme.primary,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
Text(
|
Text(
|
||||||
@@ -98,57 +86,39 @@ Future<void> showTakeSupplementDialog(
|
|||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
color: Theme.of(context).colorScheme.primary,
|
color: ShadTheme.of(context).colorScheme.primary,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Row(
|
ShadRadioGroupFormField<bool>(
|
||||||
children: [
|
initialValue: useCustomTime,
|
||||||
Expanded(
|
onChanged: (value) => setState(() => useCustomTime = value!),
|
||||||
child: RadioListTile<bool>(
|
items: [
|
||||||
dense: true,
|
ShadRadio(
|
||||||
contentPadding: EdgeInsets.zero,
|
|
||||||
title: const Text('Just now', style: TextStyle(fontSize: 12)),
|
|
||||||
value: false,
|
value: false,
|
||||||
groupValue: useCustomTime,
|
label: const Text('Just now', style: TextStyle(fontSize: 12)),
|
||||||
onChanged: (value) => setState(() => useCustomTime = value!),
|
|
||||||
),
|
),
|
||||||
),
|
ShadRadio(
|
||||||
Expanded(
|
|
||||||
child: RadioListTile<bool>(
|
|
||||||
dense: true,
|
|
||||||
contentPadding: EdgeInsets.zero,
|
|
||||||
title: const Text('Custom time', style: TextStyle(fontSize: 12)),
|
|
||||||
value: true,
|
value: true,
|
||||||
groupValue: useCustomTime,
|
label: const Text('Custom time', style: TextStyle(fontSize: 12)),
|
||||||
onChanged: (value) => setState(() => useCustomTime = value!),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (useCustomTime) ...[
|
if (useCustomTime) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Container(
|
ShadCard(
|
||||||
width: double.infinity,
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surface,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(
|
|
||||||
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
child: Column(
|
||||||
children: [
|
children: [
|
||||||
// Date picker
|
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Icon(
|
||||||
Icons.calendar_today,
|
Icons.calendar_today,
|
||||||
size: 14,
|
size: 14,
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: ShadTheme.of(context).colorScheme.foreground,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -157,7 +127,7 @@ Future<void> showTakeSupplementDialog(
|
|||||||
style: const TextStyle(fontSize: 12),
|
style: const TextStyle(fontSize: 12),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
ShadButton.outline(
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
final date = await showDatePicker(
|
final date = await showDatePicker(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -182,13 +152,12 @@ Future<void> showTakeSupplementDialog(
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
// Time picker
|
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Icon(
|
||||||
Icons.access_time,
|
Icons.access_time,
|
||||||
size: 14,
|
size: 14,
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
color: ShadTheme.of(context).colorScheme.foreground,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -197,7 +166,7 @@ Future<void> showTakeSupplementDialog(
|
|||||||
style: const TextStyle(fontSize: 12),
|
style: const TextStyle(fontSize: 12),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextButton(
|
ShadButton.outline(
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
final time = await showTimePicker(
|
final time = await showTimePicker(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -222,54 +191,53 @@ Future<void> showTakeSupplementDialog(
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
],
|
],
|
||||||
|
ShadInput(
|
||||||
TextField(
|
|
||||||
controller: notesController,
|
controller: notesController,
|
||||||
decoration: const InputDecoration(
|
placeholder: const Text('Notes (optional)'),
|
||||||
labelText: 'Notes (optional)',
|
|
||||||
border: OutlineInputBorder(),
|
|
||||||
),
|
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
),
|
),
|
||||||
],
|
const SizedBox(height: 16),
|
||||||
),
|
Row(
|
||||||
actions: [
|
mainAxisAlignment: MainAxisAlignment.end,
|
||||||
TextButton(
|
children: [
|
||||||
|
ShadButton.outline(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
child: const Text('Cancel'),
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
const SizedBox(width: 8),
|
||||||
|
ShadButton(
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
final unitsTaken = double.tryParse(unitsController.text) ?? supplement.numberOfUnits.toDouble();
|
final unitsTaken = double.tryParse(unitsController.text) ?? supplement.numberOfUnits.toDouble();
|
||||||
// For now, we'll record 0 as total dosage since we're transitioning to ingredients
|
|
||||||
// This will be properly implemented when we add the full ingredient tracking
|
|
||||||
final totalDosageTaken = 0.0;
|
final totalDosageTaken = 0.0;
|
||||||
context.read<SupplementProvider>().recordIntake(
|
context.read<SupplementProvider>().recordIntake(
|
||||||
supplement.id!,
|
supplement.id!,
|
||||||
totalDosageTaken,
|
totalDosageTaken,
|
||||||
unitsTaken: unitsTaken,
|
unitsTaken: unitsTaken,
|
||||||
notes: notesController.text.isNotEmpty ? notesController.text : null,
|
notes: notesController.text.isNotEmpty ? notesController.text : null,
|
||||||
takenAt: hideTime
|
takenAt: hideTime ? null : (useCustomTime ? selectedDateTime : null),
|
||||||
? null
|
|
||||||
: (useCustomTime ? selectedDateTime : null),
|
|
||||||
);
|
);
|
||||||
Navigator.of(context).pop();
|
Navigator.of(context).pop();
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ShadToaster.of(context).show(
|
||||||
SnackBar(
|
ShadToast(
|
||||||
content: Text('${supplement.name} recorded!'),
|
title: Text('${supplement.name} recorded!'),
|
||||||
backgroundColor: Colors.green,
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
child: const Text('Record'),
|
child: const Text('Record'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ class InfoChip extends StatelessWidget {
|
|||||||
final bool fullWidth;
|
final bool fullWidth;
|
||||||
|
|
||||||
const InfoChip({
|
const InfoChip({
|
||||||
|
super.key,
|
||||||
required this.icon,
|
required this.icon,
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.context,
|
required this.context,
|
||||||
@@ -19,7 +20,7 @@ class InfoChip extends StatelessWidget {
|
|||||||
width: fullWidth ? double.infinity : null,
|
width: fullWidth ? double.infinity : null,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.4),
|
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.4),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shadcn_ui/shadcn_ui.dart';
|
||||||
|
import 'package:popover/popover.dart';
|
||||||
import '../models/supplement.dart';
|
import '../models/supplement.dart';
|
||||||
import '../providers/supplement_provider.dart';
|
import '../providers/supplement_provider.dart';
|
||||||
|
|
||||||
@@ -10,6 +12,8 @@ class SupplementCard extends StatefulWidget {
|
|||||||
final VoidCallback onDelete;
|
final VoidCallback onDelete;
|
||||||
final VoidCallback onArchive;
|
final VoidCallback onArchive;
|
||||||
final VoidCallback onDuplicate;
|
final VoidCallback onDuplicate;
|
||||||
|
final VoidCallback? onUndoLastTaken;
|
||||||
|
final bool showCompletionStatus;
|
||||||
|
|
||||||
const SupplementCard({
|
const SupplementCard({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -19,6 +23,8 @@ class SupplementCard extends StatefulWidget {
|
|||||||
required this.onDelete,
|
required this.onDelete,
|
||||||
required this.onArchive,
|
required this.onArchive,
|
||||||
required this.onDuplicate,
|
required this.onDuplicate,
|
||||||
|
this.onUndoLastTaken,
|
||||||
|
this.showCompletionStatus = true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -28,16 +34,48 @@ class SupplementCard extends StatefulWidget {
|
|||||||
class _SupplementCardState extends State<SupplementCard> {
|
class _SupplementCardState extends State<SupplementCard> {
|
||||||
bool _isExpanded = false;
|
bool _isExpanded = false;
|
||||||
|
|
||||||
|
Widget _buildPopoverItem({
|
||||||
|
required IconData icon,
|
||||||
|
required String label,
|
||||||
|
required VoidCallback onTap,
|
||||||
|
Color? color,
|
||||||
|
}) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
icon,
|
||||||
|
size: 18,
|
||||||
|
color: color ?? Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: color ?? Theme.of(context).colorScheme.onSurface,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Consumer<SupplementProvider>(
|
return Consumer<SupplementProvider>(
|
||||||
builder: (context, provider, child) {
|
builder: (context, provider, child) {
|
||||||
final bool isTakenToday = provider.hasBeenTakenToday(widget.supplement.id!);
|
final bool isTakenToday = widget.showCompletionStatus ? provider.hasBeenTakenToday(widget.supplement.id!) : false;
|
||||||
final int todayIntakeCount = provider.getTodayIntakeCount(widget.supplement.id!);
|
final int todayIntakeCount = widget.showCompletionStatus ? provider.getTodayIntakeCount(widget.supplement.id!) : 0;
|
||||||
final bool isCompletelyTaken = todayIntakeCount >= widget.supplement.frequencyPerDay;
|
final bool isCompletelyTaken = widget.showCompletionStatus ? todayIntakeCount >= widget.supplement.frequencyPerDay : false;
|
||||||
|
|
||||||
// Get today's intake times for this supplement
|
// Get today's intake times for this supplement (only if showing completion status)
|
||||||
final todayIntakes = provider.todayIntakes
|
final todayIntakes = widget.showCompletionStatus ? provider.todayIntakes
|
||||||
.where((intake) => intake['supplement_id'] == widget.supplement.id)
|
.where((intake) => intake['supplement_id'] == widget.supplement.id)
|
||||||
.map((intake) {
|
.map((intake) {
|
||||||
final takenAt = DateTime.parse(intake['takenAt']);
|
final takenAt = DateTime.parse(intake['takenAt']);
|
||||||
@@ -46,103 +84,163 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
'time': '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}',
|
'time': '${takenAt.hour.toString().padLeft(2, '0')}:${takenAt.minute.toString().padLeft(2, '0')}',
|
||||||
'units': unitsTaken is int ? unitsTaken.toDouble() : unitsTaken as double,
|
'units': unitsTaken is int ? unitsTaken.toDouble() : unitsTaken as double,
|
||||||
};
|
};
|
||||||
}).toList();
|
}).toList() : [];
|
||||||
|
|
||||||
return Card(
|
return Card(
|
||||||
margin: const EdgeInsets.only(bottom: 16),
|
margin: const EdgeInsets.only(bottom: 8),
|
||||||
elevation: 3,
|
elevation: 2,
|
||||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||||
child: Container(
|
child: InkWell(
|
||||||
|
onTap: () {
|
||||||
|
showPopover(
|
||||||
|
context: context,
|
||||||
|
bodyBuilder: (context) => Container(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 200),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(16),
|
color: Theme.of(context).colorScheme.surface,
|
||||||
color: isCompletelyTaken
|
borderRadius: BorderRadius.circular(12),
|
||||||
? Theme.of(context).colorScheme.surface
|
|
||||||
: isTakenToday
|
|
||||||
? Theme.of(context).colorScheme.secondaryContainer
|
|
||||||
: Theme.of(context).colorScheme.surface,
|
|
||||||
border: Border.all(
|
border: Border.all(
|
||||||
color: isCompletelyTaken
|
color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
|
||||||
? Colors.green.shade600
|
width: 1,
|
||||||
: isTakenToday
|
|
||||||
? Theme.of(context).colorScheme.secondary
|
|
||||||
: Theme.of(context).colorScheme.outline.withOpacity(0.2),
|
|
||||||
width: 1.5,
|
|
||||||
),
|
),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Theme.of(context).colorScheme.shadow.withValues(alpha: 0.1),
|
||||||
|
blurRadius: 8,
|
||||||
|
offset: const Offset(0, 2),
|
||||||
),
|
),
|
||||||
child: Theme(
|
],
|
||||||
data: Theme.of(context).copyWith(
|
|
||||||
dividerColor: Colors.transparent,
|
|
||||||
),
|
),
|
||||||
child: ExpansionTile(
|
|
||||||
initiallyExpanded: _isExpanded,
|
|
||||||
onExpansionChanged: (expanded) {
|
|
||||||
setState(() {
|
|
||||||
_isExpanded = expanded;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
tilePadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
|
||||||
childrenPadding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
|
|
||||||
leading: Container(
|
|
||||||
padding: const EdgeInsets.all(8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade500
|
|
||||||
: isTakenToday
|
|
||||||
? Theme.of(context).colorScheme.secondary
|
|
||||||
: Theme.of(context).colorScheme.primary.withOpacity(0.1),
|
|
||||||
shape: BoxShape.circle,
|
|
||||||
),
|
|
||||||
child: Icon(
|
|
||||||
isCompletelyTaken
|
|
||||||
? Icons.check_circle
|
|
||||||
: isTakenToday
|
|
||||||
? Icons.schedule
|
|
||||||
: Icons.medication,
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Theme.of(context).colorScheme.inverseSurface
|
|
||||||
: isTakenToday
|
|
||||||
? Theme.of(context).colorScheme.onSecondary
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
size: 20,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
title: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
if (widget.onUndoLastTaken != null && isTakenToday)
|
||||||
widget.supplement.name,
|
_buildPopoverItem(
|
||||||
style: TextStyle(
|
icon: Icons.undo,
|
||||||
fontSize: 16,
|
label: 'Undo Last Taken',
|
||||||
fontWeight: FontWeight.bold,
|
onTap: () {
|
||||||
color: isCompletelyTaken
|
Navigator.of(context).pop();
|
||||||
? Theme.of(context).colorScheme.inverseSurface
|
widget.onUndoLastTaken!();
|
||||||
: isTakenToday
|
},
|
||||||
? Theme.of(context).colorScheme.onSecondaryContainer
|
color: Colors.orange,
|
||||||
: Theme.of(context).colorScheme.onSurface,
|
|
||||||
),
|
),
|
||||||
|
_buildPopoverItem(
|
||||||
|
icon: Icons.edit,
|
||||||
|
label: 'Edit',
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
widget.onEdit();
|
||||||
|
},
|
||||||
),
|
),
|
||||||
if (widget.supplement.brand != null && widget.supplement.brand!.isNotEmpty)
|
_buildPopoverItem(
|
||||||
Text(
|
icon: Icons.copy,
|
||||||
widget.supplement.brand!,
|
label: 'Duplicate',
|
||||||
style: TextStyle(
|
onTap: () {
|
||||||
fontSize: 12,
|
Navigator.of(context).pop();
|
||||||
color: isCompletelyTaken
|
widget.onDuplicate();
|
||||||
? Colors.green.shade200
|
},
|
||||||
: isTakenToday
|
|
||||||
? Theme.of(context).colorScheme.secondary
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
),
|
),
|
||||||
|
_buildPopoverItem(
|
||||||
|
icon: Icons.archive,
|
||||||
|
label: 'Archive',
|
||||||
|
color: Colors.orange,
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
widget.onArchive();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
_buildPopoverItem(
|
||||||
|
icon: Icons.delete,
|
||||||
|
label: 'Delete',
|
||||||
|
color: Colors.red,
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
widget.onDelete();
|
||||||
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
// Status badge and take button in collapsed view
|
direction: PopoverDirection.bottom,
|
||||||
if (!_isExpanded) ...[
|
width: 180,
|
||||||
if (isCompletelyTaken)
|
height: null,
|
||||||
|
arrowHeight: 0,
|
||||||
|
arrowWidth: 0,
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
shadow: const [],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
splashColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.4),
|
||||||
|
highlightColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.3),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 150),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Theme.of(context).colorScheme.surface
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.secondaryContainer
|
||||||
|
: Theme.of(context).colorScheme.surface) : Theme.of(context).colorScheme.surface,
|
||||||
|
border: Border.all(
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Colors.green.shade600
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.secondary
|
||||||
|
: Theme.of(context).colorScheme.outline.withValues(alpha: 0.2)) : Theme.of(context).colorScheme.outline.withValues(alpha: 0.2),
|
||||||
|
width: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Colors.green.shade500
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.secondary
|
||||||
|
: Theme.of(context).colorScheme.primary.withValues(alpha: 0.1)) : Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Icons.check_circle
|
||||||
|
: isTakenToday
|
||||||
|
? Icons.schedule
|
||||||
|
: Icons.medication) : Icons.medication,
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Theme.of(context).colorScheme.inverseSurface
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.onSecondary
|
||||||
|
: Theme.of(context).colorScheme.primary) : Theme.of(context).colorScheme.primary,
|
||||||
|
size: 18,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
widget.supplement.name,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Theme.of(context).colorScheme.inverseSurface
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.onSecondaryContainer
|
||||||
|
: Theme.of(context).colorScheme.onSurface) : Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (widget.showCompletionStatus && isCompletelyTaken) ...[
|
||||||
|
const SizedBox(width: 8),
|
||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@@ -157,335 +255,55 @@ class _SupplementCardState extends State<SupplementCard> {
|
|||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
),
|
||||||
else ...[
|
],
|
||||||
if (isTakenToday)
|
],
|
||||||
|
),
|
||||||
|
if (widget.supplement.brand != null && widget.supplement.brand!.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
widget.supplement.brand!,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
color: widget.showCompletionStatus ? (isCompletelyTaken
|
||||||
|
? Colors.green.shade200
|
||||||
|
: isTakenToday
|
||||||
|
? Theme.of(context).colorScheme.secondary
|
||||||
|
: Theme.of(context).colorScheme.primary) : Theme.of(context).colorScheme.primary,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'${widget.supplement.frequencyPerDay}x daily • ${widget.supplement.numberOfUnits} ${widget.supplement.unitType}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
color: ShadTheme.of(context).colorScheme.foreground.withValues(alpha: 0.7),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (widget.showCompletionStatus && isTakenToday && !isCompletelyTaken) ...[
|
||||||
|
const SizedBox(width: 8),
|
||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||||
margin: const EdgeInsets.only(right: 8),
|
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.secondary,
|
color: Theme.of(context).colorScheme.secondary,
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(8),
|
||||||
),
|
),
|
||||||
child: Text(
|
child: Text(
|
||||||
'$todayIntakeCount/${widget.supplement.frequencyPerDay}',
|
'$todayIntakeCount/${widget.supplement.frequencyPerDay}',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: Theme.of(context).colorScheme.onSecondary,
|
color: Theme.of(context).colorScheme.onSecondary,
|
||||||
fontSize: 10,
|
fontSize: 9,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
|
||||||
onPressed: widget.onTake,
|
|
||||||
style: ElevatedButton.styleFrom(
|
|
||||||
backgroundColor: isCompletelyTaken
|
|
||||||
? Colors.green.shade500
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
foregroundColor: Theme.of(context).colorScheme.inverseSurface,
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
|
||||||
minimumSize: const Size(60, 32),
|
|
||||||
shape: RoundedRectangleBorder(
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
isCompletelyTaken ? '✓' : 'Take',
|
|
||||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
],
|
|
||||||
),
|
|
||||||
trailing: PopupMenuButton(
|
|
||||||
padding: EdgeInsets.zero,
|
|
||||||
icon: Icon(
|
|
||||||
Icons.more_vert,
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Theme.of(context).colorScheme.inverseSurface
|
|
||||||
: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
onSelected: (value) {
|
|
||||||
switch (value) {
|
|
||||||
case 'edit':
|
|
||||||
widget.onEdit();
|
|
||||||
break;
|
|
||||||
case 'duplicate':
|
|
||||||
widget.onDuplicate();
|
|
||||||
break;
|
|
||||||
case 'archive':
|
|
||||||
widget.onArchive();
|
|
||||||
break;
|
|
||||||
case 'delete':
|
|
||||||
widget.onDelete();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
itemBuilder: (context) => [
|
|
||||||
if (isTakenToday)
|
|
||||||
PopupMenuItem(
|
|
||||||
value: 'take',
|
|
||||||
onTap: widget.onTake,
|
|
||||||
child: const Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.add_circle_outline),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Take Again'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'edit',
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.edit),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Edit'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'duplicate',
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.copy),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Duplicate'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'archive',
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.archive, color: Colors.orange),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Archive'),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const PopupMenuItem(
|
|
||||||
value: 'delete',
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.delete, color: Colors.red),
|
|
||||||
SizedBox(width: 8),
|
|
||||||
Text('Delete', style: TextStyle(color: Colors.red)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
children: [
|
|
||||||
// Today's intake times (if any) - only show in expanded view
|
|
||||||
if (todayIntakes.isNotEmpty) ...[
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade700.withOpacity(0.8)
|
|
||||||
: Theme.of(context).colorScheme.secondaryContainer.withOpacity(0.7),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade500
|
|
||||||
: Theme.of(context).colorScheme.secondary,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.check_circle_outline,
|
|
||||||
size: 16,
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade200
|
|
||||||
: Theme.of(context).colorScheme.onSecondaryContainer,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Text(
|
|
||||||
'Taken today:',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade200
|
|
||||||
: Theme.of(context).colorScheme.onSecondaryContainer,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
Wrap(
|
|
||||||
spacing: 8,
|
|
||||||
runSpacing: 4,
|
|
||||||
children: todayIntakes.map((intake) {
|
|
||||||
final units = intake['units'] as double;
|
|
||||||
final unitsText = units == 1.0
|
|
||||||
? '${widget.supplement.unitType}'
|
|
||||||
: '${units.toStringAsFixed(units % 1 == 0 ? 0 : 1)} ${widget.supplement.unitType}';
|
|
||||||
|
|
||||||
return Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.green.shade600
|
|
||||||
: Theme.of(context).colorScheme.secondary,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
'${intake['time']} • $unitsText',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 10,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
color: isCompletelyTaken
|
|
||||||
? Colors.white
|
|
||||||
: Theme.of(context).colorScheme.onSecondary,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}).toList(),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
],
|
|
||||||
|
|
||||||
// Ingredients section
|
|
||||||
Container(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
'Ingredients per ${widget.supplement.unitType}:',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Wrap(
|
|
||||||
spacing: 8,
|
|
||||||
runSpacing: 4,
|
|
||||||
children: widget.supplement.ingredients.map((ingredient) {
|
|
||||||
return Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(
|
|
||||||
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
'${ingredient.name} ${ingredient.amount}${ingredient.unit}',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 11,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
color: Theme.of(context).colorScheme.primary,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}).toList(),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
|
|
||||||
// Schedule and dosage info
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: _InfoChip(
|
|
||||||
icon: Icons.schedule,
|
|
||||||
label: '${widget.supplement.frequencyPerDay}x daily',
|
|
||||||
context: context,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: _InfoChip(
|
|
||||||
icon: Icons.medication,
|
|
||||||
label: '${widget.supplement.numberOfUnits} ${widget.supplement.unitType}',
|
|
||||||
context: context,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
|
|
||||||
if (widget.supplement.reminderTimes.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
_InfoChip(
|
|
||||||
icon: Icons.notifications,
|
|
||||||
label: 'Reminders: ${widget.supplement.reminderTimes.join(', ')}',
|
|
||||||
context: context,
|
|
||||||
fullWidth: true,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
|
|
||||||
if (widget.supplement.notes != null && widget.supplement.notes!.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding: const EdgeInsets.all(8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.2),
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
widget.supplement.notes!,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
|
|
||||||
// Take button
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton.icon(
|
|
||||||
onPressed: widget.onTake,
|
|
||||||
icon: Icon(
|
|
||||||
isCompletelyTaken ? Icons.check_circle : Icons.medication,
|
|
||||||
size: 18,
|
|
||||||
),
|
|
||||||
label: Text(
|
|
||||||
isCompletelyTaken
|
|
||||||
? 'All doses taken today'
|
|
||||||
: isTakenToday
|
|
||||||
? 'Take next dose'
|
|
||||||
: 'Take supplement',
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
|
||||||
),
|
|
||||||
style: ElevatedButton.styleFrom(
|
|
||||||
backgroundColor: isCompletelyTaken
|
|
||||||
? Colors.green.shade500
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
foregroundColor: Colors.white,
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
|
||||||
shape: RoundedRectangleBorder(
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
),
|
|
||||||
elevation: isCompletelyTaken ? 0 : 2,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -516,7 +334,7 @@ class _InfoChip extends StatelessWidget {
|
|||||||
width: fullWidth ? double.infinity : null,
|
width: fullWidth ? double.infinity : null,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.4),
|
color: Theme.of(context).colorScheme.surfaceContainerHighest.withValues(alpha: 0.4),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -544,3 +362,4 @@ class _InfoChip extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
143
pubspec.lock
143
pubspec.lock
@@ -33,6 +33,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.1.2"
|
version: "2.1.2"
|
||||||
|
boxy:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: boxy
|
||||||
|
sha256: "71af0cd1bf7889c09787f26219a345aa4f38ccb98384c8ec24189e4d8e746005"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.2.1"
|
||||||
characters:
|
characters:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -129,6 +137,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.7"
|
version: "2.0.7"
|
||||||
|
extended_image:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: extended_image
|
||||||
|
sha256: f6cbb1d798f51262ed1a3d93b4f1f2aa0d76128df39af18ecb77fa740f88b2e0
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "10.0.1"
|
||||||
|
extended_image_library:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: extended_image_library
|
||||||
|
sha256: "1f9a24d3a00c2633891c6a7b5cab2807999eb2d5b597e5133b63f49d113811fe"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.0.1"
|
||||||
fake_async:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -166,6 +190,14 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_animate:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_animate
|
||||||
|
sha256: "7befe2d3252728afb77aecaaea1dec88a89d35b9b1d2eea6d04479e8af9117b5"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.5.2"
|
||||||
flutter_fgbg:
|
flutter_fgbg:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -214,6 +246,11 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.0.2"
|
version: "1.0.2"
|
||||||
|
flutter_localizations:
|
||||||
|
dependency: transitive
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.0"
|
||||||
flutter_secure_storage:
|
flutter_secure_storage:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -263,6 +300,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.0.0"
|
version: "4.0.0"
|
||||||
|
flutter_shaders:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_shaders
|
||||||
|
sha256: "34794acadd8275d971e02df03afee3dee0f98dbfb8c4837082ad0034f612a3e2"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.1.3"
|
||||||
|
flutter_svg:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_svg
|
||||||
|
sha256: cd57f7969b4679317c17af6fd16ee233c1e60a82ed209d8a475c54fd6fd6f845
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.2.0"
|
||||||
flutter_test:
|
flutter_test:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description: flutter
|
description: flutter
|
||||||
@@ -281,6 +334,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.5.0"
|
version: "1.5.0"
|
||||||
|
http_client_helper:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: http_client_helper
|
||||||
|
sha256: "8a9127650734da86b5c73760de2b404494c968a3fd55602045ffec789dac3cb1"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.0.0"
|
||||||
http_parser:
|
http_parser:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -297,6 +358,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.20.2"
|
version: "0.20.2"
|
||||||
|
js:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: js
|
||||||
|
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.7.2"
|
||||||
json_annotation:
|
json_annotation:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -345,6 +414,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.3.0"
|
version: "1.3.0"
|
||||||
|
lucide_icons_flutter:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: lucide_icons_flutter
|
||||||
|
sha256: c88e3611c0aa272ca2f2aa263662174ae4996f5e3ee1c300021514df230b6588
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.0.9"
|
||||||
matcher:
|
matcher:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -401,6 +478,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.9.1"
|
version: "1.9.1"
|
||||||
|
path_parsing:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_parsing
|
||||||
|
sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.0"
|
||||||
path_provider:
|
path_provider:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -473,6 +558,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.1.8"
|
version: "2.1.8"
|
||||||
|
popover:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: popover
|
||||||
|
sha256: "0606f3e10f92fc0459f5c52fd917738c29e7552323b28694d50c2d3312d0e1a2"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.1"
|
||||||
provider:
|
provider:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -489,6 +582,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.28.0"
|
version: "0.28.0"
|
||||||
|
shadcn_ui:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: shadcn_ui
|
||||||
|
sha256: "628d1a7f36e4c764dae3b86b38abb086adf39ccea0073960f481777d1880f90d"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.29.2"
|
||||||
shared_preferences:
|
shared_preferences:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -678,6 +779,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.10.1"
|
version: "0.10.1"
|
||||||
|
two_dimensional_scrollables:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: two_dimensional_scrollables
|
||||||
|
sha256: "0f77ecb96596f2f82eec2b0a8e60d9305c58315557da9fa3b610c7dbf5ded621"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.7"
|
||||||
typed_data:
|
typed_data:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -686,6 +795,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.0"
|
version: "1.4.0"
|
||||||
|
universal_image:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: universal_image
|
||||||
|
sha256: ef47a4a002158cf0b36ed3b7605af132d2476cc42703e41b8067d3603705c40d
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.0.11"
|
||||||
url_launcher:
|
url_launcher:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -758,6 +875,30 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.5.1"
|
version: "4.5.1"
|
||||||
|
vector_graphics:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: vector_graphics
|
||||||
|
sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.19"
|
||||||
|
vector_graphics_codec:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: vector_graphics_codec
|
||||||
|
sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.13"
|
||||||
|
vector_graphics_compiler:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: vector_graphics_compiler
|
||||||
|
sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.19"
|
||||||
vector_math:
|
vector_math:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -816,4 +957,4 @@ packages:
|
|||||||
version: "6.6.1"
|
version: "6.6.1"
|
||||||
sdks:
|
sdks:
|
||||||
dart: ">=3.9.0 <4.0.0"
|
dart: ">=3.9.0 <4.0.0"
|
||||||
flutter: ">=3.29.0"
|
flutter: ">=3.32.0"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
name: supplements
|
name: supplements
|
||||||
description: "A supplement tracking app for managing your daily supplements"
|
description: "A supplement tracking app for managing your daily supplements"
|
||||||
publish_to: "none"
|
publish_to: "none"
|
||||||
version: 1.0.7+30082025
|
version: 1.0.10+05092025
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.9.0
|
sdk: ^3.9.0
|
||||||
@@ -29,6 +29,10 @@ dependencies:
|
|||||||
# Date time handling
|
# Date time handling
|
||||||
intl: ^0.20.2
|
intl: ^0.20.2
|
||||||
|
|
||||||
|
# UI components
|
||||||
|
shadcn_ui: ^0.29.2
|
||||||
|
popover: ^0.3.0
|
||||||
|
|
||||||
# WebDAV sync functionality
|
# WebDAV sync functionality
|
||||||
webdav_client: ^1.2.2
|
webdav_client: ^1.2.2
|
||||||
connectivity_plus: ^6.1.5
|
connectivity_plus: ^6.1.5
|
||||||
|
|||||||
Reference in New Issue
Block a user