Services API Reference

Business logic coordinators for auth, events, API integration, and HTTP.

EventService

lib/core/services/event_service.dart

The central coordination point for all event mutations. Eliminates the duplicated "update provider + persist to repository" pattern by providing a single API that handles both.

Constructor

EventService({ required EventProvider provider, EventRepository? repository, // defaults to EventRepository() })

Methods

MethodSignatureDescription
loadEvents()Future<void>Loads persisted events from SQLite into the provider. Only populates if provider is empty (avoids overwriting session data).
addEvent(event)Future<void>Adds to provider (instant), then persists to SQLite (async).
updateEvent(event)Future<void>Updates in provider (instant), then persists (async).
deleteEvent(id)Future<void>Removes from provider (instant), then deletes from SQLite (async).
Fire-and-Forget Pattern All persistence operations are wrapped in try/catch. The in-memory state is always updated first, so the UI stays responsive even if disk I/O fails. Errors are logged via debugPrint.

Usage Example

final service = EventService( provider: context.read<EventProvider>(), ); // Load persisted events on app start await service.loadEvents(); // Add a new event await service.addEvent(EventModel( id: 'uuid-123', title: 'Team Standup', date: DateTime.now(), priority: EventPriority.high, )); // Delete an event await service.deleteEvent('uuid-123');

AuthService

lib/core/services/auth_service.dart

Wraps Firebase Auth with typed exception handling. All Firebase error codes are mapped to structured AuthException instances.

Properties

PropertyTypeDescription
currentUserUser?Currently signed-in Firebase user
authStateChangesStream<User?>Stream of auth state changes (used by AuthGate)

Methods

MethodSignatureDescription
loginWithEmail(String email, String password) โ†’ Future<User?>Sign in with email/password
signUpWithEmail(String email, String password) โ†’ Future<User?>Create new account
resetPassword(String email) โ†’ Future<void>Send password reset email
logout() โ†’ Future<void>Sign out

Error Handling

All methods throw AuthException with mapped error codes:

Firebase CodeMapped Code
user-not-founduser-not-found
wrong-passwordwrong-password
email-already-in-useemail-already-in-use
weak-passwordweak-password
invalid-emailinvalid-email
OthersOriginal Firebase code

GraphService

lib/core/services/graph_service.dart

Microsoft Graph API client for calendar event synchronization. Handles pagination with SSRF protection.

Constructor

GraphService(String accessToken)

Methods

MethodSignatureDescription
fetchCalendarEvents()Future<List<Map<String, dynamic>>>Fetches all calendar events with automatic pagination (up to 50 pages). Validates pagination URLs against trusted hosts.
SSRF Protection The first API request URL is constructed internally. Subsequent pagination URLs from @odata.nextLink are validated against AppConstants.trustedApiHosts to prevent server-side request forgery. See the Security Guide for details.

Error Handling

Throws GraphServiceException when:

HttpUtils

lib/core/utils/http_utils.dart

Static HTTP utility class with built-in security validation.

Methods

MethodDescription
getRequest(url, {headers, timeout, requireTrustedHost})HTTPS GET with scheme validation and optional trusted-host enforcement
postRequest(url, body, {headers, timeout})HTTPS POST with JSON encoding and scheme validation

Security Features

Exception Types

ExceptionFieldsWhen Thrown
HttpExceptionstatusCode, responseBodyNon-200 HTTP response
HttpSecurityExceptionmessageBlocked scheme or untrusted host

Service Catalog

Complete reference for all 55 services in lib/core/services/, organized by domain.

๐Ÿ“… Calendar & Events

EventSearchService

lib/core/services/event_search_service.dart

Full-text search across events with field-weighted scoring, fuzzy matching, and date/category/priority filters.

MethodSignatureDescription
search(String query, List<EventModel> events, {SearchFilters?}) โ†’ List<SearchResult>Search events with relevance scoring and highlighting
suggest(String partial, List<EventModel> events) โ†’ List<String>Autocomplete suggestions from partial input

EventSharingService

lib/core/services/event_sharing_service.dart

Export events as plain text, Markdown, Google Calendar URLs, or Outlook web links.

MethodSignatureDescription
share(EventModel, {ShareFormat}) โ†’ StringFormat event for sharing (plainText, markdown, googleCalendar, outlook)

EventPatternService

lib/core/services/event_pattern_service.dart

Detects recurring patterns and scheduling habits from historical events, then predicts future occurrences.

MethodSignatureDescription
detectPatterns(List<EventModel>) โ†’ List<EventPattern>Identify day-of-week, time-of-day, and category patterns
predict(List<EventModel>, {int days}) โ†’ List<EventPrediction>Predict future events based on detected patterns

EventDeduplicationService

lib/core/services/event_deduplication_service.dart

Finds duplicate events using title similarity, time proximity, and location matching.

MethodSignatureDescription
scanHighConfidence(List<EventModel>) โ†’ List<DuplicateMatch>Scan all events for high-confidence duplicates
findDuplicatesOf(EventModel, List<EventModel>) โ†’ List<DuplicateMatch>Find duplicates of a specific event

ConflictDetector

lib/core/services/conflict_detector.dart

Detects time overlaps between events, checks for conflicts, and suggests alternative time slots.

MethodSignatureDescription
conflictsFor(String eventId) โ†’ List<EventConflict>Get all conflicts for an event
wouldConflict(EventModel, List<EventModel>) โ†’ boolCheck if a new event would conflict with existing ones
suggestAlternatives(EventModel, List<EventModel>) โ†’ List<DateTime>Suggest conflict-free time slots

DependencyTracker

lib/core/services/dependency_tracker.dart

Tracks event dependencies (blocked-by, blocks) and computes critical paths through event chains.

MethodSignatureDescription
addDependency(EventDependency) โ†’ voidRegister a dependency between two events
removeDependency(String fromId, String toId) โ†’ voidRemove a dependency link
criticalPath() โ†’ CriticalPathCompute the longest dependency chain

FreeSlotFinder

lib/core/services/free_slot_finder.dart

Identifies free time slots between existing events. Suggests optimal windows for new events based on duration and preferences.

MethodSignatureDescription
suggestBestSlots({Duration needed, ...}) โ†’ List<FreeSlot>Find best available slots for a given duration
slotsForDuration(Duration needed) โ†’ List<FreeSlot>Filter slots that can fit the needed duration

SnoozeService

lib/core/services/snooze_service.dart

Snooze event reminders with predefined options (15 min, 1 hour, tomorrow, next week). Tracks snooze history per event.

MethodSignatureDescription
computeSnoozeDate(EventModel, String optionId) โ†’ DateTime?Calculate when a snoozed event should reappear
getHistory(String eventId) โ†’ List<SnoozeRecord>Snooze history for an event

TemplateService

lib/core/services/template_service.dart

Manage reusable event templates. Ships with built-in templates and supports custom user-created ones.

MethodSignatureDescription
addTemplate(EventTemplate) โ†’ boolAdd a custom template
search(String query) โ†’ List<EventTemplate>Search templates by title/description
reorderTemplate(int oldIndex, int newIndex) โ†’ boolReorder template list

IcsExportService

lib/core/services/ics_export_service.dart

Export events to iCalendar (.ics) format with recurrence rules, alarms, and multi-event calendar support.

MethodSignatureDescription
exportEvent(EventModel) โ†’ StringExport a single event as .ics
exportEvents(List<EventModel>) โ†’ StringExport multiple events as one .ics calendar

โฑ๏ธ Time Management

FocusTimeService

lib/core/services/focus_time_service.dart

Track deep focus sessions. Measures fragmentation, daily focus totals, and flow-state streaks.

MethodSignatureDescription
todaysFocusBlocks(List<EventModel>) โ†’ List<FocusBlock>Get today's focus blocks from events
todaysFragmentation(List<EventModel>) โ†’ double0.0 (solid block) to 1.0 (fully fragmented)
weeklyFocusTrend(...) โ†’ List<DailyFocusSummary>7-day focus trend data

PomodoroService

lib/core/services/pomodoro_service.dart

Pomodoro timer with configurable work/break durations, automatic phase transitions, and session tracking.

MethodSignatureDescription
phaseDuration(PomodoroPhase) โ†’ intDuration in minutes for a given phase
completeCurrentSession() โ†’ voidMark current pomodoro session complete
reset() โ†’ voidReset timer state

TimeTrackerService

lib/core/services/time_tracker_service.dart

Manual time tracking for projects and tasks with start/stop logging and category breakdowns.

TimeAuditService

lib/core/services/time_audit_service.dart

Analyzes how time was spent across categories. Computes category breakdowns, daily summaries, and generates recommendations for better time allocation.

TimeBudgetService

lib/core/services/time_budget_service.dart

Set weekly/monthly time budgets per category and track actual vs. budgeted hours.

DailyTimelineService

lib/core/services/daily_timeline_service.dart

Builds a chronological timeline of the day's events and free gaps. Detects overlaps and renders as text.

MethodSignatureDescription
buildTimeline({List<EventModel>, DateTime, ...}) โ†’ List<TimelineBlock>Build blocks for a given day
formatAsText(List<TimelineBlock>) โ†’ StringRender timeline as formatted text

EisenhowerMatrixService

lib/core/services/eisenhower_matrix_service.dart

Classifies events into the Eisenhower Matrix (urgent/important, urgent/not-important, etc.) with computed urgency and importance scores.

MethodSignatureDescription
computeUrgency(EventModel, DateTime now) โ†’ doubleScore 0โ€“1 based on deadline proximity
computeImportance(EventModel) โ†’ doubleScore 0โ€“1 based on priority and metadata
getRecommendations(MatrixSummary) โ†’ List<String>Actionable advice based on quadrant distribution

ProductivityScoreService

lib/core/services/productivity_score_service.dart

Computes a daily productivity score (0โ€“100) from events, habits, goals, sleep, mood, and focus time with configurable weights.

MethodSignatureDescription
scoreEvents(List<EventModel>, DateTime) โ†’ doubleEvent completion sub-score
scoreHabits(List<Habit>, ...) โ†’ doubleHabit adherence sub-score
scoreGoals(List<Goal>, DateTime) โ†’ doubleGoal progress sub-score
scoreSleep(List<SleepEntry>, DateTime) โ†’ doubleSleep quality sub-score
scoreFocus(int focusMinutes) โ†’ doubleFocus time sub-score

StreakTracker

lib/core/services/streak_tracker.dart

Tracks consecutive-day streaks for recurring events. Supports current streak, longest streak, and gap detection.

MethodSignatureDescription
currentStreakLength(List<EventModel>, {bool includeRecurring}) โ†’ intCurrent consecutive-day streak
longestStreakLength(List<EventModel>, {bool includeRecurring}) โ†’ intAll-time longest streak

๐Ÿฅ Health & Wellness

SleepTrackerService

lib/core/services/sleep_tracker_service.dart

Tracks sleep entries with duration, quality rating, and notes. Persists to storage and provides date-range queries.

MethodSignatureDescription
addEntry(SleepEntry) โ†’ Future<void>Log a sleep entry
entriesForDate(DateTime) โ†’ List<SleepEntry>Sleep entries for a specific date
averageQuality(DateTime start, DateTime end) โ†’ doubleAverage sleep quality in range

WorkoutTrackerService

lib/core/services/workout_tracker_service.dart

Log workouts with exercises, sets, reps, and duration. Provides weekly summaries and personal records.

MeditationTrackerService

lib/core/services/meditation_tracker_service.dart

Track meditation sessions with type, duration, and mood. Includes config for daily goals and technique preferences.

MethodSignatureDescription
addSession(MeditationEntry) โ†’ voidLog a meditation session
getSessionsForDate(DateTime) โ†’ List<MeditationEntry>Sessions for a specific date
currentStreak() โ†’ intConsecutive days with at least one session

WaterTrackerService

lib/core/services/water_tracker_service.dart

Track daily water intake against a configurable goal. Supports multiple entry types (glass, bottle, etc.).

MealTrackerService

lib/core/services/meal_tracker_service.dart

Log meals with nutritional data, meal type (breakfast/lunch/dinner/snack), and calorie tracking against daily goals.

MethodSignatureDescription
getMealsForDate(DateTime) โ†’ List<MealEntry>All meals on a given date
getMealsByType(MealType) โ†’ List<MealEntry>Filter by meal type
dailyNutrition(DateTime) โ†’ NutritionSummaryAggregated nutrition for a day

MedicationTrackerService

lib/core/services/medication_tracker_service.dart

Track medication schedules, dose logging, adherence rates, and streaks. Grades adherence (Aโ€“F).

MethodSignatureDescription
adherenceRate(Medication, List<DoseLog>, DateTime from, DateTime to) โ†’ double0.0โ€“1.0 adherence rate in date range
currentStreak(Medication, List<DoseLog>) โ†’ intConsecutive days with dose logged
adherenceGrade(double rate) โ†’ StringLetter grade (A/B/C/D/F)

EnergyTrackerService

lib/core/services/energy_tracker_service.dart

Track energy levels throughout the day. Analyzes time-slot patterns, factor impacts, and generates recommendations.

MethodSignatureDescription
timeSlotAverages(List<EnergyEntry>) โ†’ List<TimeSlotAverage>Average energy by time of day
energyBoosters(List<EnergyEntry>) โ†’ List<FactorImpact>Factors that increase energy
energyDrainers(List<EnergyEntry>) โ†’ List<FactorImpact>Factors that decrease energy
recommendations(List<EnergyEntry>) โ†’ List<EnergyRecommendation>Personalized energy optimization tips

MoodJournalService

lib/core/services/mood_journal_service.dart

Async-persistent mood journal with CRUD operations. Entries include mood level, tags, and free-text notes.

MethodSignatureDescription
addEntry(MoodEntry) โ†’ Future<void>Log a mood entry
entriesForDate(DateTime) โ†’ List<MoodEntry>Entries for a specific date
averageMood(DateTime start, DateTime end) โ†’ doubleAverage mood in date range

๐Ÿ’ฐ Finance

ExpenseTrackerService

lib/core/services/expense_tracker_service.dart

Track expenses with categories, budget limits, and period-based summaries. Supports recurring entries and CSV export.

MethodSignatureDescription
addEntry(ExpenseEntry) โ†’ voidLog an expense
getEntriesInRange(DateTime start, DateTime end) โ†’ List<ExpenseEntry>Expenses in date range
categoryBreakdown(...) โ†’ Map<String, double>Spending by category

BudgetPlannerService

lib/core/services/budget_planner_service.dart

Set monthly budgets per category. Compares actual vs. budgeted spending with adherence scores and monthly trends.

MethodSignatureDescription
getBudgetComparison(int year, int month, ...) โ†’ List<BudgetComparison>Actual vs. budgeted per category
getOverspendingCategories(...) โ†’ List<BudgetComparison>Categories exceeding budget
getSavingsRate(List<ExpenseEntry>, int year, int month) โ†’ doubleMonthly savings rate
getBudgetAdherenceScore(...) โ†’ int0โ€“100 score of budget compliance

SavingsGoalService

lib/core/services/savings_goal_service.dart

Create savings goals with target amounts and deadlines. Track contributions, monthly savings trends, and import/export as JSON.

MethodSignatureDescription
addContribution(String goalId, ...) โ†’ voidAdd a contribution toward a goal
monthlySavings(int year, int month) โ†’ doubleTotal saved in a month
savingsHistory({int months}) โ†’ List<MonthlySavingsPoint>Monthly savings trend data
exportJson / importJson() โ†’ String / (String) โ†’ voidFull data export/import

SubscriptionTrackerService

lib/core/services/subscription_tracker_service.dart

Manage recurring subscriptions with billing cycles, pause/cancel support, and upcoming billing alerts.

MethodSignatureDescription
add / update / removeCRUD operationsManage subscription entries
cancel / pause / resume(String id) โ†’ voidSubscription lifecycle control
monthlyTotal() โ†’ doubleTotal monthly subscription cost

๐ŸŒฑ Personal Growth

HabitTrackerService

lib/core/services/habit_tracker_service.dart

Full habit tracking with streaks, archiving, completion logging, and detailed stats (rate, best streak, total completions).

MethodSignatureDescription
addHabit / updateHabitCRUD operationsManage habits
logCompletion(String habitId, DateTime, {String? note}) โ†’ voidMark habit as done for a day
getStats(String habitId) โ†’ HabitStatsCurrent streak, best streak, completion rate

SkillTrackerService

lib/core/services/skill_tracker_service.dart

Track skill development with practice sessions, proficiency levels, and progress reports.

MethodSignatureDescription
logPractice(String skillId, PracticeSession) โ†’ voidLog a practice session
getReport(String skillId) โ†’ SkillReportProgress report with total hours and trends

ReadingListService

lib/core/services/reading_list_service.dart

Manage a reading list with book status (to-read/reading/finished), reading challenges, and progress tracking.

MethodSignatureDescription
addBook / removeBook / updateBookCRUD operationsManage book list
setChallenge(ReadingChallenge) โ†’ voidSet yearly reading challenge
readingSpeed() โ†’ doubleAverage pages per day

GratitudeJournalService

lib/core/services/gratitude_journal_service.dart

Daily gratitude journal with tagging, favorites, date-range queries, and streak tracking.

MethodSignatureDescription
addEntry({required String text, ...}) โ†’ StringAdd a gratitude entry (returns ID)
toggleFavorite(String id) โ†’ boolToggle favorite status
getStreak() โ†’ intConsecutive days with entries

DecisionJournalService

lib/core/services/decision_journal_service.dart

Log decisions with category, importance, expected/actual outcomes, and lessons learned. Search and date-range filtering.

MethodSignatureDescription
byCategory(DecisionCategory) โ†’ List<DecisionEntry>Filter by decision category
search(String query) โ†’ List<DecisionEntry>Search decisions by text
allLessonsLearned() โ†’ List<String>All recorded lessons across decisions

DailyReviewService

lib/core/services/daily_review_service.dart

End-of-day reviews: save accomplishments, plan tomorrow's events, and rate the day.

MethodSignatureDescription
saveReview(DailyReview) โ†’ voidSave a daily review
tomorrowEvents(DateTime today) โ†’ List<EventModel>Pre-load tomorrow's schedule for planning
topAccomplishments(DateTime) โ†’ List<EventModel>Completed events ranked by importance

GoalTrackerService

lib/core/services/goal_tracker_service.dart

Set long-term goals with milestones, deadlines, and progress tracking. Archive or complete goals.

MethodSignatureDescription
addGoal / updateGoal / deleteGoalCRUD operationsGoal lifecycle management
toggleMilestone(String goalId, String milestoneId) โ†’ voidMark milestone complete/incomplete
archiveGoal / completeGoal(String goalId) โ†’ voidArchive or mark goal as achieved

AchievementService

lib/core/services/achievement_service.dart

Gamification system: register achievement definitions, track progress, award badges, and level up.

MethodSignatureDescription
register(AchievementDefinition) โ†’ boolRegister an achievement type
updateProgress(String achievementId, int value) โ†’ voidUpdate progress toward achievement
updateProgressBatch(Map<String, int>) โ†’ voidBatch update multiple achievements
isEarned(String achievementId) โ†’ boolCheck if achievement is unlocked
getAllProgress() โ†’ List<AchievementProgress>Progress for all registered achievements

๐Ÿก Life Management

ContactTrackerService

lib/core/services/contact_tracker_service.dart

Track personal and professional contacts with interaction logging, categories, archival, and relationship analytics.

MethodSignatureDescription
logInteraction({required String contactId, ...}) โ†’ InteractionRecord a contact interaction
byCategory(RelationshipCategory) โ†’ List<Contact>Filter contacts by category
archiveContact / unarchiveContact(String id) โ†’ voidArchive/restore contacts

ChoreTrackerService

lib/core/services/chore_tracker_service.dart

Manage household chores with recurrence schedules, overdue detection, streak tracking, and quality ratings.

MethodSignatureDescription
isOverdue(Chore, List<ChoreCompletion>) โ†’ boolCheck if a chore is overdue
daysUntilDue(Chore, List<ChoreCompletion>) โ†’ intDays until next due date
currentStreak(Chore, List<ChoreCompletion>) โ†’ intConsecutive on-time completions
adherenceRate(...) โ†’ double% of chores completed on time

PetCareService

lib/core/services/pet_care_service.dart

Track pet care activities (feeding, walks, vet visits), health records, costs, and overdue checkups.

MethodSignatureDescription
todayEntries(List<CareEntry>, String petId) โ†’ List<CareEntry>Today's care entries for a pet
careStreak(List<CareEntry>, String petId) โ†’ intConsecutive days with care logged
overdueRecords(List<HealthRecord>, String petId) โ†’ List<HealthRecord>Overdue health checkups
totalCost(List<CareEntry>, String petId) โ†’ doubleTotal care spending for a pet

PlantCareService

lib/core/services/plant_care_service.dart

Track plant care with watering schedules, care logs, and last-watered dates.

MethodSignatureDescription
addPlant / removePlantCRUD operationsManage plant inventory
getCareLog(String plantId, {int? limit}) โ†’ List<PlantCareEntry>Care history for a plant
getLastWatered(String plantId) โ†’ DateTime?Last watering date

ScreenTimeTrackerService

lib/core/services/screen_time_tracker_service.dart

Track screen time by app/category. Set daily goals and per-app/category limits with alert generation.

MethodSignatureDescription
addEntry(ScreenTimeEntry) โ†’ voidLog screen time
setDailyGoal(int minutes) โ†’ voidSet max daily screen time
addLimit / removeLimit({String? appName, AppCategory?}) โ†’ voidPer-app or per-category limits

RoutineBuilderService

lib/core/services/routine_builder_service.dart

Build daily routines with ordered steps. Schedule routines for specific days and track completion runs.

MethodSignatureDescription
addRoutine / updateRoutine / removeRoutineCRUD operationsManage routines
getRoutinesForDate(DateTime) โ†’ List<Routine>Routines scheduled for a date
getTotalMinutesForDate(DateTime) โ†’ intTotal routine time for a date

๐Ÿ“Š Planning & Analytics

AgendaDigestService

lib/core/services/agenda_digest_service.dart

Generates daily/weekly agenda digests from events. Outputs as plain text or Markdown, sorted by priority.

MethodSignatureDescription
formatText(AgendaDigest) โ†’ StringPlain text agenda
formatMarkdown(AgendaDigest) โ†’ StringMarkdown-formatted agenda

WeeklyPlannerService

lib/core/services/weekly_planner_service.dart

Plan weekly goals and tasks across days with drag-and-drop reordering and completion tracking.

WeeklyReportService

lib/core/services/weekly_report_service.dart

Generate weekly summary reports: events completed, habits tracked, goals progressed, and overall productivity trends.

HeatmapService

lib/core/services/heatmap_service.dart

Generates activity heatmap data (GitHub contribution graph style). Configurable intensity thresholds per data type.

LifeDashboardService

lib/core/services/life_dashboard_service.dart

Aggregates data across all domains (health, finance, productivity, relationships) into a single life dashboard with dimension scores and trend history.

CorrelationAnalyzerService

lib/core/services/correlation_analyzer_service.dart

Statistical analysis: computes Pearson correlations between life metrics (sleep vs. mood, exercise vs. productivity, etc.) and generates plain-English insights.

MethodSignatureDescription
buildSnapshots({...}) โ†’ List<DailySnapshot>Aggregate daily metrics from all trackers
analyze(List<DailySnapshot>) โ†’ List<Correlation>Compute Pearson correlations between metrics

โš™๏ธ Core Infrastructure

SecureStorageService

lib/core/services/secure_storage_service.dart

Wrapper around platform secure storage for sensitive data (tokens, credentials). Provides a simple key-value API.