Wellness & Productivity Services

Services for sleep tracking, mood journaling, habit tracking, goal management, and focused work sessions.

All wellness services follow a consistent pattern: SharedPreferences-backed persistence, lazy initialization via init(), sorted-descending storage, and analytics methods that operate on the in-memory list. Each service owns a single storage key and is independent of the others.

Common Pattern init()addEntry() / deleteEntry() / updateEntry() → analytics methods. All mutations call _save() automatically. Services are safe to call before init() — they self-initialize on first data access.

SleepTrackerService

lib/core/services/sleep_tracker_service.dart

Manages sleep log entries with bedtime/wake time tracking, quality ratings, sleep factor analysis, and trend analytics. Supports sleep debt calculation and schedule consistency scoring.

Data Model

FieldTypeDescription
bedtimeDateTimeWhen the user went to bed
wakeTimeDateTimeWhen the user woke up
qualitySleepQualityRating: terrible (1) → excellent (5)
factorsList<SleepFactor>Contributing factors (caffeine, exercise, stress, etc.)
awakeningsintNumber of times woken during the night
notesString?Optional free-text notes

CRUD Methods

MethodSignatureDescription
init()Future<void>Load entries from SharedPreferences (idempotent)
addEntry(entry)Future<void>Insert at front, auto-save
deleteEntry(id)Future<void>Remove by ID, auto-save
updateEntry(entry)Future<void>Replace by ID, auto-save
entriesForDate(date)List<SleepEntry>Filter entries by wake date
entriesForLastDays(days)List<SleepEntry>Entries within the last N days

Analytics Methods

MethodReturnsDescription
durationTrend(days)Map<DateTime, double>Daily average sleep duration for chart data
qualityTrend(days)Map<DateTime, double>Daily average quality for chart data
overallAvgDuration()double?Lifetime average sleep hours
overallAvgQuality()double?Lifetime average quality (1–5)
avgBedtimeHour(days)double?Average bedtime (0–24), handles midnight normalization
avgWakeTimeHour(days)double?Average wake time (0–24)
factorFrequency()Map<SleepFactor, int>Factor occurrence counts, sorted descending
qualityByFactor()Map<SleepFactor, double>Average quality per factor (correlations)
sleepDebt(days)doubleCumulative hours below target (default 8h)
currentStreak()intConsecutive days with sleep logs
bestStreak()intLongest-ever consecutive logging streak
consistencyScore(days)doubleSchedule consistency (0–100) based on bedtime/wake variance

Usage Example

final service = SleepTrackerService(); await service.init(); // Log last night's sleep await service.addEntry(SleepEntry( id: 'uuid-1', bedtime: DateTime(2026, 3, 2, 23, 15), wakeTime: DateTime(2026, 3, 3, 7, 0), quality: SleepQuality.good, factors: [SleepFactor.exercise, SleepFactor.meditation], )); // Check sleep debt this week final debt = service.sleepDebt(7); // hours below 8h target // Which factors correlate with better sleep? final correlations = service.qualityByFactor();

MoodJournalService

lib/core/services/mood_journal_service.dart

Tracks mood entries with a 5-level rating system, 14 activity tags, and notes. Provides trend analysis, activity-mood correlations, and streak tracking.

Data Model

FieldTypeDescription
moodMoodLevelRating: terrible (1) → great (5)
activitiesList<MoodActivity>What the user was doing (exercise, work, social, etc.)
notesString?Optional journal text
timestampDateTimeWhen the entry was recorded

Methods

MethodReturnsDescription
init()Future<void>Load from SharedPreferences
addEntry(entry)Future<void>Add mood entry, auto-save
deleteEntry(id)Future<void>Remove by ID
entriesForDate(date)List<MoodEntry>Filter by date
averageMoodForDate(date)double?Mean mood level for a day
moodTrend(days)Map<DateTime, double>Daily average mood for charting
activityFrequency()Map<MoodActivity, int>How often each activity appears
moodByActivity()Map<MoodActivity, double>Average mood per activity (correlations)
currentStreak()intConsecutive days with entries
Correlation Insight Use moodByActivity() to discover which activities are associated with higher mood scores. This powers the Insights tab in the Mood Journal screen.

HabitTrackerService

lib/core/services/habit_tracker_service.dart

Manages daily habits with check-off tracking, streak counting, and completion statistics. Habits persist across sessions.

Data Model

FieldTypeDescription
nameStringHabit name (e.g., "Meditate")
iconStringEmoji icon for display
completedDatesSet<DateTime>Dates the habit was completed
createdAtDateTimeWhen the habit was created

Methods

MethodReturnsDescription
addHabit(habit)voidAdd a new habit to track
removeHabit(id)voidRemove a habit
toggleCompletion(id, date)voidToggle check-off for a date
isCompletedOn(id, date)boolCheck if completed on a date
currentStreak(id)intCurrent consecutive-day streak
completionRate(id, days)doubleCompletion percentage over N days
todayProgress()doubleFraction of habits done today (0.0–1.0)

GoalTrackerService

lib/core/services/goal_tracker_service.dart

Manages goals with milestones, progress percentages, deadlines, and categories. Supports urgency sorting and summary statistics.

Data Model

FieldTypeDescription
titleStringGoal name
descriptionString?Detailed description
categoryGoalCategoryHealth, career, finance, education, personal, creative, social
progressintCompletion percentage (0–100)
deadlineDateTime?Optional target date
milestonesList<Milestone>Sub-tasks with individual completion tracking
statusGoalStatusactive, completed, archived

Methods

MethodReturnsDescription
addGoal(goal)voidAdd a new goal
updateGoal(goal)voidReplace an existing goal
deleteGoal(id)voidRemove permanently
completeGoal(id)voidMark as completed (100%)
archiveGoal(id)voidMove to archived
toggleMilestone(goalId, milestoneId)voidToggle milestone completion
updateProgress(goalId, progress)voidSet progress percentage
getSummary()GoalSummaryAggregate stats (active, completed, average progress)
getByUrgency()List<Goal>Active goals sorted by deadline proximity

Computed Properties

PropertyTypeDescription
activeGoalsList<Goal>Goals with status = active
completedGoalsList<Goal>Goals with status = completed
overdueGoalsList<Goal>Active goals past their deadline

PomodoroService

lib/core/services/pomodoro_service.dart

Manages Pomodoro technique work sessions with configurable durations, automatic phase transitions (work → short break → long break), and daily statistics.

Settings

SettingDefaultDescription
workMinutes25Focus session duration
shortBreakMinutes5Break between work sessions
longBreakMinutes15Break after every N work sessions
longBreakInterval4Work sessions before a long break

Methods

MethodReturnsDescription
nextPhase()PomodoroPhaseDetermine next phase based on session count
phaseDuration(phase)intMinutes for the given phase
startSession(phase)PomodoroSessionBegin a new session
completeCurrentSession()voidMark current session as completed
todayStats()PomodoroStatsToday's completed sessions, focus minutes, streak
reset()voidClear all sessions and reset phase counter

Phase Cycle

// Default cycle with longBreakInterval = 4: work → short break → work → short break → work → short break → work → long break → work → ...
Timer Not Included PomodoroService manages phase logic and statistics only. The countdown timer is handled by the UI layer (PomodoroScreen) using Timer.periodic.

DailyReviewService

lib/core/services/daily_review_service.dart

End-of-day reflection service with completion summaries, mood/energy tracking, highlights/lowlights, star ratings, and 7-day trend analysis.

Methods

MethodReturnsDescription
init()Future<void>Load review history from SharedPreferences
addReview(review)Future<void>Save a daily review
reviewForDate(date)DailyReview?Get review for a specific date
recentReviews(days)List<DailyReview>Last N days of reviews
currentStreak()intConsecutive days with reviews
averageRating(days)double?Mean star rating over N days