π₯ SmartAid β Intelligent Health Companion
SmartAid is a comprehensive, AI-powered mobile health companion built with Flutter and Firebase. It is designed to serve both patients (tracking daily medications, appointments, and health records) and doctors (viewing anonymized patient cohort analytics and research data).
The app bridges the gap between everyday health management and advanced technology by integrating:
π€ Google Gemini AI for personalized health narrative insights
π· ML Kit OCR for pill bottle camera verification
π‘ Accelerometer-based fall detection with auto-SOS
πΊοΈ Live OpenStreetMap for nearby hospitals, clinics, and pharmacies
π Adherence analytics with visual charts and progress rings
π PDF report generation for patient health summaries
π Offline-first sync so the app works without an internet connection
Feature
Description
Medication Tracking
Add medications with daily dose limits and scheduled times. Log each dose with one tap.
Adherence Analytics
Real-time adherence progress ring and weekly trend chart. Streak system for consecutive perfect days.
Appointment Booking
Schedule, view, and edit upcoming doctor appointments.
AI Narrative Insights
Gemini-powered personalized commentary on your adherence patterns.
Pill Scan Verification
Use your phone's camera with Google ML Kit OCR to verify you have the right medication.
Emergency SOS
Accelerometer-based fall detection with a 10-second countdown and auto-SMS/call to emergency contacts.
First Aid Guides
Offline-capable first aid information for common emergencies.
Live Medical Map
GPS-powered map showing nearby hospitals, clinics, and pharmacies (OpenStreetMap + Overpass API).
Health Records Vault
Upload and store medical documents (PDFs, images) locally with Firestore metadata.
Medication Log History
Full chronological history of all logged doses.
PDF Report Export
Generate and share a comprehensive patient health report as a PDF.
Offline Mode
Offline sync service queues changes when offline and syncs automatically when reconnected.
Theme Toggle
Light, dark, and system-default themes.
Feature
Description
Doctor Dashboard
Research overview with aggregate patient cohort metrics.
Consenting Patient List
View patients who have opted in to share anonymized health data.
Cohort Analytics
Summary statistics on medication adherence across the patient pool.
Research Insights
AI-generated analysis of medication patterns at a population level.
SmartAid follows a layered, feature-first architecture with clean separation of concerns:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β Screens / Widgets / Visualization Components β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Business Logic Layer β
β Services Β· Providers Β· Analytics β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Data Layer β
β Repositories Β· Models Β· Firestore β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Infrastructure / Cross-Cutting β
β Firebase Β· SQLite (sqflite) Β· Offline Sync β
β ML Kit Β· Sensors Plus Β· Gemini AI Β· PDF β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Provider + ChangeNotifier for app-wide state (theme, offline sync)
StreamBuilder for real-time Firestore data (medications, appointments, dose logs)
FutureBuilder for one-shot async operations (analytics profiles, reports)
ProxyProvider for dependency injection of services that depend on repositories
go_router with Firebase Auth stream listening for automatic login/logout redirects
Navigator.push for modal screens (add medicine, add appointment, emergency, first aid)
Technology
Purpose
Flutter 3.x / Dart ^3.9
Cross-platform UI framework
Firebase Auth
Email/password authentication, role-based (patient vs. doctor)
Cloud Firestore
Real-time NoSQL database for user data, medications, appointments, health records
Google Gemini AI (google_generative_ai)
AI-generated health narrative and cohort insights
Technology
Purpose
Google ML Kit Text Recognition
Camera-based pill bottle OCR verification
Sensors Plus
Accelerometer access for fall detection
Technology
Purpose
Flutter Map
OpenStreetMap tile rendering
Geolocator
GPS location services
Overpass API (via http)
Fetching nearby POIs (hospitals, clinics, pharmacies)
LatLong2
Coordinate data model
Technology
Purpose
sqflite
Local SQLite database for offline queue
shared_preferences
Light key-value persistence
path_provider
Platform file system paths
file_picker
User document uploads
open_filex
Open saved files in native apps
Technology
Purpose
pdf
Programmatic PDF document generation
printing
PDF preview and share sheet
Technology
Purpose
Google Fonts
Custom typography
Material 3 (useMaterial3: true)
Modern adaptive design system
connectivity_plus
Network status detection for offline mode
smart_aid/
βββ lib/
βββ main.dart # App entry, DI setup, GoRouter config
βββ firebase_options.dart # Firebase platform config
β
βββ models/ # Pure data classes (no logic)
β βββ user_model.dart
β βββ medication_model.dart
β βββ dose_log_model.dart
β βββ appointment_model.dart
β βββ health_record_model.dart
β βββ nearby_poi_model.dart
β βββ place_model.dart
β
βββ repositories/ # Firestore data access layer
β βββ user_repository.dart
β βββ medication_repository.dart
β βββ appointment_repository.dart
β βββ health_record_repository.dart
β βββ doctor_dashboard_repository.dart
β βββ places_repository.dart # Overpass API integration
β
βββ services/ # Business logic layer
β βββ user_service.dart
β βββ medication_service.dart # Dose logging, streams
β βββ appointment_service.dart
β βββ health_record_service.dart
β βββ fall_detection_service.dart # Accelerometer + SOS
β βββ pill_verification_service.dart # ML Kit OCR
β βββ pdf_export_service.dart # PDF generation & sharing
β βββ local_db_service.dart # SQLite offline queue
β
βββ screens/ # UI screens (one per feature)
β βββ auth_screen.dart
β βββ main_screen.dart # Tab host
β βββ home_screen.dart # Medications + appointments + insights
β βββ add_medicine_screen.dart
β βββ add_appointment_screen.dart
β βββ health_records_screen.dart
β βββ nearby_hospitals_screen.dart
β βββ emergency_screen.dart # Fall detection + SOS
β βββ first_aid_screen.dart
β βββ profile_screen.dart # Settings, emergency contacts, privacy
β βββ doctor_dashboard_screen.dart
β βββ language_selection_screen.dart
β
βββ analytics/ # Analytics engine
β βββ models/
β β βββ doctor_dashboard_stats.dart
β βββ services/
β β βββ adherence_analytics_service.dart
β β βββ research_analytics_service.dart
β βββ intelligence/
β βββ models/
β β βββ product_insight.dart
β βββ services/
β βββ product_insights_service.dart
β
βββ ai/ # Gemini AI integration
β βββ models/
β βββ prompts/
β βββ services/
β β βββ ai_insight_service.dart
β βββ widgets/
β βββ ai_narrative_widget.dart
β
βββ reports/ # Report generation
β βββ models/
β βββ services/
β βββ report_generation_service.dart
β
βββ offline/ # Offline-first sync
β βββ models/
β βββ services/
β βββ offline_sync_service.dart
β
βββ security/
β βββ services/
β β βββ secure_logger.dart
β βββ validators/
β βββ input_validators.dart
β
βββ visualization/ # Charting widgets
β βββ models/
β β βββ chart_point.dart
β βββ utils/
β β βββ chart_data_mapper.dart
β βββ widgets/
β βββ adherence_progress_ring.dart
β βββ weekly_trend_chart.dart
β βββ cohort_summary_widget.dart
β
βββ providers/
β βββ theme_provider.dart
β
βββ theme/
β βββ app_theme.dart
β
βββ ui/
β βββ loading/
β βββ shimmer_loading.dart # Skeleton loading cards
β
βββ utils/
β βββ firestore_parser.dart
β
βββ widgets/
βββ bottom_nav_bar.dart
Authentication (auth_screen.dart)
Combined login / sign-up screen
Doctor role toggle during registration
Firebase Auth email/password with error feedback
Branding logo display
Home Screen (home_screen.dart)
Upcoming Appointments β horizontal scrollable card list with real-time Firestore stream
Today's Insights β adherence ring + weekly trend chart + AI narrative + streak badge
Medications List β tap-to-log daily medications, strikethrough when taken
Offline indicator in app bar (pending sync count + syncing spinner)
FAB to add medicine or book appointment
Quick access to Emergency SOS and PDF export from action buttons
Emergency Screen (emergency_screen.dart)
Toggle switch to activate accelerometer-based fall monitoring
On fall detected: full-screen warning, 10-second countdown, cancel button
On countdown expiry: auto-SMS to emergency contacts + auto-dial 108 (ambulance)
Link to First Aid Guides
Nearby Hospitals Screen (nearby_hospitals_screen.dart)
Live interactive map (OpenStreetMap tiles)
Category filter chips: Hospitals / Clinics / Pharmacies
GPS location with fallback to New Delhi default
Retry logic with exponential backoff for the Overpass API
Tap markers for place name details in a bottom sheet
Health Records Screen (health_records_screen.dart)
Tab 1 β Uploaded Files : Upload any file (PDF, image), stored locally + Firestore metadata, open / delete
Tab 2 β Medication Logs : Full history of all dose log entries with timestamps
PDF export of full patient report
Doctor Dashboard (doctor_dashboard_screen.dart)
Cohort research overview with aggregate statistics
List of consenting patients with opt-in privacy model
CohortSummaryWidget with AI-generated insight
Profile Screen (profile_screen.dart)
User email display
Emergency contacts management (add / remove phone numbers)
Theme toggle (light / dark / system)
Privacy consent toggle for research data sharing
Sign out
uid: String
email: String
isDoctor: bool
emergencyContacts: List <String >
shareDataResearch: bool
createdAt: DateTime
id: String
userId: String
name: String
dailyDoseLimit: int
scheduledTimes: List <String > // e.g. ["08:00", "20:00"]
createdAt: DateTime
medicationId: String
medicationName: String
userId: String
date: String // "yyyy-MM-dd" key
count: int // doses taken today
lastTaken: DateTime
id: String
userId: String
doctorName: String
reason: String
dateTime: DateTime
id: String
userId: String
fileName: String
localPath: String
createdAt: DateTime
βοΈ Services & Repositories
Repository Layer (Firestore Access)
Repository
Firestore Collections
UserRepository
users/{uid}
MedicationRepository
users/{uid}/medications, users/{uid}/dose_logs
AppointmentRepository
users/{uid}/appointments
HealthRecordRepository
users/{uid}/health_records
DoctorDashboardRepository
Aggregates across users collection
PlacesRepository
Overpass API (external HTTP)
Service Layer (Business Logic)
Service
Responsibility
MedicationService
CRUD medications, dose logging, real-time streams
AppointmentService
CRUD appointments, upcoming filter
HealthRecordService
Upload metadata, local file management
UserService
Profile updates, emergency contacts, consent
FallDetectionService
Accelerometer monitoring, countdown, SOS dispatch
PillVerificationService
Camera capture β ML Kit OCR β fuzzy name match
PdfExportService
PDF document generation and platform share
LocalDbService
SQLite queue for offline operations
OfflineSyncService
Monitors connectivity, replays queued Firestore writes
Patient Analytics (ProductInsightsService)
Generates a PatientAdherenceProfile containing:
todayStats (expected vs taken doses)
weeklyTimeline (7-day adherence history)
consecutivePerfectDays (streak counter)
dailyInsight (sentiment-aware message: positive / neutral / warning)
Research Analytics (ResearchAnalyticsService)
Aggregates anonymized data from consenting patients
Streams DoctorDashboardStats : total patients, average adherence, medication distribution
Adherence Analytics (AdherenceAnalyticsService)
Per-medication adherence rate calculations over configurable time windows
Gemini AI (AiInsightService + AiNarrativeWidget)
Sends adherence context to Google Gemini via google_generative_ai
Returns a personalized, human-readable narrative displayed in the home screen insight card
API key injected at build time via --dart-define=GEMINI_API_KEY=...
Widget
Description
AdherenceProgressRing
Animated circular progress ring showing today's dose completion %
WeeklyTrendChart
7-bar chart mapping weekly adherence trend
CohortSummaryWidget
Doctor-facing aggregate summary card
Firebase Auth enforces authentication before any data access
Firestore Security Rules (configured via Firebase console) restrict each user to their own data path (users/{uid}/**)
Doctor role stored in Firestore and checked for dashboard access
Privacy consent model : patients must explicitly opt in to share research data (shareDataResearch flag)
SecureLogger β sanitized logging service that strips PII from debug output
InputValidators β server-side style validation on all user inputs before Firestore writes
Emergency contacts stored per-user and only accessed on the device during SOS; never broadcast to third parties beyond the user-initiated SMS
Flutter SDK ^3.9.0
Dart ^3.9.0
Firebase project with Authentication and Cloud Firestore enabled
(Optional) Google Gemini API key for AI narratives
git clone https://github.com/jeevan841/SmartAid.git
cd SmartAid/smart_aid
flutter pub get
# Android / iOS
flutter run
# Web
flutter run -d chrome
# Windows
flutter run -d windows
Run with Gemini AI enabled
flutter run --dart-define=GEMINI_API_KEY=your_key_here
Create a Firebase project at console.firebase.google.com
Enable Authentication (Email/Password provider)
Enable Cloud Firestore (start in test mode, then apply security rules)
Run flutterfire configure to regenerate firebase_options.dart
Firestore Security Rules (recommended)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == uid;
}
}
}
Icons are auto-generated via flutter_launcher_icons from assets/images/logo.png:
dart run flutter_launcher_icons
See UML_DIAGRAM.md in this repository for the full set of architecture and class diagrams.
Status
Feature
β
Medication tracking & dose logging
β
Appointment scheduling
β
AI-powered adherence narratives (Gemini)
β
Fall detection with auto-SOS
β
Pill verification via OCR
β
Live medical map (hospitals, clinics, pharmacies)
β
Health records file vault
β
PDF health report export
β
Doctor research dashboard
β
Offline-first sync
β
Multi-language screen scaffold
π
Push notifications for missed doses
π
Wearable (smartwatch) integration
π
Prescription photo-to-schedule import
π
Multi-language full localization (i18n)
π
Telemedicine in-app video call
Contributions are welcome! Please open an issue to discuss your idea before submitting a pull request.
Fork the repository
Create your feature branch: git checkout -b feature/amazing-feature
Commit your changes: git commit -m 'Add amazing feature'
Push to the branch: git push origin feature/amazing-feature
Open a pull request
This project is licensed under the MIT License β see the LICENSE file for details.
Made with β€οΈ using Flutter & Firebase