Attendly

A cross-platform Flutter mobile application that helps university students track actual conducted classes across Lecture and Lab components, calculate exact safe-absence and recovery targets, simulate hypothetical attendance scenarios, and back up records locally.

FlutterFlutter
DartDart
Riverpod
GoRouter
SQLiteSQLite
Drift
Kotlin
GitHub Actions

Project Overview

Attendly is an offline-first mobile application built with Flutter for college and university students who need to stay above mandatory attendance thresholds (such as 75% or 80%) to remain eligible for exams.

Instead of acting as a rigid weekly timetable or an institutional surveillance tool, Attendly models only classes that actually took place. Students organize courses by semester, track Lecture and Lab components independently, log Present or Absent sessions in a few taps, and immediately see how many classes they can safely miss or must attend consecutively to recover.

All data stays on the user's device in a local SQLite database with zero remote APIs, accounts, or telemetry. Students can also share semester templates via QR codes, run hypothetical "What-If" attendance scenarios without mutating real records, and monitor their standing directly from native Android home screen widgets.

Problem Statement

University students face strict attendance requirements, yet existing tracking approaches have clear limitations:

  • Timetable-driven assumptions: Generic schedule apps assume every slot on a recurring weekly timetable occurred, counting cancelled, rescheduled, or substituted classes as absences unless manually pruned.
  • Opaque institutional portals: Campus portals often lag behind actual class sessions, lack granular Lecture vs. Lab breakdowns, and do not tell students how many classes they can safely skip or need to attend consecutively to recover.
  • Calculation policy mismatches: Universities evaluate attendance differently: some combine all sessions into a single ratio, while others weight Lecture and Lab components 50/50 regardless of session count.
  • Privacy and connectivity friction: Cloud-backed trackers require accounts and internet access in lecture halls where connectivity is unreliable.

The Solution

Attendly solves this with a student-first, autonomous tracking model:

  • Actual-sessions-only ledger: Unrecorded classes are never penalized as absences. Only sessions explicitly marked Present or Absent factor into calculations, and multiple sessions for the same subject on the same day are supported.
  • Dual-policy calculation engine: Each semester can be configured for Raw Combined (present / conducted) or Component Average (50/50) ((lecturePct + labPct) / 2), with explicit provisional handling when one enabled component has zero recorded sessions.
  • Actionable math: Deterministic calculators compute exact Safe Absences (classes a student can miss without dropping below threshold) and Recovery Targets (consecutive classes needed to reach the threshold or personal goal).
  • Zero-risk experimentation & portability: An isolated in-memory What-If Simulator lets students test future attendance scenarios, while versioned JSON backup/restore and QR semester templates make data portable without a backend.

Key Features

Dual-Policy Attendance & Recovery Engine

  • What it does: Computes subject-level and semester-level attendance percentages under either Raw Combined or Component Average (50/50) rules, alongside exact safe-absence allowances and consecutive recovery counts for both mandatory thresholds and personal goals.
  • User benefit: Eliminates manual spreadsheet math and gives students an honest, policy-accurate answer to "Can I miss today's class?"
  • Implementation: Pure Dart services (AttendanceCalculator, SafeAbsenceCalculator, RecoveryCalculator) with floating-point epsilon boundary checks and explicit provisional / requiresScenario states when 50/50 policies cannot be reduced to a closed-form integer.

Fast Session Logging with Single-Tap Undo

  • What it does: Lets students log Present or Absent for any subject's Lecture or Lab component via a modal Quick Log sheet, while preventing accidental duplicate taps and future-date entries.
  • User benefit: Supports one-handed logging between classes while making mistakes trivial to reverse.
  • Implementation: QuickLogSheet tracks in-flight keys (_inFlightKeys) to debounce rapid taps, while AttendanceController emits a sealed UndoAction (UndoCreatedSession, UndoDeletedSession, UndoUpdatedSession) consumed by an auto-dismissing toast.

What-If Attendance Simulator

  • What it does: Provides a sandbox where students add, toggle, or bulk-add hypothetical future Present/Absent sessions and compare projected metrics against their real baseline.
  • User benefit: Enables students to plan upcoming absences or recovery streaks (especially useful under 50/50 component policies) without risking corruption of actual records.
  • Implementation: ScenarioCalculator maps HypotheticalSession items to ephemeral AttendanceSession objects with negative IDs (-(i + 1)) and feeds the combined list into AttendanceCalculator purely in memory.

Peer-to-Peer Semester Sharing via QR Codes

  • What it does: Encodes a semester's structure (name, threshold, personal goal, calculation method, and subject list with Lecture/Lab flags) into a versioned JSON QR payload for classmates to scan or paste.
  • User benefit: Lets an entire class set up the same semester and subject list in seconds without typing every course manually.
  • Implementation: SemesterQrPayload validates and serializes the template (qr_flutter for rendering, mobile_scanner for camera scanning with torch toggle and manual JSON paste fallback), followed by a preview sheet before atomic database insertion.

Calendar History & Day Notes

  • What it does: Displays a monthly calendar with per-day attendance status dots, session editing/deletion, and optional per-day notes (e.g., exam schedules or cancelled-class context).
  • User benefit: Keeps a complete audit trail of past sessions and context for unusual days.
  • Implementation: Enforced at the SQLite level with a UNIQUE(semester_id, date) constraint on DayNotes and reactive Drift Stream queries scoped by month and date.
  • What it does: Renders 2x2 (Small) and 4x2 (Medium) Android home screen widgets displaying the active semester, overall percentage ring, threshold badge, and top 3 subjects, plus a Quick Log action button.
  • User benefit: Surfaces attendance standing at a glance and jumps straight into the Quick Log sheet via attendly://quick-log.
  • Implementation: HomeWidgetService writes summary and theme tokens to shared storage via home_widget, while Kotlin AppWidgetProviders (SmallAttendanceWidgetProvider, MediumAttendanceWidgetProvider) build adaptive RemoteViews using Android 12+ SizeF layouts and legacy width fallbacks.

Validated Local JSON Backup & Restore

  • What it does: Exports all semesters, subjects, attendance sessions, day notes, and preferences into a versioned JSON file (attendly-backup-v1), and validates/restores backups atomically.
  • User benefit: Protects against device loss or app reinstallation without requiring cloud storage.
  • Implementation: BackupValidator enforces a 25 MB size cap, 100,000-record limit, referential integrity, calendar date validity, and component consistency before BackupService.restoreBackup executes inside a single SQLite transaction with ID remapping.

Rule-Based Insights & Daily Reminders

  • What it does: Generates factual observations (threshold delta, safe absences, recovery streaks, Lecture vs. Lab imbalances >= 10%, and chronological trend shifts >= 5% across 4+ dates) and schedules daily local notifications.
  • User benefit: Highlights actionable patterns without speculative AI fluff, and nudges students to log classes at their preferred time.
  • Implementation: InsightObservationGenerator suppresses observations when fewer than 3 sessions exist to avoid misleading conclusions; NotificationServiceImpl schedules timezone-aware daily reminders via flutter_local_notifications and flutter_timezone.

Technology Stack

CategoryTechnologiesPurpose in Attendly
Framework & LanguageFlutter, Dart (^3.14.0)Cross-platform UI and pure Dart domain logic
State Managementflutter_riverpod (^3.5.0)Reactive providers, stream composition, and controller state
Navigationgo_router (^18.1.4)Declarative route configuration (/, /onboarding, /semester-setup, /home, /simulator, /settings)
Local Persistencedrift (^2.35.4), sqlite3_flutter_libs, shared_preferencesType-safe reactive SQLite database with migrations, plus key-value storage for theme, onboarding, and reminder preferences
Native Android Widgetshome_widget (^0.10.0), Kotlin AppWidgetProviderSyncs attendance summaries and theme colors to 2x2 and 4x2 Android home screen widgets with attendly:// deep links
QR & Sharingqr_flutter (^4.1.0), mobile_scanner (^7.5.0), file_picker, share_plusSemester template QR generation/scanning and local JSON backup export/import
Notifications & Datesflutter_local_notifications, timezone, flutter_timezone, intlTimezone-aware daily attendance reminders and date/number formatting
Tooling & Testingdrift_dev, build_runner, flutter_lints, mocktail, sqlite3, GitHub ActionsCode generation, static analysis, unit/widget/journey tests, and automated APK release builds

System Architecture

Attendly follows a feature-first Clean Architecture layout (lib/features/<feature>/ split into domain, data, and presentation) alongside shared infrastructure in lib/core/ and app-level routing/theming in lib/app/.

Loading diagram...
  • Data Flow: Drift exposes reactive Streams (watchSessionsForSemester, watchActiveSemesters, etc.) that Riverpod StreamProviders and derived Providers (semesterAttendanceSummaryProvider) combine into immutable summary models.
  • Widget Synchronization: MainShellScreen listens to semesterAttendanceSummaryProvider and pushes updated metrics to HomeWidgetService, while ThemeModeNotifier synchronizes light/dark palette colors whenever the theme changes.
  • No Backend / Auth: There is no network layer, user authentication, or remote sync.

Technical Implementation

1. Boundary-Verified Safe Absence & Recovery Math

SafeAbsenceCalculator and RecoveryCalculator compute closed-form integer bounds (⌊A / t - C⌋ for safe absences and ⌈(t * C - A) / (1 - t)⌉ for recovery) and then verify those bounds with epsilon-guarded while loops so floating-point rounding never misleads a student by one class.

// lib/features/attendance/domain/services/safe_absence_calculator.dart
final rawX = (present / threshold) - conducted;
var x = math.max(0, rawX.floor());

// Boundary check verification:
while (x > 0 && ((present / (conducted + x)) < threshold - 1e-9)) {
  x--;
}
while ((present / (conducted + x + 1)) >= threshold - 1e-9) {
  x++;
}

When a semester uses componentAverage (50/50 Lecture/Lab split), both calculators explicitly return requiresScenario instead of guessing future Lecture vs. Lab distribution, directing the user to the What-If Simulator.

2. Schema Migrations & Table Rebuilds in Drift

AppDatabase (currently at schemaVersion => 5) manages incremental upgrades cleanly:

  • v2: Adds idx_attendance_sessions_date index.
  • v3: Removes an earlier per-day uniqueness constraint by rebuilding attendance_sessions inside a PRAGMA foreign_keys = OFF copy-and-rename migration, enabling multiple lectures or labs for the same subject on a single day.
  • v4: Creates day_notes with UNIQUE(semester_id, date).
  • v5: Adds target_goal to semesters.

3. Atomic Backup Restore with ID Remapping

Restoring a JSON backup (BackupService.restoreBackup) runs inside _db.transaction(...). It clears existing tables, inserts semesters and subjects while building oldToNewSemesterId and oldToNewSubjectId maps, and batch-inserts attendance_sessions and day_notes using the remapped foreign keys. Any validation or constraint error rolls back the entire transaction, preserving the user's prior database state.

4. Adaptive Android Home Screen Widgets

AttendanceWidgetViews.kt builds both Small (2x2) and Medium (4x2) RemoteViews. On Android 12+ (API >= 31), it supplies a Map<SizeF, RemoteViews> so the launcher picks the appropriate layout dynamically; on older Android versions, it inspects OPTION_APPWIDGET_MIN_WIDTH in onAppWidgetOptionsChanged.

Engineering Decisions

DecisionApproach ImplementedRationale & AdvantagesTrade-Offs
Offline-first SQLite (Drift)Local attendly.sqlite with NativeDatabase.createInBackground and SQL CHECK constraintsZero latency, works without campus Wi-Fi, strong relational integrity (ON DELETE CASCADE), reactive Stream queriesNo automatic cross-device cloud sync; users rely on manual JSON backup/restore
In-memory What-If SimulatorScenarioCalculator uses negative IDs (-(i + 1)) and never writes to DriftGuarantees simulated sessions can never pollute real attendance history; reuses the exact AttendanceCalculator engineSimulated scenarios reset when leaving the simulator rather than persisting across sessions
Explicit Component Average limitsSafeAbsenceCalculator / RecoveryCalculator return requiresScenario under 50/50 policyAvoids fabricating assumptions about whether future classes will be Lectures or LabsUsers on 50/50 policies must use the Simulator for exact projections
Apple HIG Design SystemUnified light (#F2F2F7) and True OLED dark (#000000) palettes with adaptive floating dock / side railConsistent, high-contrast typography with tabular numerals (fontFeatures) and responsive desktop/tablet rail supportEarlier multi-theme pastel concepts were consolidated into a single system

Technical Challenges & Solutions

  • Challenge: Allowing multiple Lecture or Lab sessions for the same subject on the same date without breaking existing user data.

    • Approach: Schema v3 (AppDatabase.onUpgrade) disables foreign keys temporarily, creates attendance_sessions_v3 without the legacy unique index, copies all rows, swaps the table, and re-enables foreign keys and date indexes.
    • Outcome: Students can log back-to-back lectures or extra lab sessions on the same day while preserving historical records.
  • Challenge: Preventing corrupted or maliciously oversized JSON files from breaking the local database during restore.

    • Approach: BackupValidator performs multi-stage pure-Dart validation (25 MB size limit, 100,000-record cap, format/version checks, real calendar date verification, and component-enablement checks) before BackupService.restoreBackup runs inside an atomic SQLite transaction.
    • Outcome: Invalid backups fail fast with human-readable error messages, and valid backups restore with remapped foreign keys or roll back cleanly.
  • Challenge: Keeping Android home screen widgets synchronized with live attendance changes and theme switches.

    • Approach: MainShellScreen listens to semesterAttendanceSummaryProvider and ThemeModeNotifier calls HomeWidgetService.updateThemeColors, pushing serialized metrics and ARGB color integers to SharedPreferences and triggering AppWidgetProvider updates.
    • Outcome: Widgets reflect newly logged sessions and light/dark mode switches without requiring manual refresh.

User Experience & Design

  • Apple HIG Aesthetic: Uses grouped light surfaces (#F2F2F7 canvas, #FFFFFF cards) and True OLED dark surfaces (#000000 canvas, #1C1C1E cards) with canonical semantic colors (Green, Orange, Red) and Plus Jakarta Sans typography using tabular figures (FontFeature.tabularFigures()).
  • Responsive Navigation: MainShellScreen and AppFrame adapt between a blurred floating pill dock (AppFloatingDock) on mobile and a side navigation rail (AppSideRail) on wider screens (maxWidth: 720).
  • States & Feedback: Dedicated AppLoadingState, AppEmptyState, and AppErrorState widgets handle async transitions, while AppToast provides non-blocking feedback with an Undo action for attendance mutations.
  • Accessibility: Interactive controls use Semantics labels (such as the What-If Simulator button and Quick Log actions) and constrained minimum touch targets.

Performance, Security & Reliability

  • Database & Query Optimization: AppDatabase runs SQLite in a background isolate (NativeDatabase.createInBackground) and defines indexes on attendance_sessions(session_date), attendance_sessions(subject_id, session_date), subjects(semester_id, sort_order), and day_notes(date).
  • Rendering: AppFloatingDock wraps its BackdropFilter blur in a RepaintBoundary to isolate repaints, and AttendanceCalculator.calculateSubject skips re-filtering session lists when already pre-partitioned by calculateSemester.
  • Input & Schema Validation: Both repository methods (AttendanceRepositoryImpl._validateSessionDate, SemesterRepositoryImpl) and SQLite CHECK constraints enforce non-blank names, valid thresholds (0.0 < t <= 1.0), valid YYYY-MM-DD dates, and no future-dated attendance logging.
  • Automated Testing & CI: The repository contains 57 test files in test/ (unit, repository, provider, widget, and end_to_end_user_journeys_test.dart tests) and a GitHub Actions workflow (.github/workflows/release.yml) configured to run dart analyze, flutter test, and release APK builds on pushes and PRs.

Results & Impact

Attendly delivers a complete, self-contained offline attendance tracker across 146 Dart source files (excluding generated .g.dart files), 4 Kotlin/Android widget classes, and 57 automated test files.

Demonstrated capabilities in the repository include:

  • Full semester, subject, session, and day-note CRUD backed by SQLite with 5 schema versions.
  • Dual-policy attendance math (Raw Combined and 50/50 Component Average) with safe-absence, recovery, and goal-recovery calculations.
  • In-memory What-If simulation, QR-based semester template sharing, local JSON backup/restore, daily scheduled notifications, and adaptive Android home screen widgets.

Learnings & Skills Demonstrated

  • Mobile Architecture & State Management: Structuring a multi-feature Flutter app with Riverpod (Notifier, AsyncNotifier, StreamProvider), GoRouter, and repository abstractions.
  • Relational Data Modeling: Designing normalized SQLite schemas with Drift, foreign-key cascades, CHECK constraints, multi-version table-rebuild migrations, and atomic transaction restores.
  • Domain Modeling & Edge-Case Math: Writing pure Dart business logic with floating-point boundary verification, provisional state modeling, and zero-side-effect simulation.
  • Platform Integration: Bridging Flutter with native Android AppWidgetProviders in Kotlin (RemoteViews, SizeF adaptive layouts, deep-link Intents), camera QR scanning, and local timezone-aware notifications.

Future Improvements

  1. iOS Home Screen Widgets: While HomeWidgetService includes an iOSName parameter on its wrapper, native WidgetKit extensions are not yet implemented in ios/ (currently only Android AppWidgetProviders exist).
  2. Milestone Celebrations Completion: lib/features/attendance/domain/services/milestone_service.dart is currently commented out in the codebase; re-enabling and wiring it into the dashboard/logging flow would complete personal milestone tracking.
  3. Interactive Simulator Persistence: Adding optional saved scenarios in SimulatorController so students can compare multiple semester-long attendance plans across app restarts.
  4. Automated iOS & Widget Test CI: Extending .github/workflows/release.yml beyond Android APK builds to include iOS build checks and coverage reporting.