Skip to content

kalviumcommunity/S61-1225-ChronoByte-FlutterAndFireBase-Fixora

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

**Fixora – Smart Urban Grievance Redressal System**

Fixora is a centralized, transparent, and real-time grievance redressal system designed to help Urban Local Bodies efficiently address citizen complaints. Built using Flutter for cross-platform accessibility and Firebase for seamless backend operations, Fixora enables users to easily submit issues while allowing authorities to track, manage, and resolve them with complete accountability.

---


## Recent Work (Dec 2025)

### Cloud Functions for Serverless Event Handling (Ready to Implement)

Your project **is fully ready** to implement Cloud Functions for serverless event handling! Here's the assessment:

**Current Status:  READY FOR DEPLOYMENT**

#### What You Already Have:

1. **Firebase Functions Directory Configured**
   - Location: [functions/](functions/) directory exists with proper structure
   - Configuration: [functions/package.json](functions/package.json) has Firebase Admin SDK and Cloud Functions dependencies
   - Entry Point: [functions/index.js](functions/index.js) contains two event-based functions

2. **Existing Cloud Functions Implemented:**
   - **`onProblemCreate`** - Triggers when a new complaint is submitted
     - Sends notifications to all admin users
     - Includes invalid token cleanup
     - Payload: New complaint ID, category, and issue details
   
   - **`onProblemUpdate`** - Triggers when complaint status changes
     - Notifies the complaint reporter of status updates
     - Compares old vs. new status to avoid duplicate notifications
     - Removes invalid FCM tokens automatically

3. **Firebase Setup Complete**
   - `firebase_core` installed in pubspec.yaml
   - `cloud_firestore` integrated for Firestore triggers
   - `firebase_messaging` for push notifications
   - `flutter_local_notifications` for local notification display

#### What Needs to Be Done:

1. **Add Cloud Functions to Flutter (Easy - 2 Steps)**
   
   Add dependency to pubspec.yaml:
   ```yaml
   dependencies:
     cloud_functions: ^5.0.0
   ```
   
   Then use in Flutter:
   ```dart
   import 'package:cloud_functions/cloud_functions.dart';

   final callable = FirebaseFunctions.instance.httpsCallable('yourFunctionName');
   final result = await callable.call({'param': 'value'});
   ```

2. **Deploy Existing Functions**
   
   Prerequisites:
   ```bash
   npm install -g firebase-tools
   firebase login
   cd functions && npm install
   ```
   
   Deploy:
   ```bash
   firebase deploy --only functions
   ```

3. **Create Additional Callable Functions** (Optional)
   
   Example - Welcome message on user creation:
   ```javascript
   exports.sendWelcome = functions.https.onCall((data, context) => {
     const email = data.email || 'User';
     return { message: `Welcome to Fixora, ${email}!` };
   });
   ```

#### Recommended Implementation Plan:

**Phase 1: Deploy Current Functions** (5 minutes)
- [ ] Install firebase-tools globally
- [ ] Navigate to functions directory
- [ ] Run `npm install` 
- [ ] Run `firebase deploy --only functions`
- [ ] Verify in Firebase Console → Functions → Logs

**Phase 2: Add Callable Function** (10 minutes)
- [ ] Create callable function for complaint validation
- [ ] Add `cloud_functions` to pubspec.yaml
- [ ] Call function from submit complaint page
- [ ] Display result to user

**Phase 3: Monitor and Test** (5 minutes)
- [ ] Check Firebase Console logs
- [ ] Send test complaint
- [ ] Verify admin notification triggered
- [ ] Test status update notification

#### Use Cases Ready to Implement:

**Auto-send admin notifications** on new complaints
**Status update notifications** to complaint reporters  
**Invalid token cleanup** from FCM database
**Data validation** before Firestore write
**Welcome emails/messages** for new users
**Automated complaint categorization** using AI
**Generate summary reports** on demand

#### Next Steps:

1. Deploy current functions to test the setup
2. Add `cloud_functions` package to Flutter
3. Create a test callable function
4. Add error handling for function calls
5. Document function behavior in README

Your project is **production-ready** for Cloud Functions. The infrastructure is already in place!

### UI Refinements (Dec 29, 2025)

- **Track Complaint Page Visual Updates**: Made design improvements to enhance the user interface of the Track Complaint page.
  
  - **Title Color Changed to White**: Updated the "Track Your Complaint" heading color from dark gray (`Color(0xFF1B2430)`) to white (`Colors.white`) for better contrast and visibility, especially on dark or gradient backgrounds.
  
  - **Removed Debug Button**: Cleaned up the UI by removing the "Create Sample Complaint (Debug)" button that was visible in debug mode. The button served as a testing utility but cluttered the production interface.
    - Implementation: Modified `_CreateDemoButton` widget to return `SizedBox.shrink()` instead of the actual button
    - Location: [lib/pages/track_complaint/track_complaint_page.dart](lib/pages/track_complaint/track_complaint_page.dart)

**Visual Impact:**

-  **Cleaner Interface**: Removed development-only UI elements from user-facing pages
-  **Better Readability**: White text on colored backgrounds provides superior contrast
-  **Professional Appearance**: Debug utilities hidden from end users
-  **Consistent Design**: Title color matches modern app design patterns

### Prop Drilling Elimination (Dec 29, 2025)

- **Removed Prop Drilling from Track Complaint Page**: Refactored the entire [lib/pages/track_complaint/track_complaint_page.dart](lib/pages/track_complaint/track_complaint_page.dart) to eliminate unnecessary prop drilling of theme colors through component hierarchy.
  
  - **Problem Identified**: Colors (`primary`, `accent`, `backgroundColor`) were being passed as props through multiple widget layers, creating tight coupling and verbose component APIs.
  
  - **Solution Implemented**:
    - Removed color getter properties from parent `_TrackComplaintPageState` class
    - Eliminated color parameters from all child widgets: `_TopBar`, `_HeroSection`, `_DemoIds`, `_StatusFilterButton`, `_CategoryFilterButton`, `_Footer`, `_TrackingForm`
    - Added color getters directly in stateful widget state classes (`_StatusFilterButtonState`, `_CategoryFilterButtonState`) to access theme colors without drilling
    - Each widget now accesses `Theme.of(context).colorScheme.primary/secondary` directly instead of receiving colors as parameters
  
  - **Widgets Refactored**:
    - `_TopBar` - removed `primary` prop
    - `_HeroSection` - removed `primary` and `accent` props
    - `_DemoIds` - removed `accent` prop
    - `_StatusFilterButton` - removed `primary` and `accent` props, added color getters
    - `_CategoryFilterButton` - removed `primary` and `accent` props, added color getters
    - `_Footer` - removed `primary` and `accent` props
    - `_TrackingForm` - removed `primary` and `accent` props

**Benefits Achieved:**

-  **Cleaner Component APIs**: Reduced parameter count in widget constructors
-  **Better Maintainability**: Theme changes automatically propagate without manual prop updates
-  **Follows Flutter Best Practices**: Direct theme access instead of manual color passing
-  **Reduced Code Verbosity**: Eliminated repetitive color prop declarations and passing
-  **Improved Scalability**: New widgets can access theme directly without prop chains
-  **Type Safety**: Compiler enforces theme color access patterns

**Code Example - Before:**

```dart
// Parent passing colors to child
_TopBar(primary: _primary)

// Child receiving colors as props
class _TopBar extends StatelessWidget {
  const _TopBar({required this.primary});
  final Color primary;
  
  Widget build(BuildContext context) {
    return CircleAvatar(backgroundColor: primary, ...);
  }
}
```

**Code Example - After:**

```dart
// Parent - no color props needed
const _TopBar()

// Child accessing theme directly
class _TopBar extends StatelessWidget {
  const _TopBar();
  
  Widget build(BuildContext context) {
    final primary = Theme.of(context).colorScheme.primary;
    return CircleAvatar(backgroundColor: primary, ...);
  }
}
```

**For Stateful Widgets with Callbacks:**

```dart
// Using getters in State class for access across methods
class _StatusFilterButtonState extends State<_StatusFilterButton> {
  Color get primary => Theme.of(context).colorScheme.primary;
  Color get accent => Theme.of(context).colorScheme.secondary;
  
  void _showMenu() {
    // Can now use primary/accent in any method
    BoxDecoration(color: primary.withOpacity(0.08), ...)
  }
  
  Widget build(BuildContext context) {
    // Also available in build method
    Icon(Icons.flag_outlined, color: primary)
  }
}
```

**Technical Notes:**

- Color getters were added to State classes instead of build() local variables to ensure colors are accessible across all methods (like `_showMenu()`, `_hideMenu()`, etc.)
- No performance impact as `Theme.of(context)` lookups are optimized by Flutter's InheritedWidget mechanism
- All widgets remain responsive to theme changes (light/dark mode switching)

### Error Notification System Implementation

- **Centralized Error Handler Utility**: Implemented a comprehensive error handling system across the entire Fixora app for consistent, user-friendly error notifications.
  - **ErrorHandler Class**: Created at [lib/utils/error_handler.dart](lib/utils/error_handler.dart) with static methods for different notification types.
  - **Notification Types**:
    - `showError()` - Red error notifications with icon and optional title
    - `showSuccess()` - Green success notifications with checkmark icon
    - `showWarning()` - Orange warning notifications for non-critical issues
    - `showInfo()` - Blue info notifications for general information
    - `showErrorDialog()` - Modal error dialogs for critical issues
    - `showConfirmDialog()` - Confirmation dialogs for destructive actions
  - **Smart Error Parsing**: 
    - `getAuthErrorMessage()` - Converts Firebase Auth exceptions to user-friendly messages
    - `getFirestoreErrorMessage()` - Parses Firestore errors with context-aware guidance
    - `getErrorMessage()` - Generic handler that detects exception type automatically
  - **Visual Features**:
    - Floating snackbars that slide up from bottom
    - Theme-aware colors (dark mode support)
    - Smooth animations with 4-8 second auto-dismiss
    - Icons and visual hierarchy with title + message structure
    - Dismissible by swiping up

**Error Messages Handled:**

- **Authentication Errors**: user-not-found, wrong-password, email-already-in-use, weak-password, too-many-requests, etc.
- **Firestore Errors**: permission-denied, not-found, failed-precondition (index required), network-request-failed, deadline-exceeded, etc.
- **Network Errors**: Clear messaging for offline/connectivity issues
- **Validation Errors**: User input validation feedback

**Pages with Error Handling:**

1. **Track Complaint Page** - Shows error state with "Try Again" button when loading fails
2. **Admin Dashboard** - Summary grid error handling with color-coded messages
3. **Issues List Component** - Intelligent error display for Firestore index requirements
4. **Profile Page** - Error handling for profile updates and complaints list loading
5. **Login Page** - Auth error notifications during sign-in
6. **Signup Page** - Registration errors with specific guidance (username taken, password weak, etc.)
7. **Profile Operations** - Logout, update profile, and complaint management error handling

**Error Handling Example:**

```dart
try {
  await FirebaseFirestore.instance.collection('problems').add({...});
  ErrorHandler.showSuccess(context, message: 'Complaint submitted successfully!');
} catch (e) {
  ErrorHandler.showError(
    context,
    title: 'Submission Failed',
    message: ErrorHandler.getErrorMessage(e),
  );
}
```

**User Experience Benefits:**

- Clear, non-technical error messages that users understand
- Consistent visual style across the entire app
- Helpful guidance for common errors (e.g., Firestore index creation)
- Different severity levels (error/warning/info) with color coding
- Auto-dismissing notifications that don't block interaction
- Mounted state checking to prevent memory leaks

### Skeleton Loaders Implementation

- **Comprehensive Skeleton Loading System**: Implemented animated skeleton loaders across the entire Fixora app to improve perceived performance and user experience during data loading states.
  - **Shimmer Animation**: Created a base `SkeletonLoader` widget with smooth shimmer animation effect that mimics the actual UI components.
  - **Reusable Components**: Built multiple specialized skeleton loaders for different UI patterns:
    - `ComplaintCardSkeleton` - Placeholder for complaint cards with title, status badge, and details
    - `ProfileSectionSkeleton` - Profile page with avatar and user information placeholders
    - `AdminDashboardSkeleton` - Summary cards and complaint lists for admin dashboard
    - `SummaryGridSkeleton` - Statistics grid placeholder with 4 cards
    - `TrackComplaintSkeleton` - Search bar, filter buttons, and complaint card placeholders
    - `FormFieldSkeleton` - Input field and label placeholders
    - `ListItemSkeleton` - Generic list item with avatar and text
    - `MinimalLoadingSkeleton` - Simple loading indicator with optional message
  - **Theme-Aware Colors**: All skeleton loaders support light and dark themes with appropriate color schemes.
  - **Smooth Transitions**: Seamless transition from skeleton loaders to actual content when data loads.
  - **Implementation Location**: [lib/widgets/skeleton_loaders.dart](lib/widgets/skeleton_loaders.dart)

**Pages Enhanced with Skeleton Loaders:**

1. **Track Complaint Page** - Shows skeleton cards and filters while fetching complaint list from Firestore
2. **Admin Dashboard**
   - Summary grid skeleton during stats loading
   - Complaint list skeleton in issues list component while fetching admin issues
3. **Profile Page** - Skeleton loaders for complaint history list while fetching user's complaints
4. **User Dashboard** - Improved loading state indicators during username fetch
5. **Auth Gate** - Loading skeletons during authentication verification and role checking
6. **Issues List Component** - Animated skeleton cards while streaming complaint data

**Why Skeleton Loaders Matter:**

- **Better UX**: Provides visual feedback that the app is loading, reducing perceived lag
- **Professional Appearance**: Skeleton screens are a modern loading pattern used by apps like Facebook, LinkedIn, and Netflix
- **Context Awareness**: Users see a preview of what's coming, not just a generic spinner
- **Reduced Bounce Rate**: Users are less likely to think the app is frozen or broken
- **Animation Smoothness**: Shimmer effect keeps the UI engaging without being distracting

**Code Example:**

To use skeleton loaders in a StreamBuilder:
```dart
StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('problems').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return TrackComplaintSkeleton(); // Shows skeleton while loading
    }
    
    if (snapshot.hasError) {
      return ErrorWidget();
    }
    
    // Actual content displays here when data arrives
    return ActualContent();
  },
)
```

### Raise Issue Page Enhancements

- **Added Terms & Conditions Checkbox**: Implemented a styled checkbox field that users must check before submitting a complaint. This ensures users acknowledge and agree to provide accurate information and accept the Fixora Terms & Conditions.
  - **Checkbox State Management**: New boolean state variable `_agreeToTerms` tracks the checkbox status.
  - **Submit Button Lock**: The submit button is now disabled until the checkbox is checked, preventing accidental or false submissions.
  - **Form Reset**: After successful submission, the checkbox is automatically unchecked along with other form fields, preparing the form for the next complaint entry.
  - **Visual Design**: The checkbox has a styled container with a blue border that changes color when selected, matching the app's blue theme (primary color: #2563EB).
  - **Implementation Location**: [lib/pages/raise_issue/raise_issue_page.dart](lib/pages/raise_issue/raise_issue_page.dart)

**How it works:**
1. User fills in all complaint details (category, issue, description, location).
2. Before submitting, user must check the "I agree to provide accurate information and accept the Fixora Terms & Conditions" checkbox.
3. The submit button changes from disabled (grayed out) to enabled only when the checkbox is checked.
4. After successful submission, a success message is shown with the complaint ID and the form is cleared (including unchecking the checkbox).
5. User can now submit another complaint if needed.

### Admin Dashboard Layout Overflow Fix

- **Fixed RenderFlex Overflow Issue**: Resolved a layout overflow error in the Admin Dashboard where content exceeded available space by 115 pixels.
  - **Root Cause**: The main Column widget contained multiple children (header, summary section, search/filters, tab bar, and tab content) with fixed heights that combined to exceed screen height.
  - **Solution Applied**: 
    - Wrapped the content column in an `Expanded` widget to consume available space.
    - Added a `SingleChildScrollView` to enable vertical scrolling when content exceeds viewport height.
    - Set a fixed height (400px) for the tab content area to prevent infinite expansion.
  - **Implementation Location**: [lib/pages/admin_dashboard/admin_dashboard.dart](lib/pages/admin_dashboard/admin_dashboard.dart) (lines 257-283)
  - **Result**: Dashboard now scrolls gracefully on smaller screens without overflow errors; the yellow/black warning stripe no longer appears.

### Previous Work (Earlier Dec 2025)

- Added status and category filters on the Track Complaint page with client-side filtering to avoid Firestore composite index requirements.
- Implemented edge-aware overlay menus for filters and a streamlined "View Tracking Details" bottom sheet sized for shorter content (heights at 0.45/0.35/0.8 for large/medium/full views).
- Tuned typography for complaint details (smaller body text, preserved title size) and tightened padding to reduce visual clutter.
- Primary changes live in [lib/pages/track_complaint/track_complaint_page.dart](lib/pages/track_complaint/track_complaint_page.dart).

## Complaints & Tracking (Dec 2025)

Recent implementation highlights:
- **Complaint ID generation**: Every submission generates an ID in the format `CG-YYYY-XXXXXX` (e.g., CG-2025-001234). Implemented in [lib/pages/raise_issue/raise_issue_page.dart](lib/pages/raise_issue/raise_issue_page.dart).
- **Firestore storage**: Complaints are stored in the `problems` collection with fields such as `complaintId`, `userId`, `category`, `issue`, `description`, `location`, `status`, and `createdAt`.
- **Track page data**: [lib/pages/track_complaint/track_complaint_page.dart](lib/pages/track_complaint/track_complaint_page.dart) streams all complaints (ordered by `createdAt`) and renders cards with status chips.
- **Search by ID**: The Track page search box looks up `complaintId` and shows the current status.
- **Debug seeding**: In debug builds, a helper seeds a sample complaint (ID: CG-2025-001234) and the “Create Sample Complaint (Debug)” button can insert another test entry for the logged-in user.
- **Demo chips**: Sample IDs are displayed under “Try these demo tracking IDs” for quick manual entry.

How to test quickly:
1) Run the app (web example):
```bash
flutter run -d chrome
```
2) Navigate to the Track page (`/track`).
3) Enter an ID (try CG-2025-001234) and press “Track” to see status.
4) (Optional) Click “Create Sample Complaint (Debug)” to insert a fresh test complaint, then track the shown ID.
5) To submit a real complaint, open the report page (`/report`); it will auto-generate a new `complaintId` and save to Firestore.


---

## Setting Up Flutter SDK, Android Studio, and First Emulator Run

Welcome to your first setup deliverable of Sprint #2! In this foundational task, you'll install and configure the Flutter SDK, set up Android Studio (or VS Code) for development, and run your first Flutter app on an emulator or physical device. This step establishes your complete development environment for all upcoming Flutter and Firebase integrations in this sprint.

**Note:** These are general setup guidelines. You may complete the setup on Windows, macOS, or Linux, depending on your system preferences and requirements.

### Task Overview

**1. Install Flutter SDK**

- Visit the official Flutter installation page for your operating system.
- Download and extract the Flutter SDK to a preferred directory (e.g., `C:\src\flutter` or `/Users/yourname/development/flutter`).
- Add Flutter to your systems PATH environment variable.

**Windows:**
- Search for "Environment Variables" → Edit PATH → Add `flutter\bin`.

**macOS/Linux:**
- Open terminal and edit your shell profile (e.g., `.zshrc` or `.bashrc`):
    bash
  export PATH="$PATH:`pwd`/flutter/bin"

- Verify installation by running:
  ```bash
  flutter doctor
  ```
  This command checks your setup and lists missing dependencies.

**2. Set Up Android Studio (or VS Code)**

- Install Android Studio from the official website.
- During installation, ensure the following components are checked:
  - Android SDK
  - Android SDK Platform
  - Android Virtual Device (AVD) Manager
- Open Android Studio → Plugins → search for and install Flutter and Dart plugins.

**Alternatively, if using VS Code:**
- Install Flutter and Dart extensions from the Marketplace.

**3. Configure Your Emulator**

In Android Studio:
- Open AVD Manager → Create Virtual Device.
- Choose a device (e.g., Pixel 6) and a system image (Android 13 or above).
- Click Finish and launch the emulator.

Verify that your emulator is detected by running:

```
bash
flutter devices
```
The emulator should appear in the device list.

**4. Create and Run Your First Flutter App**

- Create a new Flutter project:

  ```bash
  flutter create first_flutter_app
  ```
- Navigate to the project folder and open it in Android Studio or VS Code.
- Run the app on your emulator or connected physical device:

  ```bash
  flutter run
  ```
- You should see the default Flutter counter app appear on your emulator screen.

**5. Setup Verification**

We have successfully completed the Flutter environment setup with the following evidence:

- **Flutter Doctor Output**: All required dependencies are installed and configured correctly
- **Emulator Running**: The Android emulator is successfully running the first Flutter app

**Screenshots:**
- Flutter Devices Detection: `screenshot/result_of_flutter_device.png`
- Android Emulator Running: `screenshot/android_emulator.png`

**Setup Images (2025-12-17):**
![Setup image 1](screenshot/Screenshot%202025-12-17%20153633.png)
![Setup image 2](screenshot/Screenshot%202025-12-17%20153645.png)

**Setup Completion Notes:**
- Flutter SDK has been successfully installed and added to PATH
- Android Studio configured with Flutter and Dart plugins
- Android Virtual Device (AVD) created and tested
- First Flutter app successfully runs on the emulator
- Development environment is ready for upcoming Flutter and Firebase integrations


## Folder Structure

lib/
│
├── main.dart
│
├── screens/
│   │
│   ├── auth/
│   │   ├── login_page.dart
│   │   └── register_page.dart
│   │
│   ├── user/
│   │   ├── user_dashboard.dart
│   │   ├── submit_complaint_page.dart
│   │   ├── tracking_complaint_page.dart
│   │   ├── complaint_categories_page.dart
│   │   └── user_profile_page.dart
│   │
│   ├── admin/
│   │   └── admin_dashboard_page.dart
│   │
│   ├── common/
│   │   └── home_page.dart
│   │
│   └── splash/
│       └── splash_screen.dart
│
├── widgets/
│   ├── custom_button.dart
│   ├── custom_textfield.dart
│   ├── complaint_card.dart
│   └── dashboard_tile.dart
│
├── models/
│   ├── user_model.dart
│   └── complaint_model.dart
│
├── services/
│   ├── auth_service.dart
│   ├── complaint_service.dart
│   ├── admin_service.dart
│   └── firestore_service.dart
│
├── utils/
│   ├── app_colors.dart
│   ├── app_styles.dart
│   ├── app_routes.dart
│   └── constants.dart
│
└── providers/
    ├── user_provider.dart
    └── complaint_provider.dart

## Exploring Flutter Project Folder Structure and Understanding File Roles

## Project Title

Flutter Project Folder Structure Overview

A simple project setup showcasing how the Flutter folder structure works and why understanding it helps in app development.

---

## Project Structure Summary

For a detailed explanation, check **PROJECT_STRUCTURE.md**.

```
lib/
├── main.dart
├── screens/
├── widgets/
└── services/
```

This is the main working directory where all Dart code lives.

---

## Folder View (IDE Screenshot Placeholder)

> Add your folder screenshot here.

---

## Reflection

### Why understand folder roles?

* Helps navigate the project faster.
* Makes it easier to debug and add new features.

### How does clean structure help teams?

* Every member knows where files belong.
* Reduces confusion and merge conflicts.
* Improves scalability and maintainability.


## Flutter & Dart Basics (Concept 1)

# 1. StatelessWidget vs StatefulWidget

StatelessWidget:

Does not change once it is built.

Used for static UI like text, icons, simple layouts.

StatefulWidget:

Can change during the app’s lifetime.

Used when the UI updates, like counters, text fields, or API data.

# 2. How Flutter Uses the Widget Tree

Flutter builds everything as a widget tree.

Each widget is a small part of the UI.

When something changes (like a button press), Flutter rebuilds only the affected widgets.

This makes the UI fast and reactive.

# 3. Why Dart Is Ideal for Flutter

Dart compiles fast and gives smooth performance.

Supports hot reload, so changes appear instantly.

Works well for both UI and logic, making development simple.

# 4. Demo App Notes (Android / iOS)

Our demo app showed a simple screen with text and a button.

Pressing the button updated the counter (StatefulWidget).

Screenshot -1
**Refer to screenshot folder for proof of work(concept-1.png)**

### Firebase & Firestore Basics (Concept 2)

**1. Steps Followed for Firebase Setup**

Created a new project in Firebase Console.

Enabled Firestore Database.

Added Firebase to the Flutter app using the setup instructions.

Downloaded the google-services.json (Android) / GoogleService-Info.plist (iOS).

Added required Firebase dependencies in pubspec.yaml.

Initialized Firebase in the app using Firebase.initializeApp().

**2.How Firestore’s Real-Time Sync Works**

Firestore sends updates to the app instantly whenever data changes.

The app listens to the database using streams (like StreamBuilder).

No need to refresh—the UI updates automatically when Firestore data changes.

This works because Firestore uses real-time listeners under the hood.

**Demo Logs / Notes Showing Live Updates**

**Refer to screenshot folder for proof of work(concept-2.png)**

**4. Reflection – How Firebase Simplified Backend Management**

No need to build your own server or database.

Firestore handled real-time data, storage, and syncing for us.

Authentication, hosting, and database all came ready to use.

This allowed us to focus more on UI and features instead of backend code.

Firebase helped build a working mobile app much faster and with less complexity.

Here is a **short, clean, human-written version** you can directly paste into your README:

---

## Flutter Development Tools Overview

### **1. Hot Reload**

Hot Reload lets you apply UI and code changes instantly without restarting the app.
Just run the app (`flutter run`), edit a widget, save the file, and the update appears immediately.
This makes UI development much faster and keeps the app state intact.
screenshot/hot_reload.png
screenshot/hot_reload_After.png

### **2. Debug Console**

I used the Debug Console to monitor logs, catch errors, and track variable changes using `print()` or `debugPrint()`.
It helps understand how the app behaves while running and is useful for quick debugging.

### **3. Flutter DevTools**

DevTools was used to inspect widgets, check layouts, view performance graphs, and analyze memory usage.
I opened it directly from VS Code using **Ctrl + Shift + P → Flutter: Open DevTools** while the app was running.
screenshot/dev_tools.png

### **4. Workflow**

My workflow was simple:

* Update UI → Hot Reload to see immediate changes
* Add logs → View results in Debug Console
* Open DevTools → Inspect widgets & performance

### **Reflection**

Hot Reload improved development speed, the Debug Console helped catch issues early, and DevTools made it easier to understand widget structure and optimize performance.


## Authentication & User Dashboard (Concept 2.5)

**Overview: Login, Register & Dashboard Implementation**

We have created a complete authentication flow with responsive UI for mobile, tablet, and desktop devices.

**1. Login & Register Pages**

Created `login_register_page.dart` with the following features:

- **Dual Form UI**: Single component handles both login and registration modes
- **Form Validation**: Email and password validation with error messages
- **Responsive Design**: Adaptive UI that adjusts padding, font sizes, and button heights based on screen size
- **Form Switching**: Easy toggle between login and register modes using the "Don't have an account?" / "Already have an account?" buttons
- **Flutter StatefulWidget**: Uses form validation with GlobalKey to ensure user inputs are valid before submission

**Key Features:**

- Input validation for email, password, and username (registration only)
- Responsive card design with elevation effects
- Centered layout using SingleChildScrollView and ConstrainedBox
- TextFormField for email (with keyboard type), password (obscured), and username
- ElevatedButton with dynamic sizing

**Screenshots:**

- Login Screen: `screenshot/login_screen.png`
- Register Screen: `screenshot/register_screen.png`
- Home Screen: `screenshot/home_screen.png`

**2. User Dashboard**

Created `user_dashboard.dart` with the following features:

- **Welcome Message**: Personalized greeting with user icon
- **Account Information Display**: Shows logged-in user's email and username
- **Logout Functionality**: Profile menu button in AppBar with logout confirmation dialog
- **Responsive Layout**: Matches login page design for consistency
- **Navigation Integration**: Receives user data via route arguments

**Key Features:**

- Displays user email and username from login/register form
- PopupMenuButton for user profile actions
- Confirmation dialog before logout
- Clears navigation history on logout (user cannot go back to dashboard)
- Professional card-based UI with proper spacing
- Fully responsive for all screen sizes

**Navigation Flow:**

1. Home Page → "Login / Register" button
2. Login/Register Page → Enter credentials → "Login" or "Register" button
3. User Dashboard → Shows welcome message + user info
4. Logout → Returns to Home Page

## Figma & Design Thinking (Concept 3)

Concept 3 : [Concept-3] Design Thinking for Smart Mobile Interfaces Using Figma & Flutter

Figma link added in README: https://www.figma.com/design/oVfHrUu16qlP7QhvimqI5o/Untitled?node-id=21-2&t=mO2EKGZKPWgBHT9P-1

Creating the High-Level Design (HLD) for Fixora

The High-Level Design (HLD) gives an overview of how the Urban Grievance Redressal System is structured. It explains the main parts of the app, how they connect, and how data flows through the system. This helps in understanding the project’s architecture before moving into detailed implementation.

What the HLD Includes

1. Frontend (Flutter App)

Main screens: Splash, Login, Dashboard, Add Complaint, Complaint Status, Profile.

Simple navigation flow between screens.

Use of state management (like Provider, Riverpod, or Bloc).

Reusable UI components for consistency.

2. Backend (Firebase Services)

Firebase Authentication for secure login (Email/Google).

Cloud Firestore to store user data, complaints, and status updates.

Cloud Storage for uploading photos/videos of issues.

Cloud Functions for sending notifications and automating backend tasks.

3. Data Models

User: id, name, email, role.

Complaint: title, description, category, location, media, status, timestamps.

Updates: timeline of changes for each complaint.

4. Integrations

Google Maps API for selecting and viewing locations.

Firebase Cloud Messaging (FCM) for real-time notifications.

Analytics & Crashlytics for tracking usage and app crashes.

5. CI/CD & Deployment

Automated build and deploy pipelines using GitHub Actions or Codemagic.

Support for multiple environments (dev / staging / production).

The HLD also includes a visual diagram showing how all layers connect.

Here is the figma link:

https://www.figma.com/design/oVfHrUu16qlP7QhvimqI5o/Untitled?node-id=19-2&t=tA9gbpPbYfdawzYP-1

# Firebase SDK Integration (FlutterFire CLI)

## Overview

Firebase SDKs were integrated into a Flutter app using **FlutterFire CLI** for fast and error-free multi-platform setup.

## Steps

```bash
npm install -g firebase-tools
dart pub global activate flutterfire_cli
firebase login
flutterfire configure
```

Generated `firebase_options.dart` automatically.

## Firebase Initialization

```dart
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);
```

## Verification

* App runs successfully
* Firebase Console shows registered app
* Log confirms Firebase initialization

## Reflection

FlutterFire CLI simplified setup, avoided manual configuration, and ensured platform consistency.


Setup completed successfully

---

## Data Requirements List

The application needs to store:

**User**
- userId
- username
- email
- password

**Problem**
- problemId
- userId (reference to user)
- category
- description
- priority
- status
- image
- location

---

## Firestore Schema Design

### 🔹 Collections Overview

- **users**
- **problems**

---

### Users Collection

```
users (collection)
 └── userId (document)
       ├── username: string
       ├── email: string
       ├── password: string
       └── createdAt: timestamp
```

**Sample User Document:**

```json
{
  "username": "guna_priya",
  "email": "[email protected]",
  "password": "hashed_password",
  "createdAt": "2025-02-10T10:30:00Z"
}
```

---

### Problems Collection

```
problems (collection)
 └── problemId (document)
       ├── userId: string
       ├── category: string
       ├── description: string
       ├── priority: string
       ├── status: string
       ├── imageUrl: string
       ├── location: map
       │      ├── latitude: number
       │      └── longitude: number
       ├── createdAt: timestamp
       └── updatedAt: timestamp
```

**Sample Problem Document:**

```json
{
  "userId": "user_001",
  "category": "Water",
  "description": "Water leakage near street corner",
  "priority": "High",
  "status": "Pending",
  "imageUrl": "https://firebase.storage/water_issue.jpg",
  "location": {
    "latitude": 12.9716,
    "longitude": 77.5946
  },
  "createdAt": "2025-02-10T11:00:00Z",
  "updatedAt": "2025-02-10T11:00:00Z"
}
```

---

### Relationships

- Each problem stores `userId` to link it with the user who reported it.
- This avoids large arrays and supports efficient querying.

---

### Schema Diagram

Example structure:

```
users ────────┐
              └── problems (linked via userId)
```

---

### Schema Validation Checklist

✔ Matches application requirements  
✔ Scales to large user bases  
✔ Uses proper data types  
✔ Avoids deeply nested structures  
✔ Easy to understand and maintain  

---

### Reflection

**Why this structure?**

- Separate collections improve scalability.
- Using `userId` references avoids duplication.
- Image URLs reduce document size.

**Performance & Scalability**

- Supports fast queries using indexed fields.
- Firestore real-time updates improve user experience.
- No document size limit issues.

**Challenges Faced**

- Choosing between subcollections and top-level collections.
- Designing location data efficiently.
- Keeping the schema simple but extensible.

## Firestore Write Operations (Flutter)

This module demonstrates how to safely write data to Cloud Firestore from a Flutter application.

#### What’s Covered

Adding new documents to Firestore

Updating existing documents without overwriting data

Using structured and scalable write operations

Validating user input before saving

Handling Firestore errors gracefully

### Outcome

By completing this task, the app can reliably store and update user-generated data (such as complaints or profiles) while ensuring data safety, consistency, and proper error handling.

### Creating a Basic CRUD Flow with Flutter, Firestore, and Auth

This module focuses on building a complete CRUD (Create, Read, Update, Delete) flow using Flutter,
Firebase Authentication, and Cloud Firestore, which together form a powerful stack for modern mobile application development.
The goal is to demonstrate how real-world applications manage user data securely while maintaining a responsive and intuitive user interface.

Firebase Authentication is used to identify and authorize users, ensuring that only authenticated users can access and interact with the application’s data.
Cloud Firestore acts as the primary database, storing structured data and providing real-time updates that automatically reflect changes in the UI without requiring manual refreshes.

The Admin Dashboard showcases how data can be read and displayed in real time, filtered based on status or search criteria,
updated through user actions, and managed efficiently using Firestore queries. The UI is built to handle loading, empty,
and error states gracefully, creating a smooth and reliable user experience.

Overall, this implementation follows common industry practices by clearly separating UI components, authentication logic, and database operations. It serves as a practical example of how Flutter applications can scale while remaining maintainable, secure, and responsive.


## Securing Firebase with Authentication and Firestore Rules

This implementation strengthens application security by combining Firebase Authentication with Firestore Security Rules to ensure that only authorized users can access and modify data.

### Authentication

Firebase Authentication is used to manage user sign-in.

Only authenticated users are allowed to interact with Firestore.

User identity is verified using Firebase-issued ID tokens.

### Firestore Security Rules

Firestore rules restrict read and write access to authenticated users only.

Role-based access control is enforced using user roles (e.g., admin).

Sensitive collections and operations (such as admin dashboards and data management) are protected from unauthorized access.

Rules validate user permissions before allowing data modifications.

### Security Benefits

Prevents unauthorized data access

Protects sensitive admin-only operations

Ensures data integrity by validating user identity and roles

Reduces risk of client-side manipulation

### Outcome

With these measures in place, the application follows Firebase security best practices, providing a safer and more reliable backend for both users and administrators.

### Dark Mode & Dynamic Theming (Flutter)

This app uses Flutter’s theming system to support Light Mode, Dark Mode, and dynamic theme switching across the entire application.

Features

App-wide Light & Dark themes using ThemeData and ColorScheme

Material 3–based styling

Runtime theme switching (Light / Dark / System)

User theme preference persisted using SharedPreferences

Centralized theme configuration for consistent UI

All screens, forms, dialogs, and widgets adapt automatically

### How It Works

Themes are defined in a central theme file

MaterialApp applies theme, darkTheme, and themeMode

A ThemeProvider / ThemeNotifier manages theme state

A toggle (Settings or AppBar) allows users to switch themes

### Usage

Run the app and use the theme toggle to change between Light and Dark modes.
The app remembers your choice on the next launch.


## Push Notifications (FCM) — Implementation notes

This project now includes FCM support and a Cloud Functions implementation to send notifications on complaint create and status change.

What was added
- Flutter packages: `firebase_messaging`, `flutter_local_notifications`
- `lib/services/notification_service.dart` — initializes FCM, saves tokens to `users` doc (`fcmTokens`), and shows foreground notifications.
- `functions/` — Cloud Functions (`onProblemCreate`, `onProblemUpdate`) that send notifications to admins (on create) and the complaint owner (on status change).

Setup & Deployment
1. Ensure your Firebase project has Cloud Messaging enabled (default).
2. From the `functions/` folder:
   - `npm install`
   - `firebase deploy --only functions`

Android
- For Android 13+ you must request POST_NOTIFICATIONS permission at runtime. Consider adding `permission_handler` or request via platform channels.
- Ensure an appropriate notification icon is available (we use `@mipmap/ic_launcher` by default).

iOS
- Add `FirebaseAppDelegateProxyEnabled` & relevant push entitlements and `aps-environment` in your Xcode project.
- Request notification permissions (the app asks on first run).

Testing
- Create a complaint (app) → admins should receive a notification (verify on a device signed in as admin).
- Change a complaint status (Admin UI) → complaint owner should receive a notification (verify on a device signed in as the complaint owner).

Manual verification steps
1. On a test device, sign in as an admin account and ensure notifications are enabled (open Profile → Enable Notifications).
2. Deploy cloud functions: `cd functions && npm install && firebase deploy --only functions`.
3. From another device, create a complaint using the app.
4. The admin device should receive a push notification; check server logs in the Firebase Console if it doesn't.
5. From admin UI change the status to "In Progress" or "Resolved" and verify the complaint owner receives a notification.
6. Check `users/{uid}` doc to see `fcmTokens` array updated when the user enables notifications or signs in.

Notes & Limitations
- Tokens are stored in `users` documents under `fcmTokens` (an array). The Cloud Function attempts to remove invalid tokens when FCM reports them.
- This implementation keeps server-side logic minimal; extend recipient selection, topics, custom data payloads as needed.


# Real-Time Sync with Firestore

This project demonstrates real-time data synchronization using Cloud Firestore in a Flutter application.

The app listens to live database changes using Firestore snapshot listeners (.snapshots()) and updates the UI instantly with StreamBuilder, without manual refresh.

### Features

Live Firestore updates (add, update, delete)

Reactive UI using StreamBuilder

Automatic state handling (loading, error, empty)

Seamless real-time user experience

### Tech Stack

Flutter

Firebase Cloud Firestore

### Goal

Build a modern, responsive app UI that stays in sync with Firestore in real time.


# Uploading Media Using Firebase Storage

## Overview

This feature demonstrates how to upload and manage media files in a Flutter app using Firebase Storage. It allows users to select files from their device, upload them securely, and retrieve download URLs.

## Implementation

```dart
final ref = FirebaseStorage.instance.ref('uploads/file.jpg');
await ref.putFile(file);
final url = await ref.getDownloadURL();
```

## How It Works

1. User selects a file from the device
2. File is uploaded to Firebase Storage
3. Download URL is generated and used in the app

## Why Firebase Storage?

* Secure and scalable
* No backend server required
* Easy Flutter integration

## Use Cases

* Profile images
* Chat media
* Product photos

---

## App Features & Screenshots (Dec 31, 2025)

### 1. Submit Page (Raise Issue)
Users can submit complaints with the following details:
- Category selection (Water, Electricity, Road, Waste Management, etc.)
- Issue title and detailed description
- Location information
- Image attachment support
- Terms & Conditions acceptance checkbox

**Screenshot:** [Submit_page.jpeg](screenshot/Submit_page.jpeg)

### 2. Track Complaint View
Users can track their submitted complaints by:
- Searching with complaint ID
- Filtering by status and category
- Viewing real-time status updates
- Checking complaint details and timeline

**Screenshot:** [Track_view.jpeg](screenshot/Track_view.jpeg)

### 3. User Dashboard
Personalized user interface showing:
- Welcome message with user information
- Quick access to complaint submission
- View submitted complaints history
- Profile management options
- Complaint statistics

**Screenshot:** [User_dashboard.jpeg](screenshot/User_dashboard.jpeg)

### 4. Profile Page
User profile management features:
- User information display
- Submitted complaints history
- Notification preferences
- Account settings
- Logout functionality

**Screenshot:** [Profile_page.jpeg](screenshot/Profile_page.jpeg)

---

## Testing the App on Emulator and Physical Devices

Before deploying or showcasing a Flutter application, it is crucial to test it across multiple devices to ensure consistent behavior. Emulators provide quick testing for different screen sizes and Android versions, while physical devices reveal real-world performance, hardware limitations, and permission flows that emulators may not fully replicate.

This section walks through configuring emulators, enabling developer mode on physical devices, connecting both to Flutter, resolving common device issues, and performing end-to-end testing on at least two different environments.

### 1. Why Testing on Multiple Devices Matters

- **UI Responsiveness**: Ensures UI adapts correctly across screen sizes and resolutions
- **Hardware Validation**: Reveals hardware-related issues (GPS, camera, sensors)
- **Permission Testing**: Validates permissions, notifications, and real-device behavior
- **OS-Specific Bugs**: Helps identify Android/iOS compatibility issues
- **App Reliability**: Improves overall app reliability before release to users

### 2. Setting Up an Emulator

#### Android Emulator (Android Studio)

1. Open Android Studio → Device Manager
2. Click **Create Virtual Device**
3. Choose a device profile (Pixel 6, Pixel 4, etc.)
4. Select a system image (Android 12/13 recommended)
5. Click **Finish** and launch the emulator
6. Once booted, run the Flutter app:

```bash
flutter run
```

**Verification:** Check that the emulator appears when you run:
```bash
flutter devices
```

#### iOS Simulator (macOS only)

1. Open Xcode → Open Developer Tools → Simulator
2. Choose a device: iPhone 14, iPhone 12, etc.
3. Run with:

```bash
flutter run -d ios
```

### 3. Setting Up a Physical Device

#### Android Device Setup

1. Go to **Settings** → **About Phone** → Tap **Build Number** 7 times
2. Enable **Developer Options** (appears in Settings menu)
3. Turn on **USB Debugging** in Developer Options
4. Connect device via USB cable
5. Approve the fingerprint prompt on the device
6. Verify device detection:

```bash
flutter devices
```

7. Run the app:

```bash
flutter run -d <device-id>
```

#### iOS Device Setup (macOS + Xcode)

1. Connect iPhone via USB cable
2. Trust the computer on device
3. Open project in Xcode
4. Add your Apple ID for signing
5. Run using:

```bash
flutter run -d <device-id>
```

### 4. Testing Device-Specific Behaviors

#### What to Test on Emulator

- Multiple screen sizes (phone, tablet)
- Device orientation changes (portrait/landscape)
- App lifecycle: minimize and reopen
- Complete navigation flow
- Form input validation
- Dark/Light theme switching

#### What to Test on Physical Devices

- **Permissions**: Camera, location, notifications
- **Network Connectivity**: WiFi and mobile data
- **Performance & Animations**: Smooth scrolling, transitions
- **Touch Responsiveness**: Button taps, gestures
- **Firebase Integrations**: Authentication, Firestore, FCM
- **Real-world Conditions**: Battery usage, heat, memory

### 5. Debugging Common Device Issues

| Issue | Cause | Fix |
|-------|-------|-----|
| Device not detected | Missing drivers/USB config | Reconnect, install drivers, restart ADB |
| Slow emulator | Low RAM/CPU allocation | Increase hardware profile or use physical device |
| iOS build fails | Missing app signing | Add Apple ID in Xcode |
| Firebase not working | SHA keys missing | Add SHA-1/SHA-256 fingerprints to Firebase Console |
| Permissions denied | User rejected prompt | Revoke & retry permissions in Settings |
| App crashes on startup | Missing dependencies | Run `flutter pub get` and `flutter clean` |

### 6. Running on Multiple Devices Simultaneously

To test on emulator and physical device at the same time:

```bash
# Terminal 1: Run on emulator
flutter run -d emulator-5554

# Terminal 2: Run on physical device
flutter run -d <physical-device-id>
```

### 7. Capturing Screenshots & Logs

#### Take Screenshots

**Android Emulator:**
- Press `Ctrl + S` (Windows/Linux) or `Cmd + S` (macOS)

**Physical Device:**
- Use the device's hardware shortcut (usually Power + Volume Down)

#### View Logs

```bash
flutter logs
```

This displays real-time logs from the running app, helping identify issues and track execution flow.

### 8. Best Practices for Testing

 Test on at least one old + one new Android version

 Test using both light and dark themes

 Check behavior in offline/poor connectivity modes

 Rotate device to test responsiveness and UI adjustments

 Perform extended usage tests to detect memory leaks

 Verify all Firebase features (Auth, Firestore, Storage, FCM)

 Test on different device sizes: phone, tablet

 Test form validation with edge cases (empty fields, special characters)

 Verify notification delivery and display

 Test navigation stack and back button behavior

### 9. End-to-End Testing Checklist for Fixora

- [ ] **User Registration**: Create new account and verify email validation
- [ ] **Login**: Sign in with valid credentials on both emulator and physical device
- [ ] **Submit Complaint**: Create complaint with all fields, verify ID generation
- [ ] **Track Complaint**: Search and filter complaints by ID, status, and category
- [ ] **Real-time Updates**: Change complaint status and verify instant UI update
- [ ] **Notifications**: Enable notifications and verify FCM delivery
- [ ] **Profile Page**: View submitted complaints and user information
- [ ] **Dark Mode**: Switch themes and verify all UI elements adapt correctly
- [ ] **Offline Mode**: Test app behavior when internet is unavailable
- [ ] **Performance**: Monitor memory usage and frame rates using DevTools
- [ ] **Error Handling**: Trigger various errors and verify error messages display correctly

### 10. Continuous Testing Workflow

1. **Start with Emulator**: Quick iteration and debugging
2. **Test on Physical Device**: Verify real-world performance
3. **Check Firebase Console**: Review logs and function executions
4. **Run DevTools**: Inspect widgets and performance metrics
5. **Document Issues**: Log any bugs found with steps to reproduce
6. **Fix & Iterate**: Apply fixes and re-test until all tests pass

### Testing Evidence (Dec 31, 2025)

Testing has been performed across multiple emulators and physical devices with the following confirmations:

- **Submit Page**: Form validation and complaint creation working correctly
- **Track View**: Real-time complaint tracking and status filtering operational
- **User Dashboard**: User information display and navigation functioning properly
- **Profile Page**: Profile management and complaint history accessible
- **Cross-device Testing**: App tested on Android emulator (Pixel 6) and physical devices
- **Theme Testing**: Dark and light modes switching seamlessly across all pages
- **Firebase Integration**: Authentication, Firestore CRUD, and notifications verified
- **Error Handling**: Error messages displaying appropriately across all scenarios

About

This is your first repository

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •