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
Methods
| Method | Signature | Description |
|---|---|---|
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). |
debugPrint.
Usage Example
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
| Property | Type | Description |
|---|---|---|
currentUser | User? | Currently signed-in Firebase user |
authStateChanges | Stream<User?> | Stream of auth state changes (used by AuthGate) |
Methods
| Method | Signature | Description |
|---|---|---|
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 Code | Mapped Code |
|---|---|
user-not-found | user-not-found |
wrong-password | wrong-password |
email-already-in-use | email-already-in-use |
weak-password | weak-password |
invalid-email | invalid-email |
| Others | Original Firebase code |
GraphService
lib/core/services/graph_service.dart
Microsoft Graph API client for calendar event synchronization. Handles pagination with SSRF protection.
Constructor
Methods
| Method | Signature | Description |
|---|---|---|
fetchCalendarEvents() | Future<List<Map<String, dynamic>>> | Fetches all calendar events with automatic pagination (up to 50 pages). Validates pagination URLs against trusted hosts. |
@odata.nextLink are validated against AppConstants.trustedApiHosts to prevent server-side request forgery. See the Security Guide for details.
Error Handling
Throws GraphServiceException when:
- Response contains an
errorfield (API error) - Response is missing the expected
valuefield - Pagination URL fails trusted host validation
HttpUtils
lib/core/utils/http_utils.dart
Static HTTP utility class with built-in security validation.
Methods
| Method | Description |
|---|---|
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
- Scheme allowlist โ only
httpspermitted (nohttp,file,ftp) - Trusted host validation โ optional enforcement for pagination/redirect URLs
- 30-second default timeout โ prevents hanging connections
Exception Types
| Exception | Fields | When Thrown |
|---|---|---|
HttpException | statusCode, responseBody | Non-200 HTTP response |
HttpSecurityException | message | Blocked 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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
share | (EventModel, {ShareFormat}) โ String | Format 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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
conflictsFor | (String eventId) โ List<EventConflict> | Get all conflicts for an event |
wouldConflict | (EventModel, List<EventModel>) โ bool | Check 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.
| Method | Signature | Description |
|---|---|---|
addDependency | (EventDependency) โ void | Register a dependency between two events |
removeDependency | (String fromId, String toId) โ void | Remove a dependency link |
criticalPath | () โ CriticalPath | Compute 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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
addTemplate | (EventTemplate) โ bool | Add a custom template |
search | (String query) โ List<EventTemplate> | Search templates by title/description |
reorderTemplate | (int oldIndex, int newIndex) โ bool | Reorder 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.
| Method | Signature | Description |
|---|---|---|
exportEvent | (EventModel) โ String | Export a single event as .ics |
exportEvents | (List<EventModel>) โ String | Export 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.
| Method | Signature | Description |
|---|---|---|
todaysFocusBlocks | (List<EventModel>) โ List<FocusBlock> | Get today's focus blocks from events |
todaysFragmentation | (List<EventModel>) โ double | 0.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.
| Method | Signature | Description |
|---|---|---|
phaseDuration | (PomodoroPhase) โ int | Duration in minutes for a given phase |
completeCurrentSession | () โ void | Mark current pomodoro session complete |
reset | () โ void | Reset 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.
| Method | Signature | Description |
|---|---|---|
buildTimeline | ({List<EventModel>, DateTime, ...}) โ List<TimelineBlock> | Build blocks for a given day |
formatAsText | (List<TimelineBlock>) โ String | Render 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.
| Method | Signature | Description |
|---|---|---|
computeUrgency | (EventModel, DateTime now) โ double | Score 0โ1 based on deadline proximity |
computeImportance | (EventModel) โ double | Score 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.
| Method | Signature | Description |
|---|---|---|
scoreEvents | (List<EventModel>, DateTime) โ double | Event completion sub-score |
scoreHabits | (List<Habit>, ...) โ double | Habit adherence sub-score |
scoreGoals | (List<Goal>, DateTime) โ double | Goal progress sub-score |
scoreSleep | (List<SleepEntry>, DateTime) โ double | Sleep quality sub-score |
scoreFocus | (int focusMinutes) โ double | Focus 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.
| Method | Signature | Description |
|---|---|---|
currentStreakLength | (List<EventModel>, {bool includeRecurring}) โ int | Current consecutive-day streak |
longestStreakLength | (List<EventModel>, {bool includeRecurring}) โ int | All-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.
| Method | Signature | Description |
|---|---|---|
addEntry | (SleepEntry) โ Future<void> | Log a sleep entry |
entriesForDate | (DateTime) โ List<SleepEntry> | Sleep entries for a specific date |
averageQuality | (DateTime start, DateTime end) โ double | Average 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.
| Method | Signature | Description |
|---|---|---|
addSession | (MeditationEntry) โ void | Log a meditation session |
getSessionsForDate | (DateTime) โ List<MeditationEntry> | Sessions for a specific date |
currentStreak | () โ int | Consecutive 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.
| Method | Signature | Description |
|---|---|---|
getMealsForDate | (DateTime) โ List<MealEntry> | All meals on a given date |
getMealsByType | (MealType) โ List<MealEntry> | Filter by meal type |
dailyNutrition | (DateTime) โ NutritionSummary | Aggregated 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).
| Method | Signature | Description |
|---|---|---|
adherenceRate | (Medication, List<DoseLog>, DateTime from, DateTime to) โ double | 0.0โ1.0 adherence rate in date range |
currentStreak | (Medication, List<DoseLog>) โ int | Consecutive days with dose logged |
adherenceGrade | (double rate) โ String | Letter 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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
addEntry | (MoodEntry) โ Future<void> | Log a mood entry |
entriesForDate | (DateTime) โ List<MoodEntry> | Entries for a specific date |
averageMood | (DateTime start, DateTime end) โ double | Average 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.
| Method | Signature | Description |
|---|---|---|
addEntry | (ExpenseEntry) โ void | Log 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.
| Method | Signature | Description |
|---|---|---|
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) โ double | Monthly savings rate |
getBudgetAdherenceScore | (...) โ int | 0โ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.
| Method | Signature | Description |
|---|---|---|
addContribution | (String goalId, ...) โ void | Add a contribution toward a goal |
monthlySavings | (int year, int month) โ double | Total saved in a month |
savingsHistory | ({int months}) โ List<MonthlySavingsPoint> | Monthly savings trend data |
exportJson / importJson | () โ String / (String) โ void | Full data export/import |
SubscriptionTrackerService
lib/core/services/subscription_tracker_service.dart
Manage recurring subscriptions with billing cycles, pause/cancel support, and upcoming billing alerts.
| Method | Signature | Description |
|---|---|---|
add / update / remove | CRUD operations | Manage subscription entries |
cancel / pause / resume | (String id) โ void | Subscription lifecycle control |
monthlyTotal | () โ double | Total 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).
| Method | Signature | Description |
|---|---|---|
addHabit / updateHabit | CRUD operations | Manage habits |
logCompletion | (String habitId, DateTime, {String? note}) โ void | Mark habit as done for a day |
getStats | (String habitId) โ HabitStats | Current streak, best streak, completion rate |
SkillTrackerService
lib/core/services/skill_tracker_service.dart
Track skill development with practice sessions, proficiency levels, and progress reports.
| Method | Signature | Description |
|---|---|---|
logPractice | (String skillId, PracticeSession) โ void | Log a practice session |
getReport | (String skillId) โ SkillReport | Progress 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.
| Method | Signature | Description |
|---|---|---|
addBook / removeBook / updateBook | CRUD operations | Manage book list |
setChallenge | (ReadingChallenge) โ void | Set yearly reading challenge |
readingSpeed | () โ double | Average pages per day |
GratitudeJournalService
lib/core/services/gratitude_journal_service.dart
Daily gratitude journal with tagging, favorites, date-range queries, and streak tracking.
| Method | Signature | Description |
|---|---|---|
addEntry | ({required String text, ...}) โ String | Add a gratitude entry (returns ID) |
toggleFavorite | (String id) โ bool | Toggle favorite status |
getStreak | () โ int | Consecutive 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.
| Method | Signature | Description |
|---|---|---|
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.
| Method | Signature | Description |
|---|---|---|
saveReview | (DailyReview) โ void | Save 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.
| Method | Signature | Description |
|---|---|---|
addGoal / updateGoal / deleteGoal | CRUD operations | Goal lifecycle management |
toggleMilestone | (String goalId, String milestoneId) โ void | Mark milestone complete/incomplete |
archiveGoal / completeGoal | (String goalId) โ void | Archive or mark goal as achieved |
AchievementService
lib/core/services/achievement_service.dart
Gamification system: register achievement definitions, track progress, award badges, and level up.
| Method | Signature | Description |
|---|---|---|
register | (AchievementDefinition) โ bool | Register an achievement type |
updateProgress | (String achievementId, int value) โ void | Update progress toward achievement |
updateProgressBatch | (Map<String, int>) โ void | Batch update multiple achievements |
isEarned | (String achievementId) โ bool | Check 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.
| Method | Signature | Description |
|---|---|---|
logInteraction | ({required String contactId, ...}) โ Interaction | Record a contact interaction |
byCategory | (RelationshipCategory) โ List<Contact> | Filter contacts by category |
archiveContact / unarchiveContact | (String id) โ void | Archive/restore contacts |
ChoreTrackerService
lib/core/services/chore_tracker_service.dart
Manage household chores with recurrence schedules, overdue detection, streak tracking, and quality ratings.
| Method | Signature | Description |
|---|---|---|
isOverdue | (Chore, List<ChoreCompletion>) โ bool | Check if a chore is overdue |
daysUntilDue | (Chore, List<ChoreCompletion>) โ int | Days until next due date |
currentStreak | (Chore, List<ChoreCompletion>) โ int | Consecutive 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.
| Method | Signature | Description |
|---|---|---|
todayEntries | (List<CareEntry>, String petId) โ List<CareEntry> | Today's care entries for a pet |
careStreak | (List<CareEntry>, String petId) โ int | Consecutive days with care logged |
overdueRecords | (List<HealthRecord>, String petId) โ List<HealthRecord> | Overdue health checkups |
totalCost | (List<CareEntry>, String petId) โ double | Total 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.
| Method | Signature | Description |
|---|---|---|
addPlant / removePlant | CRUD operations | Manage 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.
| Method | Signature | Description |
|---|---|---|
addEntry | (ScreenTimeEntry) โ void | Log screen time |
setDailyGoal | (int minutes) โ void | Set max daily screen time |
addLimit / removeLimit | ({String? appName, AppCategory?}) โ void | Per-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.
| Method | Signature | Description |
|---|---|---|
addRoutine / updateRoutine / removeRoutine | CRUD operations | Manage routines |
getRoutinesForDate | (DateTime) โ List<Routine> | Routines scheduled for a date |
getTotalMinutesForDate | (DateTime) โ int | Total 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.
| Method | Signature | Description |
|---|---|---|
formatText | (AgendaDigest) โ String | Plain text agenda |
formatMarkdown | (AgendaDigest) โ String | Markdown-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.
| Method | Signature | Description |
|---|---|---|
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.