Skip to content

Latest commit

Β 

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ₯ SmartAid β€” Intelligent Health Companion

SmartAid Logo

A cross-platform Flutter app that brings AI-powered medication management, emergency response, and health analytics to everyone.

Flutter Firebase Dart License Platform


πŸ“‹ Table of Contents


🌟 Overview

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

✨ Features

πŸ‘€ Patient Features

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.

🩺 Doctor Features

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.

πŸ—οΈ Architecture

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           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

State Management

  • 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

Navigation

  • go_router with Firebase Auth stream listening for automatic login/logout redirects
  • Navigator.push for modal screens (add medicine, add appointment, emergency, first aid)

πŸ› οΈ Tech Stack

Core

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

On-Device Intelligence

Technology Purpose
Google ML Kit Text Recognition Camera-based pill bottle OCR verification
Sensors Plus Accelerometer access for fall detection

Maps & Location

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

Storage & Files

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

PDF & Reporting

Technology Purpose
pdf Programmatic PDF document generation
printing PDF preview and share sheet

UI & Theme

Technology Purpose
Google Fonts Custom typography
Material 3 (useMaterial3: true) Modern adaptive design system
connectivity_plus Network status detection for offline mode

πŸ“ Project Structure

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

πŸ“± Screens & UX

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

πŸ—„οΈ Data Models

UserModel

uid: String
email: String
isDoctor: bool
emergencyContacts: List<String>
shareDataResearch: bool
createdAt: DateTime

MedicationModel

id: String
userId: String
name: String
dailyDoseLimit: int
scheduledTimes: List<String>   // e.g. ["08:00", "20:00"]
createdAt: DateTime

DoseLogModel

medicationId: String
medicationName: String
userId: String
date: String          // "yyyy-MM-dd" key
count: int            // doses taken today
lastTaken: DateTime

AppointmentModel

id: String
userId: String
doctorName: String
reason: String
dateTime: DateTime

HealthRecordModel

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

πŸ€– Analytics & AI

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=...

Visualization Widgets

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

πŸ”’ Security

  • 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

πŸš€ Getting Started

Prerequisites

  • 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

Clone & Install

git clone https://github.com/jeevan841/SmartAid.git
cd SmartAid/smart_aid
flutter pub get

Run

# 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

βš™οΈ Configuration

Firebase Setup

  1. Create a Firebase project at console.firebase.google.com
  2. Enable Authentication (Email/Password provider)
  3. Enable Cloud Firestore (start in test mode, then apply security rules)
  4. 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;
    }
  }
}

App Icons

Icons are auto-generated via flutter_launcher_icons from assets/images/logo.png:

dart run flutter_launcher_icons

πŸ“ UML Diagrams

See UML_DIAGRAM.md in this repository for the full set of architecture and class diagrams.


πŸ—ΊοΈ Roadmap

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

πŸ‘©β€πŸ’» Contributing

Contributions are welcome! Please open an issue to discuss your idea before submitting a pull request.

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a pull request

πŸ“œ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


Made with ❀️ using Flutter & Firebase

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages