Skip to content
anwarsafyPublic

About

Production Flutter starter with Clean Architecture, Firebase Auth, FCM, Firestore profiles, and English/Arabic RTL.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

Flutter Firebase Starter

Production-ready Flutter starter with Clean Architecture, Firebase, and BLoC state management. Ships with authentication, push notifications (FCM), and user profile features — English + Arabic (RTL) out of the box.


Table of contents


Features

Authentication

  • Email & password (login, register, forgot password)
  • Google Sign-In
  • Apple Sign-In
  • Phone OTP with 60-second resend timer
  • Auth-guarded navigation via GoRouter
  • User document saved to Firestore on sign-in

Push notifications (FCM)

  • Permission request on first launch (iOS + Android 13+)
  • Foreground: custom in-app banner (auto-dismiss 4s)
  • Background & terminated: top-level handler + tap navigation
  • FCM token stored in Firestore users/{uid}/fcmToken
  • Token refresh on onTokenRefresh
  • Last 20 notifications cached locally (SharedPreferences)
  • Notification history screen

User profile

  • View and edit display name & bio
  • Profile photo upload to Firebase Storage
  • Data persisted in Firestore users/{uid}

Core

  • Clean Architecture (domain / data / presentation)
  • Dependency injection (GetIt + injectable)
  • Immutable models & states (freezed)
  • Functional error handling (Either<Failure, T> via fpdart)
  • Light / dark theme (ThemeCubit + SharedPreferences)
  • Localization: English + Arabic (RTL)

Tech stack

Category Packages
State flutter_bloc, bloc_test
DI get_it, injectable
Navigation go_router
Firebase firebase_core, firebase_auth, cloud_firestore, firebase_messaging, firebase_storage, firebase_analytics
Auth providers google_sign_in, sign_in_with_apple
Code gen freezed, json_serializable, build_runner
Testing mocktail, flutter_test
Other fpdart, dio, shared_preferences, image_picker, intl

Architecture

Each feature lives under lib/features/<feature>/ with three layers:

lib/features/<feature>/
├── domain/       # entities, repository contracts, use-cases
├── data/         # models, datasources, repository implementations
└── presentation/ # bloc/cubit, pages, widgets

Shared code: lib/core/ (errors, DI, router, theme, constants, utils).

flowchart TB
    subgraph presentation [Presentation]
        Pages[Pages / Widgets]
        Bloc[BLoC / Cubit]
    end
    subgraph domain [Domain]
        UC[Use Cases]
        RepoAbs[Repository Contract]
        Entity[Entities]
    end
    subgraph data [Data]
        RepoImpl[Repository Impl]
        DS[Datasources]
        Model[Models]
    end
    Pages --> Bloc --> UC --> RepoAbs
    UC --> Entity
    RepoImpl -.implements.-> RepoAbs
    RepoImpl --> DS
    DS --> Model
Loading

Prerequisites

Tool Version
Flutter SDK ≥ 3.10
Dart SDK ≥ 3.10
Firebase project console.firebase.google.com
FlutterFire CLI dart pub global activate flutterfire_cli
Xcode Latest (for iOS)
Android Studio Latest (for Android)

Optional but recommended:

  • A physical device for Phone OTP and Apple Sign-In testing
  • Firebase CLI for rules deployment

Quick start

1. Clone and install dependencies

git clone <your-repo-url>
cd starter
flutter pub get

2. Configure Firebase

dart pub global activate flutterfire_cli
flutterfire configure

This generates lib/firebase_options.dart with your real API keys and downloads platform config files:

  • android/app/google-services.json
  • ios/Runner/GoogleService-Info.plist

3. Generate code

dart run build_runner build --delete-conflicting-outputs
flutter gen-l10n

4. Run

flutter run

Firebase setup

Enable services

In Firebase Console → your project:

Service Where
Authentication Build → Authentication → Sign-in method
Cloud Firestore Build → Firestore Database → Create database
Cloud Storage Build → Storage → Get started
Cloud Messaging Project Settings → Cloud Messaging

Authentication providers

Enable all providers you plan to use:

Provider Console steps
Email/Password Authentication → Sign-in method → Email/Password → Enable
Google Enable Google → add support email
Apple Enable Apple → follow Apple Developer setup (see below)
Phone Enable Phone → add test numbers for development

Google Sign-In (Android)

  1. Firebase Console → Project Settings → Your apps → Android
  2. Add SHA-1 and SHA-256 fingerprints:
# Debug keystore (default)
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
  1. Download updated google-services.json and replace in android/app/

Apple Sign-In (iOS)

  1. Apple Developer → Identifiers → enable Sign in with Apple for your App ID
  2. Xcode → open ios/Runner.xcworkspace → Runner target → Signing & Capabilities → + Capability → Sign in with Apple
  3. Firebase Console → Authentication → Apple → configure Service ID & key
  4. Test on a real iPhone (Simulator support is limited)

Phone OTP

  1. Firebase Console → Authentication → Phone → Enable
  2. Add test phone numbers for development (bypasses SMS)
  3. Use a physical device — emulators often fail SMS delivery
  4. Ensure SHA fingerprints are registered (Android)

iOS push notifications

  1. Apple Developer → create APNs key
  2. Firebase Console → Project Settings → Cloud Messaging → upload APNs key
  3. Xcode → Runner → Signing & Capabilities → Push Notifications + Background Modes → Remote notifications
    (Background modes are already in ios/Runner/Info.plist)

Run the app

# List devices
flutter devices

# Run on a specific device
flutter run -d <device_id>

# Release build
flutter build apk --release
flutter build ios --release

First launch flow

  1. Splash (/) — checks auth state
  2. Login (/login) — if not signed in
  3. Home (/home) — if authenticated

From Home you can open Profile and Notifications.


Project structure

lib/
├── main.dart                    # Firebase init, DI, FCM background handler
├── app.dart                     # MaterialApp.router, theme, banner host
├── firebase_options.dart        # Generated by flutterfire configure
├── core/
│   ├── constants/
│   ├── di/                      # GetIt + injectable
│   ├── errors/                  # Failure types
│   ├── router/                  # GoRouter + auth redirect
│   ├── theme/
│   ├── usecases/
│   └── utils/
├── features/
│   ├── auth/                    # Login, register, OTP, social auth
│   ├── notifications/           # FCM service, history, in-app banner
│   ├── profile/                 # Edit profile, photo upload
│   └── home/
└── l10n/                        # app_en.arb, app_ar.arb

test/
└── features/
    ├── auth/
    ├── notifications/
    └── profile/

Routes

Path Screen Auth required
/ Splash No
/login Login No
/register Register No
/phone-login Phone login No
/otp OTP verification No
/forgot-password Reset password No
/home Home Yes
/profile Profile editor Yes
/notifications Notification history Yes

Route constants: lib/core/router/route_names.dart


Authentication

Supported flows

  • Email — LoginPage, RegisterPage, ForgotPasswordPage
  • Google / Apple — social buttons on login screen
  • Phone — PhoneLoginPage → OtpPage (6-digit input, 60s resend)

Firestore user document

On successful sign-in, a document is created/merged at:

users/{uid}
  ├── email
  ├── displayName
  ├── photoUrl
  ├── phoneNumber
  ├── createdAt
  └── fcmToken          # updated on login & token refresh

Auth state

AuthBloc listens to FirebaseAuth.authStateChanges() and drives GoRouter redirects.


Push notifications (FCM)

How it works

App state Behavior
Foreground In-app banner via NotificationBannerHost
Background System tray notification; tap opens app + navigates
Terminated getInitialMessage() on cold start

Send a test notification

Firebase Console → Engage → Messaging → Create campaign → Firebase Notification messages.

Custom data (required for routing and history):

Key Example Description
type order chat, order, promo, or system
targetRoute /home GoRouter path to open on tap
title New order Fallback title
body Order #123 ready Fallback body

Example payload (HTTP v1 / Cloud Functions):

{
  "message": {
    "token": "<FCM_DEVICE_TOKEN>",
    "notification": {
      "title": "New order",
      "body": "Order #123 is ready"
    },
    "data": {
      "type": "order",
      "targetRoute": "/home",
      "title": "New order",
      "body": "Order #123 is ready"
    }
  }
}

Local history

The last 20 notifications are stored in SharedPreferences and shown on /notifications.


User profile

Firestore fields

users/{uid}
  ├── displayName
  ├── email          # read-only in UI
  ├── bio
  ├── photoUrl
  └── phoneNumber

Photo storage

Uploaded to Firebase Storage:

users/{uid}/avatar.jpg

The download URL is saved to photoUrl in Firestore.

Permissions

  • iOS: NSPhotoLibraryUsageDescription in ios/Runner/Info.plist
  • Android: READ_MEDIA_IMAGES, POST_NOTIFICATIONS in AndroidManifest.xml

Localization

Locale File RTL
English lib/l10n/app_en.arb No
Arabic lib/l10n/app_ar.arb Yes

Access strings in widgets:

import 'package:starter/core/utils/l10n_extension.dart';

Text(context.l10n.loginTitle);

Add a new key to both ARB files, then run:

flutter gen-l10n

Test Arabic: change device language to Arabic or add a locale switcher.


Code generation

Run after changing @freezed, @injectable, or @JsonSerializable classes:

dart run build_runner build --delete-conflicting-outputs

Watch mode (during active development):

dart run build_runner watch --delete-conflicting-outputs

Regenerate localizations:

flutter gen-l10n

Testing

# All tests
flutter test

# With coverage
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html   # optional HTML report

# Analyzer
flutter analyze

Tests use mocktail (not mockito) and bloc_test for BLoC/Cubit sequences.

test/features/
├── auth/           # use-cases, repository, AuthBloc
├── notifications/  # use-cases, NotificationsCubit
└── profile/        # use-cases, ProfileCubit

Security rules

Firestore

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Storage

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /users/{userId}/{allPaths=**} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Deploy with Firebase CLI:

firebase deploy --only firestore:rules,storage

Troubleshooting

firebase_options.dart has placeholder keys

Run flutterfire configure and select your Firebase project.

Google Sign-In fails on Android

  • Add SHA-1/SHA-256 to Firebase Console
  • Re-download google-services.json
  • Use the same package name as registered in Firebase

Apple Sign-In not working

  • Enable capability in Xcode
  • Configure Apple provider in Firebase Console
  • Test on a real device with a valid Apple ID

Phone OTP not received

  • Add test numbers in Firebase Console for dev
  • Use a physical device
  • Check SHA fingerprints (Android)
  • Verify Phone auth is enabled

FCM not showing on iOS

  • Upload APNs key to Firebase Console
  • Enable Push Notifications capability in Xcode
  • Test on a real device (not Simulator for remote pushes)

build_runner conflicts

dart run build_runner build --delete-conflicting-outputs

Profile photo upload fails

  • Enable Firebase Storage in Console
  • Deploy Storage security rules
  • Check photoUrl write permissions on users/{uid}

Analyzer / import errors after pull

flutter pub get
dart run build_runner build --delete-conflicting-outputs
flutter gen-l10n

License

This project is provided as a starter template. Add your own license as needed.

About

Production Flutter starter with Clean Architecture, Firebase Auth, FCM, Firestore profiles, and English/Arabic RTL.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages