Flutter + Firebase + BLoC — Production Skill
Universal Skill: Compatible with Claude Code, Cursor, Windsurf, GitHub Copilot, Codex CLI, Gemini CLI / Antigravity, and standalone
AGENTS.md/.cursorrules. Load files fromreferences/on demand for the specific domain you are implementing; copy base configs directly fromtemplates/.
1. Reference Map (Progressive Disclosure)
| Need | Read This File |
|---|---|
Domain, Data, Offline-First, Pagination, Storage, DI (GetIt + Injectable) |
references/architecture-and-di.md |
| Full Auth (Google, Apple Nonce, OTP, Email, DeleteAccount), Security Rules, App Check, RASP, Rules Unit Tests | references/auth-and-security.md |
Single-State BLoC, Sealed AppFailure, Static AppLogger, ErrorReporter, Theme, AdaptiveScaffold, EN/AR RTL l10n |
references/bloc-errors-l10n.md |
Leak-Free FcmService (Mobile + Web VAPID/SW), Local Notifications, Cloud Functions v2, GoRouter + Universal/App Links |
references/notifications-and-links.md |
Flavors (dev/staging/prod), bootstrap(), Performance Traces, Remote Config + A/B, GitHub Actions CI/CD + Symbols, Tests |
references/flavors-perf-rc-cicd.md |
| Starter Configs & Templates | templates/: analysis_options.yaml, l10n.yaml, firebase.json, pubspec.yaml, app_en.arb, app_ar.arb, firestore.indexes.json, .firebaserc, dependabot.yml, ExportOptions.plist |
2. Decision Matrix (Choose Once, Never Mix)
| Decision | Default Choice | When to Use Alternative |
|---|---|---|
State equality & copyWith |
Equatable + manual copyWith |
Freezed only if used consistently across ALL models & states |
| Firestore writes | Offline-first unawaited writes (client IDs + batch <= 400 ops); server rejections go to WriteErrorBus -> localized SnackBar |
onCall Cloud Function for billing, quotas, multi-user invariants, and ALL recursive deletes (a board with sub-collections, account data) |
Connectivity check (NetworkInfo) |
Never gate normal Firestore CRUD | Always gate onCall Functions, Storage uploads, and deleteAccount |
| Failure handling | Sealed AppFailure -> mapException() / stream.catchFailures() -> failure.localize(context) |
Never pass raw e.toString(), English strings, or display text (ValidationFailure carries a code) into UI state |
| Local persistence | SharedPreferences ONLY for non-sensitive UI prefs (theme, locale, drafts) |
flutter_secure_storage for any tokens, secrets, or sensitive local data |
| Navigation | GoRouter with RouteNames + AuthStatus.unknown splash guard |
Never call Navigator.of(context).push for app routes |
| Logging & crashes | Static AppLogger -> ErrorReporter (Crashlytics on mobile, console/Sentry on web) |
Never call print() or invoke Crashlytics directly on Web |
| Functional types | fpdart (Either, Right, Left, unit) |
Never dartz (unmaintained) |
| Combining auth + profile streams | rxdart switchMap |
Never asyncExpand for endless inner streams — it blocks the next outer event forever |
3. The 10 Ironclad Laws (Anti-Patterns)
domain/is pure Dart. NEVER importflutter/*,cloud_firestore,firebase_auth, orfirebase_messagingindomain/.- Every repository method returns
Future<Either<AppFailure, T>>orStream<Either<AppFailure, T>>. Map withmapException()(CancelledException->FirebaseAuthException->FirebaseException->Object). Streams MUST end with.catchFailures(op):try/catcharoundyield*does NOT catch stream errors. - One state class per feature BLoC. Use
enum <Feature>Status { initial, loading, success, failure }+copyWith+AppFailure? failure. Failed refreshes MUST preserve existing data in state. Everyemit.forEachhas anonError. - NEVER leak
StreamSubscriptions. Useemit.forEach/emit.onEachinside BLoC handlers, registered withtransformer: restartable()(bloc_concurrency); refresh byadd(WatchStarted(...)), never by calling the handler directly. In singleton services (FcmService,ConnectivityCubit,FeatureFlagsCubit), store and cancel all subscriptions indispose()/close(). - Offline-first means NEVER
awaitFirestore write futures (set,update,delete,batch.commit) in normal CRUD. Fire via_fireAndLog(...)(which publishes rejections toWriteErrorBus) and listen viasnapshots(includeMetadataChanges: true). - Transactions fail offline. Never call
runTransactionon the client for user actions; move transactions to Cloud Functions. - Always
withConverterfor Firestore reads, and always writeupdatedAt: FieldValue.serverTimestamp(). Handle nullableTimestamp?locally (?? DateTime.now()). - Zero hardcoded colors, strings, or directional padding. Use
Theme.of(context).colorScheme.*,AppLocalizations.of(context), andEdgeInsetsDirectional/AlignmentDirectionalfor RTL. - Security Rules deny by default & block tampering:
-
users/{uid}uses an ALLOW-LIST of client fields:keys().hasOnly(...)on create,diff().affectedKeys().hasOnly(...)on update. Privileged fields (isPro,role,plan,boardCount, anything new) are writable ONLY by Admin SDK / Custom Claims. A deny-list (unchanged([...])) alone is NOT enough. - Server timestamps are enforced (updatedAt == request.time); recursive deletes areallow delete: if false+ callable Function. - Every tamper rule has a@firebase/rules-unit-testingtest, includingupdatepaths. - Prevent scraping (allow get: if isSignedIn(); allow list: if false;onpublicProfiles). - Validatekeys().hasOnly(...)and string/arraysize()on BOTHcreateandupdate. - Notifications are created ONLY by Cloud Functions; Storage rules MUST checkfirestore.exists(...)beforefirestore.get(...). - Never use FCM topics for private data: any client can subscribe to any topic. Send to member tokens. - Account deletion erases server data (cleanupDeletedUserononUserDeleted) — App Store / Google Play requirement. - Zero secrets in client code or
--dart-define. Protection = Security Rules + App Check (Play Integrity/App Attest/reCAPTCHA Enterpriseenforced on Auth, Firestore, Storage, andonCallFunctions) + Hosting CSP/HSTS/X-Frame-Optionsheaders (templates/firebase.json— verify the CSP on a staging deploy before prod).
4. Canonical Project Layout
project_root/
├── analysis_options.yaml # Copy from templates/analysis_options.yaml
├── l10n.yaml # Copy from templates/l10n.yaml
├── firebase.json # Copy from templates/firebase.json
├── .firebaserc # Copy from templates/.firebaserc
├── .fvmrc / pubspec.yaml # Copy starter from templates/pubspec.yaml
├── .github/
│ ├── dependabot.yml # Copy from templates/dependabot.yml
│ └── workflows/ # ci.yml, deploy-web.yml, deploy-firebase.yml, release-*.yml
├── ios/ExportOptions.plist # Copy from templates/ExportOptions.plist
├── firebase/
│ ├── firestore.rules / storage.rules
│ ├── firestore.indexes.json # Copy from templates/firestore.indexes.json
│ ├── tests/ # @firebase/rules-unit-testing
│ └── functions/src/ # index.ts, notifications/, triggers/
├── web/firebase-messaging-sw.js
├── lib/
│ ├── app.dart / app_config.dart / bootstrap.dart
│ ├── main_dev.dart / main_staging.dart / main_prod.dart
│ ├── injection_container.dart
│ ├── l10n/ (app_en.arb, app_ar.arb)
│ ├── core/ (constants, errors, firebase, l10n, network, notifications, observers, performance, remote_config, router, storage, theme, usecases, utils, widgets)
│ ├── common/ (layouts, widgets shared across >=2 features)
│ └── features/ (auth, notifications, <feature>/{domain,data,presentation})
├── test/ (unit, widget, helpers)
└── integration_test/
5. Exact Startup Sequence (bootstrap.dart)
Every flavor entrypoint (main_dev.dart, main_staging.dart, main_prod.dart) calls AppConfig.init(...) then bootstrap():
WidgetsFlutterBinding.ensureInitialized()await Firebase.initializeApp(options: AppConfig.instance.firebaseOptions)await activateAppCheck()(debug in dev; PlayIntegrity / AppAttest / ReCaptchaEnterprise in staging/prod)- Register
ErrorReporter(WebErrorReporteron web,CrashlyticsErrorReporteron mobile) +await installGlobalErrorHandlers(reporter) await configureFirestore()(runs a pending sign-out cache wipe viaclearPersistence(), then persistence + 100 MB cache — MUST precede any Firestore call; neverterminate()the shared instance at runtime)await configureDependencies()(sl.init()with@preResolveforSharedPreferences&PackageInfo)await sl<RemoteConfigService>().init()(activate()cached + unawaited backgroundfetch())await sl<PerfService>().init()(enabled only inprod)- Register
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler)+setForegroundNotificationPresentationOptions(...) Bloc.observer = AppBlocObserver()sl<AuthBloc>().add(const AuthWatchStarted())runApp(const App())
6. Feature Scaffold Order (Inside-Out)
domain/: Entity (Equatable) -> Repository interface (Either<AppFailure, T>) -> UseCases (UseCase/StreamUseCase+ typedParams).data/: Model (null-safefromFirestore,?? DateTime.now(),hasPendingWrites,toMap(),toEntity()) -> Datasource (withConverter,snapshots(includeMetadataChanges: true), unawaited_fireAndLog, cursor pagination) -> RepositoryImpl (mapsFirebaseAuthException->FirebaseException->AppLogger.error).presentation/: Single State + enum +copyWith-> Sealed Events ->@injectableBLoC (emit.forEach) ->BlocConsumerUI (ErrorViewonly when list empty, otherwiseAppSnackBar.error).- Routing & Security:
RouteNames+createAppRouter(deep links preserved via?from=) ->firebase/firestore.rules+firebase/firestore.indexes.json-> Cloud Functions if needed. - Tests: Unit tests (UseCases + Repository) ->
blocTest-> Widget tests (wrapped withAppLocalizationsdelegates) -> Emulator integration & Rules unit tests.
7. Mandatory Verification Gate (Run Before Finishing)
flutter gen-l10n
dart run build_runner build --delete-conflicting-outputs
dart format --output=none --set-exit-if-changed lib test
flutter analyze
flutter test
# If firebase/functions changed:
(cd firebase/functions && npm run build)
# If rules changed:
firebase emulators:exec --only firestore "npx vitest run firebase/tests"
# If composite queries changed:
firebase emulators:exec --only auth,firestore "flutter test integration_test/"
Architecture, Offline-First Data & Dependency Injection (Complete Code)
1. pubspec.yaml
name: my_app
description: Flutter + Firebase + BLoC Production App
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.12.0
flutter: ">=3.44.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
# Firebase (versions verified on pub.dev, Nov 2026)
firebase_core: ^5.2.0
firebase_auth: ^7.1.0
cloud_firestore: ^7.2.0
cloud_functions: ^7.1.0
firebase_messaging: ^17.1.0
firebase_storage: ^14.0.1
firebase_analytics: ^13.1.0
firebase_crashlytics: ^6.1.0
firebase_performance: ^0.12.1
firebase_remote_config: ^7.0.1
firebase_app_check: ^0.5.2
google_sign_in: ^7.2.0
sign_in_with_apple: ^8.2.0
# State & DI
flutter_bloc: ^9.1.1
bloc_concurrency: ^0.3.0
equatable: ^2.0.7
get_it: ^9.3.0
injectable: ^3.0.0
# Navigation, Functional & Streams
go_router: ^18.1.4
fpdart: ^1.2.0
rxdart: ^0.28.0
# Notifications & UI
flutter_local_notifications: ^23.0.3
app_badge_plus: ^1.4.0
cached_network_image: ^3.4.1
# Network, Storage & Utils
connectivity_plus: ^7.3.2
shared_preferences: ^2.5.6
flutter_secure_storage: ^11.2.0
dio: ^5.11.1
intl: any # pinned by flutter_localizations
crypto: ^3.0.6
package_info_plus: ^10.2.2
pub_semver: ^2.2.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
very_good_analysis: ^11.0.0
bloc_test: ^10.0.0
mocktail: ^1.0.4
fake_cloud_firestore: ^4.5.0
build_runner: ^2.17.1
injectable_generator: ^3.1.3
flutter:
generate: true
uses-material-design: true
2. UseCase Base (lib/core/usecases/usecase.dart)
import 'package:fpdart/fpdart.dart';
import 'package:equatable/equatable.dart';
import '../errors/failures.dart';
abstract interface class UseCase<Type, Params> {
Future<Either<AppFailure, Type>> call(Params params);
}
abstract interface class StreamUseCase<Type, Params> {
Stream<Either<AppFailure, Type>> call(Params params);
}
final class NoParams extends Equatable {
const NoParams();
@override
List<Object?> get props => [];
}
3. Dependency Injection (lib/injection_container.dart)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'injection_container.config.dart';
final GetIt sl = GetIt.instance;
@InjectableInit()
Future<void> configureDependencies() => sl.init();
@module
abstract class FirebaseModule {
@lazySingleton FirebaseFirestore get firestore => FirebaseFirestore.instance;
@lazySingleton FirebaseAuth get auth => FirebaseAuth.instance;
@lazySingleton FirebaseFunctions get functions => FirebaseFunctions.instance;
@lazySingleton FirebaseMessaging get messaging => FirebaseMessaging.instance;
@lazySingleton FirebaseStorage get storage => FirebaseStorage.instance;
@lazySingleton FirebaseRemoteConfig get remoteConfig => FirebaseRemoteConfig.instance;
@lazySingleton FirebasePerformance get performance => FirebasePerformance.instance;
@lazySingleton FirebaseAnalytics get analytics => FirebaseAnalytics.instance;
@lazySingleton Connectivity get connectivity => Connectivity();
@lazySingleton FlutterSecureStorage get secureStorage => const FlutterSecureStorage();
@preResolve Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
@preResolve Future<PackageInfo> get packageInfo => PackageInfo.fromPlatform();
}
4. Offline-First Firestore + Connectivity (core/firebase/firestore_setup.dart, core/network/*, core/widgets/offline_banner.dart)
// lib/core/firebase/firestore_setup.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shared_preferences/shared_preferences.dart';
const kPendingCacheWipeKey = 'pending_firestore_cache_wipe';
/// Call in `bootstrap()` BEFORE any other Firestore call.
/// Sign-out only marks the wipe (see `AuthRemoteDatasource.signOut`): calling
/// `terminate()` at runtime would kill the `FirebaseFirestore` instance that
/// GetIt and every datasource already hold. `clearPersistence()` is only legal
/// before the instance starts, so the wipe runs on the next cold start.
Future<void> configureFirestore() async {
final prefs = await SharedPreferences.getInstance();
if (prefs.getBool(kPendingCacheWipeKey) ?? false) {
await FirebaseFirestore.instance.clearPersistence();
await prefs.remove(kPendingCacheWipeKey);
}
FirebaseFirestore.instance.settings = const Settings(
persistenceEnabled: true,
cacheSizeBytes: 100 * 1024 * 1024, // 100 MB
);
}
// lib/core/firebase/write_error_bus.dart
// Offline-first writes are not awaited, so a server rejection (rules, App Check)
// can't be returned to the caller. Publish it here; `App` shows a localized
// SnackBar, so the user knows why an optimistic change disappeared.
@lazySingleton
class WriteErrorBus {
final _controller = StreamController<AppFailure>.broadcast();
Stream<AppFailure> get stream => _controller.stream;
void add(AppFailure failure) {
if (!_controller.isClosed) _controller.add(failure);
}
@disposeMethod
Future<void> dispose() => _controller.close();
}
// lib/core/errors/stream_failures.dart
// `try/catch` around `yield*` does NOT catch stream errors — they are forwarded
// to the listener. Map every repository stream through `catchFailures`, so the
// BLoC always receives `Left(AppFailure)` instead of a raw exception.
extension EitherStreamX<T> on Stream<Either<AppFailure, T>> {
Stream<Either<AppFailure, T>> catchFailures(String op) => transform(
StreamTransformer.fromHandlers(
handleError: (Object e, StackTrace s, EventSink<Either<AppFailure, T>> sink) =>
sink.add(Left(mapException(e, s, op))),
),
);
}
AppFailure mapException(Object e, StackTrace s, String op) {
if (e is CancelledException) return const CancelledFailure(); // user closed the sign-in sheet
// Order matters: FirebaseAuthException and FirebaseFunctionsException extend FirebaseException.
if (e is FirebaseAuthException) return e.toFailure();
if (e is FirebaseException) return e.toFailure();
AppLogger.error('$op failed', error: e, stack: s);
return const UnknownFailure('unknown');
}
// lib/core/network/network_info.dart
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:injectable/injectable.dart';
abstract interface class NetworkInfo {
Future<bool> get isConnected;
Stream<bool> get onStatusChange;
}
@LazySingleton(as: NetworkInfo)
class NetworkInfoImpl implements NetworkInfo {
NetworkInfoImpl(this._connectivity);
final Connectivity _connectivity;
@override
Future<bool> get isConnected async => _hasNetwork(await _connectivity.checkConnectivity());
@override
Stream<bool> get onStatusChange => _connectivity.onConnectivityChanged.map(_hasNetwork).distinct();
bool _hasNetwork(List<ConnectivityResult> results) =>
results.any((r) => r != ConnectivityResult.none);
}
// lib/core/network/connectivity_cubit.dart
@lazySingleton
class ConnectivityCubit extends Cubit<bool> {
ConnectivityCubit(this._network) : super(true) {
_sub = _network.onStatusChange.listen(emit);
unawaited(_network.isConnected.then((online) {
if (!isClosed) emit(online);
}));
}
final NetworkInfo _network;
late final StreamSubscription<bool> _sub;
@override
Future<void> close() async {
await _sub.cancel();
return super.close();
}
}
// lib/core/widgets/offline_banner.dart
class OfflineBanner extends StatelessWidget {
const OfflineBanner({super.key});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final l = AppLocalizations.of(context);
return BlocBuilder<ConnectivityCubit, bool>(
builder: (context, online) => AnimatedSize(
duration: const Duration(milliseconds: 250),
child: online
? const SizedBox(width: double.infinity)
: Material(
color: cs.tertiaryContainer,
child: SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsetsDirectional.symmetric(horizontal: 16, vertical: 8),
child: Row(children: [
Icon(Icons.cloud_off_rounded, size: 18, color: cs.onTertiaryContainer),
const SizedBox(width: 8),
Expanded(
child: Text(l.offlineBanner, style: TextStyle(color: cs.onTertiaryContainer)),
),
]),
),
),
),
),
);
}
}
5. Safe Model, Offline Datasource & Repository Impl
// features/boards/data/models/board_model.dart
class BoardModel {
const BoardModel({
required this.id,
required this.title,
required this.color,
required this.ownerId,
required this.memberIds,
required this.updatedAt,
this.createdAt,
this.hasPendingWrites = false,
});
final String id, title, color, ownerId;
final List<String> memberIds;
final DateTime? createdAt;
final DateTime updatedAt;
final bool hasPendingWrites;
factory BoardModel.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
final data = doc.data() ?? <String, dynamic>{};
return BoardModel(
id: doc.id,
title: (data['title'] as String?) ?? '',
color: (data['color'] as String?) ?? '#6366F1',
ownerId: (data['ownerId'] as String?) ?? '',
memberIds: List<String>.from((data['memberIds'] as List?) ?? const []),
createdAt: (data['createdAt'] as Timestamp?)?.toDate(),
updatedAt: (data['updatedAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
hasPendingWrites: doc.metadata.hasPendingWrites,
);
}
Map<String, dynamic> toMap() => {
'title': title,
'color': color,
'ownerId': ownerId,
'memberIds': memberIds,
'updatedAt': FieldValue.serverTimestamp(),
};
BoardEntity toEntity() => BoardEntity(
id: id,
title: title,
color: color,
ownerId: ownerId,
memberIds: memberIds,
createdAt: createdAt,
updatedAt: updatedAt,
hasPendingWrites: hasPendingWrites,
);
}
// features/boards/data/datasources/boards_remote_datasource.dart
abstract interface class BoardsRemoteDatasource {
Stream<List<BoardModel>> watchBoards(String userId);
Future<BoardModel> createBoard(CreateBoardParams params);
Future<void> updateBoard(String boardId, Map<String, dynamic> data);
Future<void> deleteBoard(String boardId);
}
@LazySingleton(as: BoardsRemoteDatasource)
class BoardsRemoteDatasourceImpl implements BoardsRemoteDatasource {
const BoardsRemoteDatasourceImpl(this._firestore, this._functions, this._writeErrors);
final FirebaseFirestore _firestore;
final FirebaseFunctions _functions;
final WriteErrorBus _writeErrors;
CollectionReference<Map<String, dynamic>> get _raw => _firestore.collection('boards');
CollectionReference<BoardModel> get _boards => _raw.withConverter<BoardModel>(
fromFirestore: (snap, _) => BoardModel.fromFirestore(snap),
toFirestore: (model, _) => model.toMap(),
);
@override
Stream<List<BoardModel>> watchBoards(String userId) => _boards
.where('memberIds', arrayContains: userId)
.orderBy('updatedAt', descending: true)
.limit(50)
.snapshots(includeMetadataChanges: true)
.map((s) => s.docs.map((d) => d.data()).toList());
@override
Future<BoardModel> createBoard(CreateBoardParams params) async {
final ref = _raw.doc(); // client-generated ID works offline
final model = BoardModel(
id: ref.id,
title: params.title,
color: params.color,
ownerId: params.userId,
memberIds: [params.userId],
updatedAt: DateTime.now(),
hasPendingWrites: true,
);
_fireAndLog(
ref.set({...model.toMap(), 'createdAt': FieldValue.serverTimestamp()}),
'createBoard',
);
return model;
}
@override
Future<void> updateBoard(String boardId, Map<String, dynamic> data) async {
_fireAndLog(
_raw.doc(boardId).update({...data, 'updatedAt': FieldValue.serverTimestamp()}),
'updateBoard',
);
}
/// Recursive deletes run server-side (Decision Matrix): a client batch only
/// sees cached sub-documents when offline and would leave orphaned cards.
/// The repository gates this call on `NetworkInfo`.
@override
Future<void> deleteBoard(String boardId) async {
await _functions.httpsCallable('deleteBoardRecursive').call<void>({'boardId': boardId});
}
void _fireAndLog(Future<void> write, String op) {
unawaited(write.catchError((Object e, StackTrace s) {
_writeErrors.add(mapException(e, s, op)); // user sees a localized SnackBar
AppLogger.error('$op rejected by server', error: e, stack: s);
}));
}
}
// features/boards/data/repositories/boards_repository_impl.dart
@LazySingleton(as: BoardsRepository)
class BoardsRepositoryImpl implements BoardsRepository {
const BoardsRepositoryImpl(this._remote, this._network);
final BoardsRemoteDatasource _remote;
final NetworkInfo _network;
@override
Stream<Either<AppFailure, List<BoardEntity>>> watchBoards(String userId) => _remote
.watchBoards(userId)
.map<Either<AppFailure, List<BoardEntity>>>(
(models) => Right(models.map((m) => m.toEntity()).toList()),
)
.catchFailures('watchBoards');
@override
Future<Either<AppFailure, BoardEntity>> createBoard(CreateBoardParams params) async {
try {
final model = await _remote.createBoard(params);
return Right(model.toEntity());
} catch (e, s) {
return Left(mapException(e, s, 'createBoard'));
}
}
@override
Future<Either<AppFailure, Unit>> deleteBoard(String boardId) async {
if (!await _network.isConnected) return const Left(NetworkFailure());
try {
await _remote.deleteBoard(boardId);
return const Right(unit);
} catch (e, s) {
return Left(mapException(e, s, 'deleteBoard'));
}
}
}
6. Cursor Pagination, Storage Service, DraftStore, Fractional Ordering & Sign-Out Wipe
// Cursor pagination
class PaginatedResult<T> {
const PaginatedResult({required this.items, required this.hasMore, this.cursor});
final List<T> items;
final bool hasMore;
final Object? cursor;
}
Future<PaginatedResult<ActivityModel>> fetchActivityPage({
required String boardId,
Object? cursor,
int pageSize = 25,
}) async {
var q = _firestore
.collection('boards').doc(boardId).collection('activity')
.orderBy('createdAt', descending: true)
.limit(pageSize);
if (cursor is DocumentSnapshot) q = q.startAfterDocument(cursor);
final snap = await q.get();
return PaginatedResult(
items: snap.docs.map(ActivityModel.fromFirestore).toList(),
hasMore: snap.docs.length == pageSize,
cursor: snap.docs.isEmpty ? cursor : snap.docs.last,
);
}
// lib/core/storage/storage_service.dart
@lazySingleton
class StorageService {
StorageService(this._storage, this._perf);
final FirebaseStorage _storage;
final PerfService _perf;
Future<String> uploadBytes({
required String path,
required Uint8List bytes,
required String contentType,
void Function(double progress)? onProgress,
}) =>
_perf.trace('storage_upload', () async {
final ref = _storage.ref(path);
final task = ref.putData(bytes, SettableMetadata(contentType: contentType));
final sub = task.snapshotEvents.listen((s) {
if (s.totalBytes > 0) onProgress?.call(s.bytesTransferred / s.totalBytes);
});
try {
await task;
return await ref.getDownloadURL();
} finally {
await sub.cancel();
}
}, attributes: {'size_bucket': bytes.length < 1048576 ? '<1MB' : '>=1MB'});
Future<void> delete(String path) => _storage.ref(path).delete();
}
// lib/core/storage/draft_store.dart (non-sensitive UI drafts only; use FlutterSecureStorage for secrets)
@lazySingleton
class DraftStore {
DraftStore(this._prefs);
final SharedPreferences _prefs;
String? read(String cardId) => _prefs.getString('draft_$cardId');
Future<void> save(String cardId, String text) => _prefs.setString('draft_$cardId', text);
Future<void> clear(String cardId) => _prefs.remove('draft_$cardId');
}
// Fractional ordering (drag-and-drop updates ONE document)
double positionBetween(double? before, double? after) {
if (before == null && after == null) return 1000;
if (before == null) return after! - 1000;
if (after == null) return before + 1000;
return (before + after) / 2;
}
// Sign-out local persistence wipe: mark it, never `terminate()` the shared instance.
// `configureFirestore()` clears the cache on the next cold start.
// High-sensitivity apps (shared devices, fintech): restart the process right after
// sign-out so the wipe happens immediately.
Future<void> signOutAndMarkCacheWipe(FirebaseAuth auth, SharedPreferences prefs) async {
await prefs.setBool(kPendingCacheWipeKey, true);
await auth.signOut();
}
Authentication & Hardened Security (Complete Code)
1. UserEntity, UserModel & AuthRepository
// features/auth/domain/entities/user_entity.dart
class UserEntity extends Equatable {
const UserEntity({
required this.id,
this.name,
this.email,
this.phone,
this.photoUrl,
this.username,
this.isPro = false,
});
final String id;
final String? name, email, phone, photoUrl, username;
final bool isPro;
bool get needsOnboarding => username == null || username!.isEmpty;
@override
List<Object?> get props => [id, name, email, phone, photoUrl, username, isPro];
}
// features/auth/data/models/user_model.dart
class UserModel {
const UserModel({
required this.id,
this.name,
this.email,
this.phone,
this.photoUrl,
this.username,
this.isPro = false,
});
final String id;
final String? name, email, phone, photoUrl, username;
final bool isPro;
factory UserModel.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
final d = doc.data() ?? <String, dynamic>{};
return UserModel(
id: doc.id,
name: d['name'] as String?,
email: d['email'] as String?,
phone: d['phone'] as String?,
photoUrl: d['photoUrl'] as String?,
username: d['username'] as String?,
isPro: (d['isPro'] as bool?) ?? false,
);
}
factory UserModel.fromFirebaseUser(User u) => UserModel(
id: u.uid,
name: u.displayName,
email: u.email,
phone: u.phoneNumber,
photoUrl: u.photoURL,
);
UserEntity toEntity() => UserEntity(
id: id,
name: name,
email: email,
phone: phone,
photoUrl: photoUrl,
username: username,
isPro: isPro,
);
}
2. Complete AuthRemoteDatasourceImpl (All Auth Methods + Delete Account)
// imports: package:rxdart/rxdart.dart (switchMap, onErrorReturnWith),
// package:google_sign_in/google_sign_in.dart (v7 API), package:shared_preferences/shared_preferences.dart
@LazySingleton(as: AuthRemoteDatasource)
class AuthRemoteDatasourceImpl implements AuthRemoteDatasource {
AuthRemoteDatasourceImpl(this._auth, this._firestore, this._prefs);
final FirebaseAuth _auth;
final FirebaseFirestore _firestore;
final SharedPreferences _prefs;
Future<void>? _googleInit;
/// `switchMap` (NOT `asyncExpand`): `asyncExpand` waits for the inner
/// `snapshots()` stream to finish before handling the next auth event, and
/// that stream never finishes — so sign-out (`null`) would never arrive.
/// `switchMap` cancels the previous user's listener on every auth change.
@override
Stream<UserModel?> watchAuthState() => _auth.authStateChanges().switchMap((user) {
if (user == null) return Stream<UserModel?>.value(null);
return _firestore
.collection('users')
.doc(user.uid)
.snapshots()
.map<UserModel?>(
(doc) => doc.exists ? UserModel.fromFirestore(doc) : UserModel.fromFirebaseUser(user),
)
// Profile read failed (e.g. rules, offline first launch): stay signed in with Auth data.
.onErrorReturnWith((Object e, StackTrace s) {
AppLogger.error('watch user profile failed', error: e, stack: s);
return UserModel.fromFirebaseUser(user);
});
});
// google_sign_in 7.x: initialize() exactly once before any other call.
Future<void> _ensureGoogleInit() => _googleInit ??= GoogleSignIn.instance.initialize(
serverClientId: AppConfig.instance.googleServerClientId, // null on Android = read from google-services.json
);
@override
Future<UserModel> signInWithGoogle() async {
if (kIsWeb) {
// GoogleSignIn.authenticate() is not supported on web; use the Firebase popup flow.
final cred = await _auth.signInWithPopup(GoogleAuthProvider());
return _upsertUser(cred.user!);
}
await _ensureGoogleInit();
final GoogleSignInAccount account;
try {
account = await GoogleSignIn.instance.authenticate(scopeHint: const ['email']);
} on GoogleSignInException catch (e) {
if (e.code == GoogleSignInExceptionCode.canceled) throw const CancelledException();
rethrow;
}
final idToken = account.authentication.idToken; // v7: ID token only, no access token
final cred = await _auth.signInWithCredential(GoogleAuthProvider.credential(idToken: idToken));
return _upsertUser(cred.user!);
}
@override
Future<UserModel> signInWithApple() async {
final rawNonce = generateNonce();
final sha256Nonce = sha256.convert(utf8.encode(rawNonce)).toString();
final AuthorizationCredentialAppleID appleCred;
try {
appleCred = await SignInWithApple.getAppleIDCredential(
scopes: [AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName],
nonce: sha256Nonce,
);
} on SignInWithAppleAuthorizationException catch (e) {
if (e.code == AuthorizationErrorCode.canceled) throw const CancelledException();
rethrow;
}
final cred = await _auth.signInWithCredential(
OAuthProvider('apple.com').credential(idToken: appleCred.identityToken, rawNonce: rawNonce),
);
final name = [appleCred.givenName, appleCred.familyName].whereType<String>().join(' ').trim();
return _upsertUser(cred.user!, displayName: name.isEmpty ? null : name);
}
@override
Future<String> sendOtp(String phoneNumber) {
final completer = Completer<String>();
unawaited(_auth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 60),
verificationCompleted: (_) {},
verificationFailed: (e) {
if (!completer.isCompleted) completer.completeError(e);
},
codeSent: (id, _) {
if (!completer.isCompleted) completer.complete(id);
},
codeAutoRetrievalTimeout: (_) {},
));
return completer.future;
}
@override
Future<UserModel> verifyOtp({required String verificationId, required String otp}) async {
final cred = await _auth.signInWithCredential(
PhoneAuthProvider.credential(verificationId: verificationId, smsCode: otp.trim()),
);
return _upsertUser(cred.user!);
}
@override
Future<UserModel> signInWithEmail({required String email, required String password}) async {
final cred = await _auth.signInWithEmailAndPassword(email: email.trim(), password: password);
return _upsertUser(cred.user!);
}
@override
Future<UserModel> signUpWithEmail({required String email, required String password}) async {
final cred = await _auth.createUserWithEmailAndPassword(email: email.trim(), password: password);
return _upsertUser(cred.user!);
}
@override
Future<void> sendPasswordReset(String email) =>
_auth.sendPasswordResetEmail(email: email.trim());
/// Throws FirebaseAuthException('requires-recent-login') if the session is old:
/// the UI must re-authenticate (Google/Apple/OTP again) and retry.
/// Server data is erased by the `cleanupDeletedUser` Cloud Function (notifications-and-links.md §4).
@override
Future<void> deleteAccount() async {
final user = _auth.currentUser;
if (user == null) return;
await user.delete();
await _afterSessionEnd();
}
@override
Future<void> signOut() async {
await _auth.signOut();
await _afterSessionEnd();
}
Future<void> _afterSessionEnd() async {
// Never `terminate()` here: GetIt and every datasource hold this Firestore instance.
await _prefs.setBool(kPendingCacheWipeKey, true); // cleared on next cold start
if (!kIsWeb && _googleInit != null) {
await GoogleSignIn.instance.signOut().catchError((Object _) {});
}
}
Future<UserModel> _upsertUser(User user, {String? displayName}) async {
final ref = _firestore.collection('users').doc(user.uid);
// Note: Never send `isPro`, `role`, or `boardCount` from client — Security Rules block them.
await ref.set({
'id': user.uid,
'name': displayName ?? user.displayName,
'email': user.email,
'phone': user.phoneNumber,
'photoUrl': user.photoURL,
'lastSignIn': FieldValue.serverTimestamp(),
}, SetOptions(merge: true));
return UserModel.fromFirestore(await ref.get());
}
}
2b. AuthRepositoryImpl (Stream Errors Mapped, Network-Gated Delete)
@LazySingleton(as: AuthRepository)
class AuthRepositoryImpl implements AuthRepository {
const AuthRepositoryImpl(this._remote, this._network);
final AuthRemoteDatasource _remote;
final NetworkInfo _network;
@override
Stream<Either<AppFailure, UserEntity?>> watchAuthState() => _remote
.watchAuthState()
.map<Either<AppFailure, UserEntity?>>((m) => Right(m?.toEntity()))
.catchFailures('watchAuthState');
@override
Future<Either<AppFailure, UserEntity>> signInWithGoogle() => _guard('signInWithGoogle', _remote.signInWithGoogle);
@override
Future<Either<AppFailure, UserEntity>> signInWithApple() => _guard('signInWithApple', _remote.signInWithApple);
@override
Future<Either<AppFailure, Unit>> deleteAccount() async {
if (!await _network.isConnected) return const Left(NetworkFailure()); // Decision Matrix: always gate
try {
await _remote.deleteAccount();
return const Right(unit);
} catch (e, s) {
return Left(mapException(e, s, 'deleteAccount')); // 'requires-recent-login' -> AuthFailure
}
}
@override
Future<Either<AppFailure, Unit>> signOut() async {
try {
await _remote.signOut();
return const Right(unit);
} catch (e, s) {
return Left(mapException(e, s, 'signOut'));
}
}
Future<Either<AppFailure, UserEntity>> _guard(String op, Future<UserModel> Function() call) async {
try {
return Right((await call()).toEntity());
} catch (e, s) {
return Left(mapException(e, s, op)); // CancelledException -> CancelledFailure (no SnackBar)
}
}
}
3. Complete AuthBloc (AuthStatus.unknown Splash Guard)
enum AuthStatus { unknown, authenticated, unauthenticated, loading, failure }
class AuthState extends Equatable {
const AuthState({
this.status = AuthStatus.unknown,
this.user,
this.verificationId,
this.failure,
});
final AuthStatus status;
final UserEntity? user;
final String? verificationId;
final AppFailure? failure;
AuthState copyWith({
AuthStatus? status,
UserEntity? Function()? user,
String? verificationId,
AppFailure? Function()? failure,
}) =>
AuthState(
status: status ?? this.status,
user: user != null ? user() : this.user,
verificationId: verificationId ?? this.verificationId,
failure: failure != null ? failure() : this.failure,
);
@override
List<Object?> get props => [status, user, verificationId, failure];
}
sealed class AuthEvent extends Equatable {
const AuthEvent();
@override
List<Object?> get props => [];
}
class AuthWatchStarted extends AuthEvent { const AuthWatchStarted(); }
class GoogleSignInRequested extends AuthEvent { const GoogleSignInRequested(); }
class AppleSignInRequested extends AuthEvent { const AppleSignInRequested(); }
class SignOutRequested extends AuthEvent { const SignOutRequested(); }
class DeleteAccountRequested extends AuthEvent { const DeleteAccountRequested(); }
@lazySingleton
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc(this._repo, this._fcm, this._reporter) : super(const AuthState()) {
on<AuthWatchStarted>(_onWatch);
on<GoogleSignInRequested>(_onGoogle);
on<AppleSignInRequested>(_onApple);
on<SignOutRequested>(_onSignOut);
on<DeleteAccountRequested>(_onDeleteAccount);
}
final AuthRepository _repo;
final FcmService _fcm;
final ErrorReporter _reporter;
Future<void> _onWatch(AuthWatchStarted _, Emitter<AuthState> emit) => emit.forEach(
_repo.watchAuthState(), // Stream<Either<AppFailure, UserEntity?>> mapped with catchFailures
onData: (result) => result.fold(
(f) => state.copyWith(status: AuthStatus.failure, failure: () => f),
(user) {
unawaited(_reporter.setUser(user?.id));
if (user != null) unawaited(_fcm.initialize(user.id)); // idempotent per uid
return user == null
? const AuthState(status: AuthStatus.unauthenticated)
: AuthState(status: AuthStatus.authenticated, user: user);
},
),
onError: (e, s) => state.copyWith(
status: AuthStatus.failure,
failure: () => const UnknownFailure('auth-stream'),
),
);
Future<void> _onGoogle(GoogleSignInRequested _, Emitter<AuthState> emit) async {
emit(state.copyWith(status: AuthStatus.loading, failure: () => null));
final res = await _repo.signInWithGoogle();
res.fold(
(f) => emit(state.copyWith(status: AuthStatus.failure, failure: () => f)),
(_) {},
);
}
Future<void> _onApple(AppleSignInRequested _, Emitter<AuthState> emit) async {
emit(state.copyWith(status: AuthStatus.loading, failure: () => null));
final res = await _repo.signInWithApple();
res.fold(
(f) => emit(state.copyWith(status: AuthStatus.failure, failure: () => f)),
(_) {},
);
}
Future<void> _onSignOut(SignOutRequested _, Emitter<AuthState> emit) async {
final uid = state.user?.id;
if (uid != null) await _fcm.removeToken(uid); // needs auth: run BEFORE signOut
_fcm.dispose();
await _repo.signOut(); // auth stream emits null -> unauthenticated
}
Future<void> _onDeleteAccount(DeleteAccountRequested _, Emitter<AuthState> emit) async {
// `user` is kept in state, so the router keeps the user on the current screen.
emit(state.copyWith(status: AuthStatus.loading, failure: () => null));
final res = await _repo.deleteAccount(); // requires network: repository gates on NetworkInfo
await res.fold(
// e.g. AuthFailure('requires-recent-login') -> UI re-authenticates and retries
(f) async => emit(state.copyWith(status: AuthStatus.failure, failure: () => f)),
(_) async {
_fcm.dispose();
await _fcm.deleteLocalToken(); // user doc + tokens are erased server-side
},
);
}
}
4. App Check (lib/core/firebase/app_check_setup.dart)
// firebase_app_check 0.5.x: provider objects (the old androidProvider/appleProvider/
// webProvider enum parameters were removed in 0.5.0).
Future<void> activateAppCheck() {
final dev = AppConfig.instance.isDev;
return FirebaseAppCheck.instance.activate(
providerAndroid: dev ? AndroidDebugProvider() : AndroidPlayIntegrityProvider(),
providerApple: dev ? AppleDebugProvider() : AppleAppAttestWithDeviceCheckFallbackProvider(),
providerWeb: ReCaptchaEnterpriseProvider(AppConfig.instance.recaptchaSiteKey),
);
}
5. Hardened Firestore & Storage Rules (firebase/firestore.rules, firebase/storage.rules)
// firebase/firestore.rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() { return request.auth != null; }
function isOwner(userId) { return isSignedIn() && request.auth.uid == userId; }
function isMember(data) { return isSignedIn() && request.auth.uid in data.memberIds; }
function boardData(boardId) { return get(/databases/$(database)/documents/boards/$(boardId)).data; }
function incoming() { return request.resource.data; }
function changed() { return incoming().diff(resource.data).affectedKeys(); }
function unchanged(fields) { return !changed().hasAny(fields); }
function onlyChanges(fields) { return changed().hasOnly(fields); }
function optString(d, k, max) { return !(k in d) || d[k] == null || (d[k] is string && d[k].size() <= max); }
function stampedNow(field) { return incoming()[field] == request.time; } // FieldValue.serverTimestamp()
// ---- users/{uid}: an ALLOW-LIST of client fields. Everything else (isPro, role, plan,
// boardCount, credits, ...) can only be written by the Admin SDK / Cloud Functions.
function userClientFields() {
return ['id', 'name', 'email', 'phone', 'photoUrl', 'username', 'lastSignIn',
'fcmTokens', 'notificationsEnabled', 'lastTokenUpdatedAt'];
}
function validUser(d) {
return optString(d, 'name', 100) && optString(d, 'email', 254) && optString(d, 'phone', 20)
&& optString(d, 'photoUrl', 2048) && optString(d, 'username', 30)
&& (!('fcmTokens' in d) || (d.fcmTokens is list && d.fcmTokens.size() <= 10))
&& (!('notificationsEnabled' in d) || d.notificationsEnabled is bool);
}
match /users/{userId} {
allow read: if isOwner(userId);
allow create: if isOwner(userId) && incoming().id == userId
&& incoming().keys().hasOnly(userClientFields()) && validUser(incoming());
// affectedKeys().hasOnly(): server-owned fields already in the doc stay untouched.
allow update: if isOwner(userId) && onlyChanges(userClientFields())
&& unchanged(['id']) && validUser(incoming());
allow delete: if false; // `cleanupDeletedUser` Cloud Function only
}
match /publicProfiles/{userId} {
allow get: if isSignedIn();
allow list: if false; // anti-scraping
allow create, update: if isOwner(userId) && incoming().keys().hasOnly(['name', 'photoUrl', 'username'])
&& optString(incoming(), 'name', 100) && optString(incoming(), 'photoUrl', 2048)
&& optString(incoming(), 'username', 30);
allow delete: if false;
}
function validBoard(d) {
return d.keys().hasOnly(['title', 'color', 'ownerId', 'memberIds', 'createdAt', 'updatedAt'])
&& d.title is string && d.title.size() >= 1 && d.title.size() <= 120
&& d.color is string && d.color.size() <= 16
&& d.memberIds is list && d.memberIds.size() <= 50 && d.ownerId in d.memberIds
&& d.createdAt is timestamp && d.updatedAt is timestamp;
}
match /boards/{boardId} {
allow read: if isMember(resource.data);
allow create: if isSignedIn() && incoming().ownerId == request.auth.uid
&& incoming().memberIds == [request.auth.uid]
&& stampedNow('createdAt') && stampedNow('updatedAt') && validBoard(incoming());
allow update: if isMember(resource.data) && unchanged(['ownerId', 'createdAt'])
&& (isOwner(resource.data.ownerId) || unchanged(['memberIds']))
&& stampedNow('updatedAt') && validBoard(incoming());
allow delete: if false; // `deleteBoardRecursive` callable (Admin SDK) only
function validCard(d) {
return d.keys().hasOnly(['title', 'description', 'position', 'assigneeId', 'createdAt', 'updatedAt'])
&& d.title is string && d.title.size() >= 1 && d.title.size() <= 200
&& optString(d, 'description', 5000)
&& d.position is number
&& (!('assigneeId' in d) || d.assigneeId == null || d.assigneeId in boardData(boardId).memberIds);
}
match /cards/{cardId} {
allow read: if isMember(boardData(boardId));
allow create: if isMember(boardData(boardId)) && stampedNow('createdAt') && stampedNow('updatedAt')
&& validCard(incoming());
allow update: if isMember(boardData(boardId)) && unchanged(['createdAt']) && stampedNow('updatedAt')
&& validCard(incoming());
allow delete: if isMember(boardData(boardId));
}
}
match /notifications/{notifId} {
allow read: if isOwner(resource.data.userId); // list queries must filter where('userId', '==', uid)
allow update: if isOwner(resource.data.userId) && onlyChanges(['isRead']) && incoming().isRead is bool;
allow create, delete: if false; // Cloud Functions only
}
}
}
// firebase/storage.rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
function isBoardMember(boardId) {
return request.auth != null
&& firestore.exists(/databases/(default)/documents/boards/$(boardId))
&& request.auth.uid in firestore.get(/databases/(default)/documents/boards/$(boardId)).data.memberIds;
}
match /boards/{boardId}/attachments/{fileName} {
allow read: if isBoardMember(boardId);
allow create, update: if isBoardMember(boardId)
&& request.resource.size < 10 * 1024 * 1024
&& request.resource.contentType.matches('image/(png|jpeg|webp|gif)|application/pdf');
allow delete: if isBoardMember(boardId);
}
match /users/{userId}/avatar.jpg {
allow read: if request.auth != null;
allow create, update: if request.auth != null && request.auth.uid == userId
&& request.resource.size < 5 * 1024 * 1024
&& request.resource.contentType.matches('image/(png|jpeg|webp)');
allow delete: if request.auth != null && request.auth.uid == userId;
}
match /{allPaths=**} { allow read, write: if false; }
}
}
6. Security Rules Automated Tests (firebase/tests/rules.test.ts)
Run with the emulator: firebase emulators:exec --only firestore "npx vitest run firebase/tests".
Every rule that blocks tampering gets a test that proves it — especially update paths, where most privilege escalations happen.
import { assertFails, assertSucceeds, initializeTestEnvironment, RulesTestEnvironment } from '@firebase/rules-unit-testing';
import { serverTimestamp, doc, setDoc, updateDoc, getDoc, getDocs, collection, addDoc, deleteDoc } from 'firebase/firestore';
import { readFileSync } from 'node:fs';
import { afterAll, beforeAll, beforeEach, describe, it } from 'vitest';
let env: RulesTestEnvironment;
beforeAll(async () => {
env = await initializeTestEnvironment({
projectId: 'demo-rules',
firestore: { rules: readFileSync('firebase/firestore.rules', 'utf8') },
});
});
afterAll(() => env.cleanup());
beforeEach(async () => {
await env.clearFirestore();
await env.withSecurityRulesDisabled(async (ctx) => {
const db = ctx.firestore();
await setDoc(doc(db, 'users/alice'), { id: 'alice', name: 'Alice', isPro: false });
await setDoc(doc(db, 'boards/b1'), {
title: 'Board', color: '#6366F1', ownerId: 'alice', memberIds: ['alice', 'bob'],
createdAt: new Date(), updatedAt: new Date(),
});
await setDoc(doc(db, 'notifications/n1'), { userId: 'alice', title: 'Hi', isRead: false });
});
});
const as = (uid: string) => env.authenticatedContext(uid).firestore();
describe('users/{uid}', () => {
it('allows creating an own profile with client fields only', async () => {
await assertSucceeds(setDoc(doc(as('carol'), 'users/carol'), { id: 'carol', name: 'Carol' }));
});
it('blocks privileged fields on create', async () => {
await assertFails(setDoc(doc(as('carol'), 'users/carol'), { id: 'carol', isPro: true }));
await assertFails(setDoc(doc(as('carol'), 'users/carol'), { id: 'carol', plan: 'enterprise' }));
});
it('blocks privilege escalation on update (isPro, role, plan, any unknown field)', async () => {
const db = as('alice');
for (const field of ['isPro', 'role', 'plan', 'boardCount', 'anythingElse']) {
await assertFails(updateDoc(doc(db, 'users/alice'), { [field]: true }));
}
});
it('allows updating client fields', async () => {
await assertSucceeds(updateDoc(doc(as('alice'), 'users/alice'), { name: 'Alice B.' }));
});
it('blocks oversized values and other users', async () => {
await assertFails(updateDoc(doc(as('alice'), 'users/alice'), { name: 'x'.repeat(101) }));
await assertFails(getDoc(doc(as('bob'), 'users/alice')));
await assertFails(deleteDoc(doc(as('alice'), 'users/alice')));
});
});
describe('publicProfiles', () => {
it('blocks listing (anti-scraping)', async () => {
await assertFails(getDocs(collection(as('alice'), 'publicProfiles')));
});
});
describe('boards', () => {
const board = (uid: string, memberIds: string[]) => ({
title: 'New', color: '#000000', ownerId: uid, memberIds,
createdAt: serverTimestamp(), updatedAt: serverTimestamp(),
});
it('allows creating an own board', async () => {
await assertSucceeds(setDoc(doc(as('alice'), 'boards/b2'), board('alice', ['alice'])));
});
it('blocks adding other members or a foreign owner on create', async () => {
await assertFails(setDoc(doc(as('alice'), 'boards/b3'), board('alice', ['alice', 'mallory'])));
await assertFails(setDoc(doc(as('mallory'), 'boards/b4'), board('alice', ['alice'])));
});
it('blocks non-members and ownership hijacking', async () => {
await assertFails(getDoc(doc(as('mallory'), 'boards/b1')));
await assertFails(updateDoc(doc(as('bob'), 'boards/b1'), { ownerId: 'bob', updatedAt: serverTimestamp() }));
await assertFails(updateDoc(doc(as('bob'), 'boards/b1'), { memberIds: ['alice', 'bob', 'mallory'], updatedAt: serverTimestamp() }));
});
it('blocks client-side board deletes (callable only)', async () => {
await assertFails(deleteDoc(doc(as('alice'), 'boards/b1')));
});
});
describe('notifications', () => {
it('blocks forged notifications and allows marking own as read', async () => {
await assertFails(addDoc(collection(as('alice'), 'notifications'), { userId: 'alice', title: 'fake' }));
await assertFails(updateDoc(doc(as('alice'), 'notifications/n1'), { title: 'edited' }));
await assertSucceeds(updateDoc(doc(as('alice'), 'notifications/n1'), { isRead: true }));
});
});
firebase/tests/package.json dev dependencies: @firebase/rules-unit-testing, firebase, vitest, typescript.
7. High-Sensitivity Apps (Fintech / Enterprise)
- Store local sensitive data only via
FlutterSecureStorage(neverSharedPreferences). - Restart the app process right after sign-out so the pending Firestore cache wipe runs immediately (shared devices).
- Add RASP / Root / Jailbreak / Frida detection (
freerasp) +FLAG_SECUREon sensitive screens. - Enforce App Check in Firebase Console on Auth, Firestore, Storage, AND Functions, and enable Email Enumeration Protection.
BLoC, Errors, Theme, Adaptive UI & RTL Localization (Complete Code)
1. Single-State BLoC + Events + UI (BoardsBloc)
enum BoardsStatus { initial, loading, success, failure }
class BoardsState extends Equatable {
const BoardsState({
this.status = BoardsStatus.initial,
this.boards = const [],
this.failure,
});
final BoardsStatus status;
final List<BoardEntity> boards;
final AppFailure? failure;
BoardsState copyWith({
BoardsStatus? status,
List<BoardEntity>? boards,
AppFailure? Function()? failure,
}) =>
BoardsState(
status: status ?? this.status,
boards: boards ?? this.boards,
failure: failure != null ? failure() : this.failure,
);
@override
List<Object?> get props => [status, boards, failure];
}
sealed class BoardsEvent extends Equatable {
const BoardsEvent();
@override
List<Object?> get props => [];
}
class WatchBoardsStarted extends BoardsEvent {
const WatchBoardsStarted(this.userId);
final String userId;
@override
List<Object?> get props => [userId];
}
class BoardsRefreshed extends BoardsEvent { const BoardsRefreshed(); }
class CreateBoardRequested extends BoardsEvent {
const CreateBoardRequested({required this.title, required this.color, required this.userId});
final String title, color, userId;
@override
List<Object?> get props => [title, color, userId];
}
class DeleteBoardRequested extends BoardsEvent {
const DeleteBoardRequested(this.boardId);
final String boardId;
@override
List<Object?> get props => [boardId];
}
// import 'package:bloc_concurrency/bloc_concurrency.dart';
@injectable
class BoardsBloc extends Bloc<BoardsEvent, BoardsState> {
BoardsBloc(this._watchBoards, this._createBoard, this._deleteBoard) : super(const BoardsState()) {
// restartable(): a new WatchBoardsStarted cancels the previous emit.forEach subscription.
// Without it, every refresh would add one more live Firestore listener (leak).
on<WatchBoardsStarted>(_onWatchStarted, transformer: restartable());
on<BoardsRefreshed>(_onRefreshed);
on<CreateBoardRequested>(_onCreateBoard);
on<DeleteBoardRequested>(_onDeleteBoard);
}
final WatchBoards _watchBoards;
final CreateBoard _createBoard;
final DeleteBoard _deleteBoard;
String? _userId;
Future<void> _onWatchStarted(WatchBoardsStarted e, Emitter<BoardsState> emit) async {
_userId = e.userId;
emit(state.copyWith(status: BoardsStatus.loading));
await emit.forEach(
_watchBoards(e.userId), // repository maps stream errors to Left(AppFailure)
onData: (result) => result.fold(
// boards are NOT cleared: a failed refresh keeps the last data on screen
(f) => state.copyWith(status: BoardsStatus.failure, failure: () => f),
(b) => state.copyWith(status: BoardsStatus.success, boards: b, failure: () => null),
),
// Safety net: never leave the UI stuck in `loading` if something unmapped escapes.
onError: (_, __) => state.copyWith(
status: BoardsStatus.failure,
failure: () => const UnknownFailure('watch-boards'),
),
);
}
// Re-dispatch instead of calling the handler directly: the event goes through
// the restartable() transformer, which cancels the old listener first.
void _onRefreshed(BoardsRefreshed _, Emitter<BoardsState> emit) {
final uid = _userId;
if (uid != null) add(WatchBoardsStarted(uid));
}
Future<void> _onCreateBoard(CreateBoardRequested e, Emitter<BoardsState> emit) async {
final res = await _createBoard(CreateBoardParams(title: e.title, color: e.color, userId: e.userId));
res.fold((f) => emit(state.copyWith(status: BoardsStatus.failure, failure: () => f)), (_) {});
}
Future<void> _onDeleteBoard(DeleteBoardRequested e, Emitter<BoardsState> emit) async {
final res = await _deleteBoard(e.boardId);
res.fold((f) => emit(state.copyWith(status: BoardsStatus.failure, failure: () => f)), (_) {});
}
}
// UI Usage (keep boards on screen if a refresh fails)
BlocConsumer<BoardsBloc, BoardsState>(
listenWhen: (p, c) =>
c.failure != null && p.failure != c.failure &&
c.boards.isNotEmpty && c.failure is! CancelledFailure,
listener: (context, s) => AppSnackBar.error(context, s.failure!.localize(context)),
builder: (context, s) => switch (s) {
BoardsState(status: BoardsStatus.loading, boards: []) => const AppShimmer(),
BoardsState(status: BoardsStatus.failure, boards: [], :final failure?) => ErrorView(
failure: failure,
onRetry: () => context.read<BoardsBloc>().add(const BoardsRefreshed()),
),
BoardsState(boards: []) => const AppEmptyState(),
BoardsState(:final boards) => BoardsGrid(boards: boards),
},
);
2. AppBlocObserver (lib/core/observers/app_bloc_observer.dart)
class AppBlocObserver extends BlocObserver {
@override
void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
super.onEvent(bloc, event);
AppLogger.info('EVENT: $event', tag: '${bloc.runtimeType}');
}
@override
void onTransition(Bloc<dynamic, dynamic> bloc, Transition<dynamic, dynamic> transition) {
super.onTransition(bloc, transition);
AppLogger.info(
'${transition.currentState.runtimeType} -> ${transition.nextState.runtimeType}',
tag: '${bloc.runtimeType}',
);
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
AppLogger.error('BLoC ${bloc.runtimeType}', error: error, stack: stackTrace);
unawaited(sl<ErrorReporter>().record(error, stackTrace, reason: 'BLoC ${bloc.runtimeType}'));
super.onError(bloc, error, stackTrace);
}
}
3. Complete Error Handling (failures.dart, exception_mapper.dart, failure_l10n.dart, error_reporter.dart, global_error_handlers.dart, app_logger.dart, error_view.dart, app_snack_bar.dart, friendly_error_widget.dart)
// failures.dart
sealed class AppFailure extends Equatable {
const AppFailure(this.message);
final String message;
@override
List<Object?> get props => [message];
}
final class NetworkFailure extends AppFailure { const NetworkFailure() : super('network'); }
final class PermissionFailure extends AppFailure { const PermissionFailure() : super('permission-denied'); }
final class NotFoundFailure extends AppFailure { const NotFoundFailure() : super('not-found'); }
final class CancelledFailure extends AppFailure { const CancelledFailure() : super('cancelled'); }
final class CacheFailure extends AppFailure { const CacheFailure(super.message); }
final class FirebaseFailure extends AppFailure { const FirebaseFailure(super.message); }
/// Validation carries a CODE, never display text: the UI localizes it.
enum ValidationCode { required, tooLong, invalidEmail, invalidPhone }
final class ValidationFailure extends AppFailure {
const ValidationFailure(this.code) : super('validation');
final ValidationCode code;
@override
List<Object?> get props => [message, code];
}
final class AuthFailure extends AppFailure {
const AuthFailure(this.code) : super('auth/$code');
final String code;
}
final class UnknownFailure extends AppFailure { const UnknownFailure(super.message); }
/// Thrown by datasources when the user dismisses a sign-in sheet; mapped to CancelledFailure.
final class CancelledException implements Exception { const CancelledException(); }
// app_logger.dart
abstract final class AppLogger {
static void info(String m, {String? tag}) { if (kDebugMode) debugPrint('[${tag ?? 'App'}] $m'); }
static void warning(String m) { if (kDebugMode) debugPrint('[Warning] $m'); }
static void error(String m, {Object? error, StackTrace? stack}) {
if (kDebugMode) debugPrint('[Error] $m: $error');
if (error != null) unawaited(sl<ErrorReporter>().record(error, stack, reason: m));
}
}
// error_reporter.dart
abstract interface class ErrorReporter {
Future<void> record(Object error, StackTrace? stack, {bool fatal = false, String? reason});
Future<void> recordFlutterError(FlutterErrorDetails details);
Future<void> setUser(String? uid);
Future<void> setKey(String key, Object value);
}
class CrashlyticsErrorReporter implements ErrorReporter {
final _c = FirebaseCrashlytics.instance;
@override Future<void> record(Object e, StackTrace? s, {bool fatal = false, String? reason}) => _c.recordError(e, s, fatal: fatal, reason: reason);
@override Future<void> recordFlutterError(FlutterErrorDetails d) => _c.recordFlutterFatalError(d);
@override Future<void> setUser(String? uid) => _c.setUserIdentifier(uid ?? '');
@override Future<void> setKey(String k, Object v) => _c.setCustomKey(k, v);
}
class WebErrorReporter implements ErrorReporter {
@override Future<void> record(Object e, StackTrace? s, {bool fatal = false, String? reason}) async => debugPrint('$reason $e\n$s');
@override Future<void> recordFlutterError(FlutterErrorDetails d) async => FlutterError.dumpErrorToConsole(d);
@override Future<void> setUser(String? uid) async {}
@override Future<void> setKey(String k, Object v) async {}
}
// global_error_handlers.dart
Future<void> installGlobalErrorHandlers(ErrorReporter reporter) async {
if (!kIsWeb) {
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(kReleaseMode && !AppConfig.instance.isDev);
}
FlutterError.onError = (details) {
FlutterError.presentError(details);
unawaited(reporter.recordFlutterError(details));
};
PlatformDispatcher.instance.onError = (error, stack) {
unawaited(reporter.record(error, stack, fatal: true));
return true;
};
if (!kIsWeb) {
Isolate.current.addErrorListener(RawReceivePort((List<dynamic> pair) {
unawaited(reporter.record(pair.first as Object, StackTrace.fromString(pair.last.toString()), fatal: true));
}).sendPort);
}
ErrorWidget.builder = (details) =>
kReleaseMode ? const FriendlyErrorWidget() : ErrorWidget(details.exception);
}
// exception_mapper.dart
extension FirebaseAuthExceptionX on FirebaseAuthException {
AppFailure toFailure() => switch (code) {
'invalid-credential' || 'wrong-password' || 'user-not-found' => const AuthFailure('invalid-credential'),
'network-request-failed' => const NetworkFailure(),
'web-context-cancelled' || 'popup-closed-by-user' => const CancelledFailure(),
_ => AuthFailure(code),
};
}
extension FirebaseExceptionX on FirebaseException {
AppFailure toFailure() => switch (code) {
'unavailable' || 'deadline-exceeded' => const NetworkFailure(),
'permission-denied' || 'unauthenticated' => const PermissionFailure(), // incl. callable Functions
'not-found' => const NotFoundFailure(),
_ => FirebaseFailure(message ?? code),
};
}
// failure_l10n.dart
extension AppFailureL10n on AppFailure {
String localize(BuildContext context) {
final l = AppLocalizations.of(context);
return switch (this) {
NetworkFailure() => l.errorNoInternet,
PermissionFailure() => l.errorNoPermission,
NotFoundFailure() => l.errorNotFound,
CancelledFailure() => '',
ValidationFailure(:final code) => switch (code) {
ValidationCode.required => l.validationRequired,
ValidationCode.tooLong => l.validationTooLong,
ValidationCode.invalidEmail => l.validationInvalidEmail,
ValidationCode.invalidPhone => l.validationInvalidPhone,
},
AuthFailure(:final code) => switch (code) {
'invalid-credential' => l.authInvalidCredential,
'email-already-in-use' => l.authEmailInUse,
'weak-password' => l.authWeakPassword,
'too-many-requests' => l.authTooManyRequests,
'user-disabled' => l.authUserDisabled,
'requires-recent-login' => l.authRequiresRecentLogin,
_ => l.errorGeneric,
},
FirebaseFailure() || CacheFailure() || UnknownFailure() => l.errorGeneric,
};
}
}
// error_view.dart
class ErrorView extends StatelessWidget {
const ErrorView({super.key, required this.failure, this.onRetry});
final AppFailure failure;
final VoidCallback? onRetry;
IconData get _icon => switch (failure) {
NetworkFailure() => Icons.wifi_off_rounded,
PermissionFailure() => Icons.lock_outline_rounded,
NotFoundFailure() => Icons.search_off_rounded,
_ => Icons.error_outline_rounded,
};
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final canRetry = onRetry != null && failure is! PermissionFailure && failure is! NotFoundFailure;
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Icon(_icon, size: 48, color: theme.colorScheme.onSurfaceVariant),
const SizedBox(height: 16),
Text(failure.localize(context), textAlign: TextAlign.center, style: theme.textTheme.bodyLarge),
if (canRetry) ...[
const SizedBox(height: 16),
FilledButton.tonalIcon(
onPressed: onRetry,
icon: const Icon(Icons.refresh_rounded),
label: Text(AppLocalizations.of(context).retry),
),
],
]),
),
);
}
}
// app_snack_bar.dart & friendly_error_widget.dart
abstract final class AppSnackBar {
static void error(BuildContext context, String message) => _show(
context, message, Theme.of(context).colorScheme.error, Theme.of(context).colorScheme.onError,
);
static void success(BuildContext context, String message) => _show(
context, message, Theme.of(context).colorScheme.primary, Theme.of(context).colorScheme.onPrimary,
);
static void _show(BuildContext context, String msg, Color bg, Color fg) {
if (msg.isEmpty) return;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(msg, style: TextStyle(color: fg)), backgroundColor: bg, behavior: SnackBarBehavior.floating));
}
}
class FriendlyErrorWidget extends StatelessWidget {
const FriendlyErrorWidget({super.key});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme; // falls back to the default theme above MaterialApp
return ColoredBox(
color: cs.surfaceContainerHighest,
child: Center(child: Icon(Icons.error_outline_rounded, size: 40, color: cs.onSurfaceVariant)),
);
}
}
4. Theme, Responsive Layouts & Localization (app_theme.dart, theme_cubit.dart, adaptive_scaffold.dart, locale_cubit.dart)
class AppTheme {
static const _primary = Color(0xFF6366F1);
static const _secondary = Color(0xFF818CF8);
static const _error = Color(0xFFEF4444);
static ThemeData get light => _build(const ColorScheme.light(
primary: _primary, secondary: _secondary, surface: Color(0xFFFFFFFF), error: _error,
));
static ThemeData get dark => _build(const ColorScheme.dark(
primary: _primary, secondary: _secondary, surface: Color(0xFF1A1D2E), error: _error,
));
static ThemeData _build(ColorScheme cs) => ThemeData(
useMaterial3: true,
colorScheme: cs,
appBarTheme: const AppBarTheme(elevation: 0, centerTitle: false),
cardTheme: CardThemeData(
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
);
}
@lazySingleton
class ThemeCubit extends Cubit<ThemeMode> {
ThemeCubit(this._prefs) : super(ThemeMode.values.elementAt(_prefs.getInt(_key) ?? 0));
static const _key = 'theme_mode';
final SharedPreferences _prefs;
Future<void> setMode(ThemeMode mode) async {
await _prefs.setInt(_key, mode.index);
emit(mode);
}
}
@lazySingleton
class LocaleCubit extends Cubit<Locale?> {
LocaleCubit(this._prefs) : super(_read(_prefs));
static const _key = 'locale_code';
final SharedPreferences _prefs;
static Locale? _read(SharedPreferences p) {
final code = p.getString(_key);
return code == null ? null : Locale(code);
}
Future<void> setLocale(Locale? locale) async {
if (locale == null) {
await _prefs.remove(_key);
} else {
await _prefs.setString(_key, locale.languageCode);
}
emit(locale);
}
}
class ResponsiveLayout extends StatelessWidget {
const ResponsiveLayout({super.key, required this.mobile, this.tablet, required this.desktop});
final Widget mobile, desktop;
final Widget? tablet;
@override
Widget build(BuildContext context) => LayoutBuilder(builder: (_, c) {
if (c.maxWidth >= 1024) return desktop;
if (c.maxWidth >= 600) return tablet ?? desktop;
return mobile;
});
}
class AdaptiveScaffold extends StatelessWidget {
const AdaptiveScaffold({
super.key,
required this.selectedIndex,
required this.onSelected,
required this.destinations,
required this.body,
});
final int selectedIndex;
final ValueChanged<int> onSelected;
final List<NavigationDestination> destinations;
final Widget body;
@override
Widget build(BuildContext context) {
final wide = MediaQuery.sizeOf(context).width >= 600;
return Scaffold(
body: wide
? Row(children: [
NavigationRail(
selectedIndex: selectedIndex,
onDestinationSelected: onSelected,
destinations: [
for (final d in destinations)
NavigationRailDestination(icon: d.icon, selectedIcon: d.selectedIcon, label: Text(d.label)),
],
),
const VerticalDivider(width: 1),
Expanded(child: body),
])
: body,
bottomNavigationBar: wide
? null
: NavigationBar(selectedIndex: selectedIndex, onDestinationSelected: onSelected, destinations: destinations),
);
}
}
- RTL Rule: ALWAYS use
EdgeInsetsDirectional,AlignmentDirectional,BorderRadiusDirectional, andIcons.arrow_back. NeverEdgeInsets.only(left: ...)orright: ....
Notifications, Cloud Functions & GoRouter Deep Links (Complete Code)
1. AndroidManifest & Channels (NotificationChannels, LocalNotificationService)
<!-- android/app/src/main/AndroidManifest.xml (inside <application>) -->
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="high_importance_channel" />
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_color" />
<!-- Inside <manifest> -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// lib/core/notifications/notification_channels.dart
class NotificationChannels {
static const highImportance = AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
description: 'Board assignments, mentions & urgent tasks',
importance: Importance.max,
playSound: true,
enableVibration: true,
);
static const low = AndroidNotificationChannel(
'low_channel',
'General Updates',
description: 'Comments, board updates & reminders',
importance: Importance.defaultImportance,
);
static Future<void> register(FlutterLocalNotificationsPlugin plugin) async {
final android = plugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
await android?.createNotificationChannel(highImportance);
await android?.createNotificationChannel(low);
}
}
// lib/core/notifications/local_notification_service.dart
@lazySingleton
class LocalNotificationService {
final _plugin = FlutterLocalNotificationsPlugin();
Future<void> init() async {
const initSettings = InitializationSettings(
android: AndroidInitializationSettings('@drawable/ic_notification'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
);
// flutter_local_notifications >= 20: named parameters
await _plugin.initialize(settings: initSettings, onDidReceiveNotificationResponse: _onTap);
await NotificationChannels.register(_plugin);
}
Future<void> show({
required int id,
required String title,
required String body,
String? payload,
bool highPriority = true,
}) async {
final channel = highPriority ? NotificationChannels.highImportance : NotificationChannels.low;
final details = NotificationDetails(
android: AndroidNotificationDetails(
channel.id, channel.name,
channelDescription: channel.description,
importance: channel.importance,
priority: Priority.high,
icon: '@drawable/ic_notification',
styleInformation: BigTextStyleInformation(body),
),
iOS: const DarwinNotificationDetails(presentAlert: true, presentBadge: true, presentSound: true),
);
await _plugin.show(id: id, title: title, body: body, notificationDetails: details, payload: payload);
}
void _onTap(NotificationResponse response) {
if (response.payload == null) return;
NotificationNavigator.navigateFromPayload(response.payload!);
}
}
2. Background Handler, App Widget & Complete FcmService
// lib/core/notifications/fcm_background.dart
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
debugPrint('BG message: ${message.messageId}');
}
// lib/app.dart
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
final _messengerKey = GlobalKey<ScaffoldMessengerState>();
late final StreamSubscription<AppFailure> _writeErrorSub;
late final AuthBloc _authBloc = sl<AuthBloc>();
late final FeatureFlagsCubit _flags = sl<FeatureFlagsCubit>();
late final ThemeCubit _themeCubit = sl<ThemeCubit>();
late final LocaleCubit _localeCubit = sl<LocaleCubit>();
late final ConnectivityCubit _connectivity = sl<ConnectivityCubit>();
late final GoRouter _router = createAppRouter(authBloc: _authBloc, flags: _flags);
@override
void initState() {
super.initState();
AppNavigator.router = _router;
_writeErrorSub = sl<WriteErrorBus>().stream.listen(_showWriteError);
unawaited(_openFromTerminatedNotification());
}
/// Offline-first writes rejected by the server (rules / App Check) surface here.
void _showWriteError(AppFailure failure) {
final messenger = _messengerKey.currentState;
final ctx = _messengerKey.currentContext;
if (messenger == null || ctx == null) return;
final cs = Theme.of(ctx).colorScheme;
messenger
..hideCurrentSnackBar()
..showSnackBar(SnackBar(
content: Text(AppLocalizations.of(ctx).errorWriteRejected, style: TextStyle(color: cs.onError)),
backgroundColor: cs.error,
behavior: SnackBarBehavior.floating,
));
}
@override
void dispose() {
unawaited(_writeErrorSub.cancel());
super.dispose();
}
Future<void> _openFromTerminatedNotification() async {
final message = await FirebaseMessaging.instance.getInitialMessage();
if (message == null || !mounted) return;
WidgetsBinding.instance.addPostFrameCallback(
(_) => NotificationNavigator.navigate(message.data),
);
}
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider.value(value: _authBloc),
BlocProvider.value(value: _flags),
BlocProvider.value(value: _themeCubit),
BlocProvider.value(value: _localeCubit),
BlocProvider.value(value: _connectivity),
],
child: BlocBuilder<ThemeCubit, ThemeMode>(
builder: (context, themeMode) => BlocBuilder<LocaleCubit, Locale?>(
builder: (context, locale) => MaterialApp.router(
title: AppConfig.instance.appName,
theme: AppTheme.light,
darkTheme: AppTheme.dark,
themeMode: themeMode,
locale: locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
routerConfig: _router,
scaffoldMessengerKey: _messengerKey,
builder: (context, child) {
final app = Column(children: [const OfflineBanner(), Expanded(child: child!)]);
return AppConfig.instance.isProd
? app
: Banner(
message: AppConfig.instance.isDev ? 'DEV' : 'STG',
location: BannerLocation.topEnd,
color: AppConfig.instance.isDev ? Colors.orange : Colors.purple,
child: app,
);
},
),
),
),
);
}
}
// lib/core/notifications/fcm_service.dart
@lazySingleton
class FcmService {
FcmService(this._messaging, this._firestore, this._local);
final FirebaseMessaging _messaging;
final FirebaseFirestore _firestore;
final LocalNotificationService _local;
StreamSubscription<String>? _tokenSub;
StreamSubscription<RemoteMessage>? _fgSub, _tapSub;
String? _activeUserId;
Future<void> initialize(String userId) async {
if (_activeUserId == userId) return;
dispose();
_activeUserId = userId;
if (!kIsWeb) await _local.init();
final settings = await _messaging.requestPermission(provisional: true);
AppLogger.info('FCM permission: ${settings.authorizationStatus}', tag: 'FCM');
if (settings.authorizationStatus == AuthorizationStatus.denied) {
await _firestore.collection('users').doc(userId).set(
{'notificationsEnabled': false},
SetOptions(merge: true),
);
return;
}
final token = await _messaging.getToken(
vapidKey: kIsWeb ? AppConfig.instance.webVapidKey : null,
);
if (token != null) await _saveToken(userId, token);
_tokenSub = _messaging.onTokenRefresh.listen(
(t) => _saveToken(userId, t),
onError: (Object e, StackTrace s) => AppLogger.error('Token refresh error', error: e, stack: s),
);
_fgSub = FirebaseMessaging.onMessage.listen(_handleForeground);
_tapSub = FirebaseMessaging.onMessageOpenedApp.listen((m) => NotificationNavigator.navigate(m.data));
}
Future<void> _handleForeground(RemoteMessage m) async {
final n = m.notification;
if (n == null || kIsWeb) return;
await _local.show(
id: (m.messageId ?? '${m.sentTime}').hashCode & 0x7fffffff, // stable 31-bit id
title: n.title ?? '',
body: n.body ?? '',
payload: jsonEncode(m.data),
highPriority: m.data['priority'] == 'high',
);
if (await AppBadgePlus.isSupported()) {
final current = await AppBadgePlus.getBadgeCount();
await AppBadgePlus.updateBadge(current + 1);
}
}
Future<void> _saveToken(String uid, String token) =>
_firestore.collection('users').doc(uid).set({
'fcmTokens': FieldValue.arrayUnion([token]),
'notificationsEnabled': true,
'lastTokenUpdatedAt': FieldValue.serverTimestamp(),
}, SetOptions(merge: true));
/// Call BEFORE signing out (the write needs auth). Best effort: never block sign-out.
Future<void> removeToken(String uid) async {
try {
final t = await _messaging.getToken(vapidKey: kIsWeb ? AppConfig.instance.webVapidKey : null);
if (t != null) {
await _firestore.collection('users').doc(uid).update({
'fcmTokens': FieldValue.arrayRemove([t]),
}).timeout(const Duration(seconds: 5));
}
} catch (e, s) {
AppLogger.error('removeToken failed', error: e, stack: s);
}
await deleteLocalToken();
}
/// After account deletion the user doc is gone; only invalidate the device token.
Future<void> deleteLocalToken() async {
try {
await _messaging.deleteToken();
} catch (e, s) {
AppLogger.error('deleteToken failed', error: e, stack: s);
}
}
Future<void> clearBadge() async {
if (!kIsWeb && await AppBadgePlus.isSupported()) await AppBadgePlus.updateBadge(0);
}
void dispose() {
unawaited(_tokenSub?.cancel());
unawaited(_fgSub?.cancel());
unawaited(_tapSub?.cancel());
_tokenSub = _fgSub = _tapSub = null;
_activeUserId = null;
}
}
// lib/core/notifications/notification_navigator.dart
abstract final class NotificationNavigator {
static void navigateFromPayload(String payload) {
try {
final decoded = jsonDecode(payload);
if (decoded is Map<String, dynamic>) navigate(decoded);
} catch (e, s) {
AppLogger.error('Invalid notification payload', error: e, stack: s);
}
}
static void navigate(Map<String, dynamic> data) {
final type = data['type'] as String?;
final id = data['id'] as String?;
final boardId = data['boardId'] as String?;
switch (type) {
case 'board_invite':
if (id != null) AppNavigator.go(RouteNames.boardPath(id));
case 'card_assigned' || 'comment_added':
if (boardId != null) AppNavigator.go(RouteNames.boardPath(boardId));
default:
AppNavigator.go(RouteNames.notifications);
}
}
}
3. NotificationsBloc & UnreadBadge
enum NotificationsStatus { initial, loading, success, failure }
class NotificationsState extends Equatable {
const NotificationsState({
this.status = NotificationsStatus.initial,
this.notifications = const [],
this.unreadCount = 0,
this.failure,
});
final NotificationsStatus status;
final List<NotificationEntity> notifications;
final int unreadCount;
final AppFailure? failure;
NotificationsState copyWith({
NotificationsStatus? status,
List<NotificationEntity>? notifications,
int? unreadCount,
AppFailure? Function()? failure,
}) =>
NotificationsState(
status: status ?? this.status,
notifications: notifications ?? this.notifications,
unreadCount: unreadCount ?? this.unreadCount,
failure: failure != null ? failure() : this.failure,
);
@override
List<Object?> get props => [status, notifications, unreadCount, failure];
}
// Badge UI
BlocBuilder<NotificationsBloc, NotificationsState>(
buildWhen: (p, c) => p.unreadCount != c.unreadCount,
builder: (_, s) => Badge(
isLabelVisible: s.unreadCount > 0,
label: Text(s.unreadCount > 99 ? '99+' : '${s.unreadCount}'),
child: const Icon(Icons.notifications_outlined),
),
);
4. Cloud Functions v2 (firebase/functions/src/*) + Web Service Worker
// web/firebase-messaging-sw.js (keep the SDK version in sync with Flutter web's Firebase JS SDK)
importScripts('https://www.gstatic.com/firebasejs/13.4.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/13.4.0/firebase-messaging-compat.js');
firebase.initializeApp({ apiKey: '...', projectId: '...', messagingSenderId: '...', appId: '...' });
firebase.messaging().onBackgroundMessage((p) => {
if (p.notification?.title) self.registration.showNotification(p.notification.title, { body: p.notification.body, data: p.data });
});
// firebase/functions/src/index.ts — firebase-functions ^7.4 (2nd gen) + firebase-admin ^14.5 (modular API)
import { initializeApp } from 'firebase-admin/app';
import { getFirestore, FieldValue } from 'firebase-admin/firestore';
import { getMessaging } from 'firebase-admin/messaging';
import { getStorage } from 'firebase-admin/storage';
import { onCall, HttpsError } from 'firebase-functions/https';
import { onDocumentWritten } from 'firebase-functions/firestore';
import { onUserDeleted } from 'firebase-functions/identity';
import { logger } from 'firebase-functions';
initializeApp();
const db = getFirestore();
// Called by BoardsRemoteDatasource.deleteBoard (client batches can't see uncached sub-docs offline).
export const deleteBoardRecursive = onCall({ enforceAppCheck: true }, async (req) => {
const uid = req.auth?.uid;
const boardId = req.data?.boardId;
if (!uid) throw new HttpsError('unauthenticated', 'Sign in required');
if (typeof boardId !== 'string' || boardId.length === 0 || boardId.length > 128) {
throw new HttpsError('invalid-argument', 'boardId required');
}
const ref = db.collection('boards').doc(boardId);
const snap = await ref.get();
if (!snap.exists || snap.get('ownerId') !== uid) {
throw new HttpsError('permission-denied', 'Owner only');
}
await db.recursiveDelete(ref);
await getStorage().bucket().deleteFiles({ prefix: `boards/${boardId}/` });
return { deleted: true };
});
// Account deletion (App Store 5.1.1(v) / Google Play data-deletion policy): erase everything
// the user owns when `user.delete()` succeeds on the client.
export const cleanupDeletedUser = onUserDeleted({}, async (event) => {
const uid = event.data.uid;
const bulk = db.bulkWriter();
// 1. Boards the user owns: delete recursively (cards, activity, attachments).
const owned = await db.collection('boards').where('ownerId', '==', uid).get();
for (const board of owned.docs) {
await db.recursiveDelete(board.ref, bulk);
await getStorage().bucket().deleteFiles({ prefix: `boards/${board.id}/` });
}
// 2. Boards shared with the user: remove membership only.
const shared = await db.collection('boards').where('memberIds', 'array-contains', uid).get();
for (const board of shared.docs) {
if (board.get('ownerId') !== uid) bulk.update(board.ref, { memberIds: FieldValue.arrayRemove(uid) });
}
// 3. Personal documents.
const notifs = await db.collection('notifications').where('userId', '==', uid).get();
notifs.docs.forEach((d) => bulk.delete(d.ref));
bulk.delete(db.doc(`publicProfiles/${uid}`));
bulk.delete(db.doc(`users/${uid}`));
await bulk.close();
await getStorage().bucket().deleteFiles({ prefix: `users/${uid}/` });
logger.info('User data erased', { uid, ownedBoards: owned.size });
});
export const onCardAssigned = onDocumentWritten('boards/{boardId}/cards/{cardId}', async (event) => {
const before = event.data?.before.data();
const after = event.data?.after.data();
if (!after || !after.assigneeId || before?.assigneeId === after.assigneeId) return;
const assigneeId = after.assigneeId as string;
const { boardId, cardId } = event.params;
const title = 'New card assigned to you';
const body = typeof after.title === 'string' ? after.title : 'You have a new task';
const data = { type: 'card_assigned', id: cardId, boardId }; // FCM data values must be strings
await db.collection('notifications').add({
userId: assigneeId, title, body, data, isRead: false, createdAt: FieldValue.serverTimestamp(),
});
const userDoc = await db.collection('users').doc(assigneeId).get();
const tokens: string[] = userDoc.get('fcmTokens') ?? [];
if (!tokens.length) return;
const res = await getMessaging().sendEachForMulticast({
tokens,
notification: { title, body },
data,
android: { priority: 'high', notification: { channelId: 'high_importance_channel', priority: 'max', sound: 'default' } },
apns: { payload: { aps: { sound: 'default', badge: 1, contentAvailable: true } } },
});
const stale = res.responses
.map((r, i) => ({ r, t: tokens[i] }))
.filter(({ r }) => !r.success && ['messaging/registration-token-not-registered', 'messaging/invalid-registration-token'].includes(r.error?.code ?? ''))
.map(({ t }) => t);
if (stale.length) await userDoc.ref.update({ fcmTokens: FieldValue.arrayRemove(...stale) });
});
// Do NOT fan out private board updates through FCM topics: any client can subscribe to
// any topic name. Send to the members' tokens (as above) instead.
5. Complete GoRouter (app_router.dart, route_names.dart, stream_listenable.dart, app_navigator.dart) + Universal/App Links
// route_names.dart
abstract final class RouteNames {
static const splash = '/splash';
static const onboarding = '/onboarding';
static const welcome = '/auth/welcome';
static const phoneLogin = '/auth/phone';
static const otp = '/auth/otp';
static const emailLogin = '/auth/email';
static const home = '/home';
static const board = '/board/:id';
static const notifications = '/notifications';
static const maintenance = '/maintenance';
static const updateRequired = '/update-required';
static const authPrefix = '/auth';
static String boardPath(String id) => '/board/$id';
}
// stream_listenable.dart & app_navigator.dart
class StreamListenable extends ChangeNotifier {
StreamListenable(Stream<dynamic> stream) { _sub = stream.listen((_) => notifyListeners()); }
late final StreamSubscription<dynamic> _sub;
@override
void dispose() { unawaited(_sub.cancel()); super.dispose(); }
}
abstract final class AppNavigator {
static late GoRouter router;
static void go(String location) => router.go(location);
}
// app_router.dart
GoRouter createAppRouter({required AuthBloc authBloc, required FeatureFlagsCubit flags}) {
return GoRouter(
initialLocation: RouteNames.splash,
refreshListenable: Listenable.merge([StreamListenable(authBloc.stream), StreamListenable(flags.stream)]),
redirect: (context, state) {
final loc = state.matchedLocation;
// Keep the original deep link (notification / universal link) through splash & login.
String withFrom(String target) {
final from = state.uri.queryParameters['from'] ??
(_isPublic(loc) ? null : state.uri.toString());
return from == null ? target : Uri(path: target, queryParameters: {'from': from}).toString();
}
final f = flags.state;
if (f.maintenanceMode) return loc == RouteNames.maintenance ? null : RouteNames.maintenance;
if (isBelowMinVersion(f.minSupportedVersion)) {
return loc == RouteNames.updateRequired ? null : RouteNames.updateRequired;
}
if (loc == RouteNames.maintenance || loc == RouteNames.updateRequired) return RouteNames.splash;
final authState = authBloc.state;
if (authState.status == AuthStatus.unknown) {
return loc == RouteNames.splash ? null : withFrom(RouteNames.splash);
}
// `user != null`, not `status == authenticated`: loading/failure states during
// delete-account or re-auth keep the user, so they must not bounce to welcome.
final isAuth = authState.user != null;
final onAuthRoute = loc.startsWith(RouteNames.authPrefix);
if (!isAuth) return onAuthRoute ? null : withFrom(RouteNames.welcome);
if (authState.user!.needsOnboarding) {
return loc == RouteNames.onboarding ? null : withFrom(RouteNames.onboarding);
}
if (loc == RouteNames.splash || onAuthRoute || loc == RouteNames.onboarding) {
return _safeFrom(state.uri.queryParameters['from']) ?? RouteNames.home;
}
return null;
},
routes: [
GoRoute(path: RouteNames.splash, builder: (_, __) => const SplashPage()),
GoRoute(path: RouteNames.onboarding, builder: (_, __) => const OnboardingPage()),
GoRoute(path: RouteNames.welcome, builder: (_, __) => const WelcomePage()),
GoRoute(path: RouteNames.phoneLogin, builder: (_, __) => const PhoneLoginPage()),
GoRoute(path: RouteNames.otp, builder: (_, __) => const OtpPage()),
GoRoute(path: RouteNames.emailLogin, builder: (_, __) => const EmailLoginPage()),
GoRoute(path: RouteNames.home, builder: (_, __) => const HomePage()),
GoRoute(path: RouteNames.board, builder: (_, s) => BoardPage(boardId: s.pathParameters['id']!)),
GoRoute(path: RouteNames.notifications, builder: (_, __) => const NotificationsPage()),
GoRoute(path: RouteNames.maintenance, builder: (_, __) => const MaintenancePage()),
GoRoute(path: RouteNames.updateRequired, builder: (_, __) => const UpdateRequiredPage()),
],
);
}
bool _isPublic(String loc) =>
loc == RouteNames.splash || loc == RouteNames.onboarding || loc.startsWith(RouteNames.authPrefix) ||
loc == RouteNames.maintenance || loc == RouteNames.updateRequired;
/// Only same-app relative paths: blocks open redirects like `?from=https://evil.com`.
String? _safeFrom(String? from) {
if (from == null || !from.startsWith('/') || from.startsWith('//')) return null;
return _isPublic(Uri.parse(from).path) ? null : from;
}
- Universal Links / App Links: Place
public/.well-known/assetlinks.json(Android SHA-256) andpublic/.well-known/apple-app-site-association(iOS Team ID +/board/*), and enableFlutterDeepLinkingEnabled = trueinios/Runner/Info.plist.
Flavors, Performance, Remote Config, CI/CD & Testing (Complete Code)
1. Flavors, AppConfig & bootstrap.dart
// lib/app_config.dart
enum AppFlavor { dev, staging, prod }
class AppConfig {
const AppConfig._(this.flavor, this.appName, this.firebaseOptions, this.webVapidKey, this.recaptchaSiteKey,
[this.googleServerClientId]);
final AppFlavor flavor;
final String appName, webVapidKey, recaptchaSiteKey; // public identifiers, NOT secrets
final FirebaseOptions firebaseOptions;
/// Web OAuth client ID for google_sign_in 7.x. Null on Android = read from google-services.json.
final String? googleServerClientId;
static late final AppConfig instance;
static void init(AppFlavor flavor) => instance = switch (flavor) {
AppFlavor.dev => AppConfig._(flavor, 'MyApp DEV', dev.DefaultFirebaseOptions.currentPlatform, 'DEV_VAPID_KEY', 'DEV_RECAPTCHA_SITE_KEY'),
AppFlavor.staging => AppConfig._(flavor, 'MyApp STG', staging.DefaultFirebaseOptions.currentPlatform, 'STG_VAPID_KEY', 'STG_RECAPTCHA_SITE_KEY'),
AppFlavor.prod => AppConfig._(flavor, 'MyApp', prod.DefaultFirebaseOptions.currentPlatform, 'PROD_VAPID_KEY', 'PROD_RECAPTCHA_SITE_KEY'),
};
bool get isDev => flavor == AppFlavor.dev;
bool get isStaging => flavor == AppFlavor.staging;
bool get isProd => flavor == AppFlavor.prod;
}
// lib/main_dev.dart / main_staging.dart / main_prod.dart
void main() { AppConfig.init(AppFlavor.dev); unawaited(bootstrap()); }
// lib/bootstrap.dart
Future<void> bootstrap() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: AppConfig.instance.firebaseOptions);
await activateAppCheck();
final ErrorReporter reporter = kIsWeb ? WebErrorReporter() : CrashlyticsErrorReporter();
sl.registerSingleton<ErrorReporter>(reporter);
await installGlobalErrorHandlers(reporter);
await configureFirestore(); // runs a pending sign-out cache wipe, then sets persistence
await configureDependencies();
await sl<RemoteConfigService>().init();
await sl<PerfService>().init();
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
Bloc.observer = AppBlocObserver();
sl<AuthBloc>().add(const AuthWatchStarted());
runApp(const App());
}
// android/app/build.gradle.kts (flavors + CI release signing)
import java.util.Properties
val keystoreProps = Properties().apply {
val f = rootProject.file("key.properties")
if (f.exists()) f.inputStream().use { load(it) }
}
android {
signingConfigs {
create("release") {
if (keystoreProps.isNotEmpty()) {
storeFile = file(keystoreProps.getProperty("storeFile"))
storePassword = keystoreProps.getProperty("storePassword")
keyAlias = keystoreProps.getProperty("keyAlias")
keyPassword = keystoreProps.getProperty("keyPassword")
}
}
}
buildTypes {
release {
signingConfig = if (keystoreProps.isNotEmpty()) signingConfigs.getByName("release") else signingConfigs.getByName("debug")
}
}
flavorDimensions += "env"
productFlavors {
create("dev") { dimension = "env"; applicationIdSuffix = ".dev"; versionNameSuffix = "-dev"; resValue("string", "app_name", "MyApp DEV") }
create("staging") { dimension = "env"; applicationIdSuffix = ".stg"; versionNameSuffix = "-stg"; resValue("string", "app_name", "MyApp STG") }
create("prod") { dimension = "env"; resValue("string", "app_name", "MyApp") }
}
}
iOS Xcode Setup (6 Steps)
| Step | Action |
|---|---|
| 1. Build configurations | Duplicate Debug/Release/Profile as Debug-dev, Release-dev, Profile-dev (same for -staging, -prod). Flutter requires the -flavor suffix. |
| 2. Schemes | Create shared schemes named dev, staging, prod pointing to their matching configurations. |
| 3. Bundle ID | Set PRODUCT_BUNDLE_IDENTIFIER per config (com.example.myapp.dev, .stg, com.example.myapp). |
| 4. Display name | Add FLAVOR_APP_NAME user-defined setting and set CFBundleDisplayName = $(FLAVOR_APP_NAME) in Info.plist. |
5. GoogleService-Info.plist |
Let flutterfire configure --ios-build-config install the per-flavor copy script. |
| 6. Push (APNs) | Upload an APNs .p8 key to each Firebase project (dev, staging, prod). |
flutterfire configure, Launcher Icons & .vscode/launch.json
# Run once per flavor & Xcode build config (repeat for Release-dev, Profile-dev, staging, prod)
flutterfire configure \
--project=your-app-dev \
--out=lib/firebase_options_dev.dart \
--platforms=android,ios,web \
--android-package-name=com.example.myapp.dev \
--android-out=android/app/src/dev/google-services.json \
--ios-bundle-id=com.example.myapp.dev \
--ios-build-config=Debug-dev \
--ios-out=ios/flavors/dev/GoogleService-Info.plist
# Run / Release commands
flutter run --flavor dev -t lib/main_dev.dart
flutter run -d chrome -t lib/main_dev.dart # Web uses -t without --flavor
flutter build appbundle --flavor prod -t lib/main_prod.dart --obfuscate --split-debug-info=build/symbols
flutter build ipa --flavor prod -t lib/main_prod.dart --obfuscate --split-debug-info=build/symbols
flutter build web -t lib/main_prod.dart --release
# flutter_launcher_icons-dev.yaml (repeat for -staging.yaml and -prod.yaml)
flutter_launcher_icons:
android: true
ios: true
image_path: "assets/icons/icon_dev.png"
# Generate all: dart run flutter_launcher_icons
// .vscode/launch.json
{
"configurations": [
{ "name": "dev", "request": "launch", "type": "dart", "program": "lib/main_dev.dart", "args": ["--flavor", "dev"] },
{ "name": "staging", "request": "launch", "type": "dart", "program": "lib/main_staging.dart", "args": ["--flavor", "staging"] },
{ "name": "prod", "request": "launch", "type": "dart", "program": "lib/main_prod.dart", "args": ["--flavor", "prod"] },
{ "name": "web dev", "request": "launch", "type": "dart", "program": "lib/main_dev.dart", "deviceId": "chrome" }
]
}
2. Performance (PerfService + PerfInterceptor)
// lib/core/performance/perf_service.dart
@lazySingleton
class PerfService {
PerfService(this._perf);
final FirebasePerformance _perf;
Future<void> init() => _perf.setPerformanceCollectionEnabled(AppConfig.instance.isProd);
Future<T> trace<T>(String name, Future<T> Function() op, {Map<String, String> attributes = const {}}) async {
final t = _perf.newTrace(name);
attributes.forEach(t.putAttribute);
await t.start();
try {
final result = await op();
t.putAttribute('result', 'ok');
return result;
} catch (_) {
t.putAttribute('result', 'error');
rethrow;
} finally {
await t.stop();
}
}
Trace start(String name) => _perf.newTrace(name)..start();
}
// lib/core/network/perf_interceptor.dart
class PerfInterceptor extends Interceptor {
final _metrics = <RequestOptions, HttpMetric>{};
@override
Future<void> onRequest(RequestOptions o, RequestInterceptorHandler h) async {
if (!kIsWeb) {
final url = '${o.uri.origin}${o.uri.path}'; // never include query string / PII
final m = FirebasePerformance.instance.newHttpMetric(url, _method(o.method));
_metrics[o] = m;
await m.start();
}
h.next(o);
}
@override
Future<void> onResponse(Response<dynamic> r, ResponseInterceptorHandler h) async {
await _finish(r.requestOptions, r.statusCode, r.headers);
h.next(r);
}
@override
Future<void> onError(DioException e, ErrorInterceptorHandler h) async {
await _finish(e.requestOptions, e.response?.statusCode, e.response?.headers);
h.next(e);
}
Future<void> _finish(RequestOptions o, int? code, Headers? headers) async {
final m = _metrics.remove(o);
if (m == null) return;
m.httpResponseCode = code;
m.responseContentType = headers?.value(Headers.contentTypeHeader);
final len = headers?.value(Headers.contentLengthHeader);
if (len != null) m.responsePayloadSize = int.tryParse(len);
await m.stop();
}
HttpMethod _method(String m) => HttpMethod.values.firstWhere(
(v) => v.name.toUpperCase() == m.toUpperCase(),
orElse: () => HttpMethod.Get,
);
}
3. Remote Config (RcKeys, RemoteConfigService, FeatureFlagsCubit, VersionGate)
// lib/core/remote_config/rc_keys.dart
abstract final class RcKeys {
static const featureNewHome = 'feature_new_home_enabled';
static const maxItemsFree = 'limit_max_items_free';
static const maintenanceMode = 'ops_maintenance_mode';
static const minSupportedVersion = 'ops_min_supported_version';
static const onboardingVariant = 'exp_onboarding_variant';
}
// lib/core/remote_config/remote_config_service.dart
@lazySingleton
class RemoteConfigService {
RemoteConfigService(this._rc);
final FirebaseRemoteConfig _rc;
static const _defaults = <String, dynamic>{
RcKeys.featureNewHome: false,
RcKeys.maxItemsFree: 3,
RcKeys.maintenanceMode: false,
RcKeys.minSupportedVersion: '1.0.0',
RcKeys.onboardingVariant: 'control',
};
Future<void> init() async {
await _rc.setConfigSettings(RemoteConfigSettings(
fetchTimeout: const Duration(seconds: 10),
minimumFetchInterval: AppConfig.instance.isProd ? const Duration(hours: 1) : const Duration(minutes: 1),
));
await _rc.setDefaults(_defaults);
await _rc.activate();
unawaited(_rc.fetch().catchError((Object e) => AppLogger.warning('RC fetch failed: $e')));
}
Stream<Set<String>> get onUpdated => kIsWeb
? const Stream.empty()
: _rc.onConfigUpdated.asyncMap((u) async { await _rc.activate(); return u.updatedKeys; });
FeatureFlags snapshot() => FeatureFlags(
featureNewHome: _rc.getBool(RcKeys.featureNewHome),
maxItemsFree: _rc.getInt(RcKeys.maxItemsFree),
maintenanceMode: _rc.getBool(RcKeys.maintenanceMode),
minSupportedVersion: _rc.getString(RcKeys.minSupportedVersion),
onboardingVariant: _rc.getString(RcKeys.onboardingVariant),
);
}
// lib/core/remote_config/feature_flags_cubit.dart
@lazySingleton
class FeatureFlagsCubit extends Cubit<FeatureFlags> {
FeatureFlagsCubit(this._rc) : super(_rc.snapshot()) {
_sub = _rc.onUpdated.listen((keys) {
if (keys.any((k) => k.startsWith('ops_'))) emit(_rc.snapshot());
});
}
final RemoteConfigService _rc;
late final StreamSubscription<Set<String>> _sub;
@override
Future<void> close() async {
await _sub.cancel();
return super.close();
}
}
// lib/core/remote_config/version_gate.dart
bool isBelowMinVersion(String minSupported) {
final current = Version.parse(sl<PackageInfo>().version);
return current < Version.parse(minSupported);
}
// A/B Experiment + Goal Metric + PDPL Consent
Widget buildOnboarding(BuildContext context) {
final variant = context.select((FeatureFlagsCubit c) => c.state.onboardingVariant);
return switch (variant) {
'variant_a' => const OnboardingFlowA(),
_ => const OnboardingFlowControl(),
};
}
Future<void> logOnboardingGoal(Duration elapsed) => FirebaseAnalytics.instance.logEvent(
name: 'onboarding_completed',
parameters: {'seconds': elapsed.inSeconds},
);
// Honour user consent (e.g., KSA PDPL / GDPR) before analytics collection
Future<void> applyAnalyticsConsent({required bool granted}) async {
await FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(granted);
await FirebaseAnalytics.instance.setConsent(
analyticsStorageConsentGranted: granted,
adStorageConsentGranted: false,
);
}
- RC Security Rule: Never treat Remote Config flags (
limit_max_items_free) as security — enforce limits server-side in Cloud Functions / Security Rules. Only live-updateops_*keys; applyfeature_*on next cold launch.
4. Complete GitHub Actions CI/CD Workflows
# .github/workflows/ci.yml
name: CI
on:
push: { branches: [main] }
pull_request: {}
concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: true }
permissions: { contents: read }
jobs:
flutter:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- uses: subosito/flutter-action@v2
with: { channel: stable, flutter-version-file: .fvmrc, cache: true }
- run: flutter pub get
- run: flutter gen-l10n && dart run build_runner build --delete-conflicting-outputs
- run: dart format --output=none --set-exit-if-changed lib test
- run: flutter analyze
- run: flutter test --coverage
- run: flutter build web -t lib/main_dev.dart
rules:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6 # Firestore emulator needs a JRE
with: { distribution: temurin, java-version: "21" }
- uses: actions/setup-node@v7
with: { node-version: 22, cache: npm, cache-dependency-path: firebase/tests/package-lock.json }
- run: npm ci --prefix firebase/tests
- run: npx firebase-tools@latest emulators:exec --only firestore --project demo-rules "npx --prefix firebase/tests vitest run firebase/tests"
functions:
runs-on: ubuntu-latest
timeout-minutes: 10
defaults: { run: { working-directory: firebase/functions } }
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with: { node-version: 22, cache: npm, cache-dependency-path: firebase/functions/package-lock.json }
- run: npm ci && npm run build
# .github/workflows/deploy-web.yml
# PR previews build the STAGING flavor and deploy to the STAGING Firebase project, so a preview
# never reads or writes production data. Only pushes to main ship the prod build to prod.
name: Deploy Web
on:
pull_request: {}
push: { branches: [main] }
permissions: { contents: read, pull-requests: write, checks: write }
jobs:
hosting:
# Fork PRs get no secrets: skip them instead of failing.
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
environment: ${{ github.event_name == 'push' && 'production' || 'staging' }} # each env has its own SA secret
env:
SA: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }}
TARGET: ${{ github.event_name == 'push' && 'lib/main_prod.dart' || 'lib/main_staging.dart' }}
PROJECT: ${{ github.event_name == 'push' && 'your-prod-project-id' || 'your-staging-project-id' }}
steps:
- if: env.SA == ''
run: echo "::notice::FIREBASE_SERVICE_ACCOUNT not set — skipping"
- uses: actions/checkout@v7
if: env.SA != ''
- uses: subosito/flutter-action@v2
if: env.SA != ''
with: { channel: stable, flutter-version-file: .fvmrc, cache: true }
- if: env.SA != ''
run: flutter pub get && flutter gen-l10n && dart run build_runner build --delete-conflicting-outputs && flutter build web --release -t "$TARGET"
- uses: FirebaseExtended/action-hosting-deploy@v0
if: env.SA != ''
with:
repoToken: ${{ secrets.GITHUB_TOKEN }}
firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }}
projectId: ${{ env.PROJECT }}
channelId: ${{ github.event_name == 'push' && 'live' || '' }}
expires: 14d
# .github/workflows/deploy-firebase.yml
name: Deploy Firebase Backend
on:
push: { branches: [main], paths: ["firebase/**", "firebase.json"] }
permissions: { contents: read, id-token: write }
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with: { node-version: 22, cache: npm, cache-dependency-path: firebase/functions/package-lock.json }
- run: npm ci && npm run build
working-directory: firebase/functions
- uses: google-github-actions/auth@v3
with: { workload_identity_provider: ${{ vars.GCP_WIF_PROVIDER }}, service_account: ${{ vars.GCP_DEPLOY_SA }} }
- run: npx firebase-tools@latest deploy --only firestore,storage,functions --project your-project-id --force --non-interactive
# .github/workflows/release-android.yml
name: Release Android
on: { push: { tags: ["v*.*.*"] } }
permissions: { contents: read }
jobs:
android:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with: { distribution: temurin, java-version: "21" }
- uses: subosito/flutter-action@v2
with: { channel: stable, flutter-version-file: .fvmrc, cache: true }
- run: |
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
cat > android/key.properties <<EOF
storeFile=upload-keystore.jks
storePassword=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
EOF
- run: |
flutter pub get && flutter gen-l10n && dart run build_runner build --delete-conflicting-outputs
flutter build appbundle --release --flavor prod -t lib/main_prod.dart \
--build-name "${GITHUB_REF_NAME#v}" --build-number "${{ github.run_number }}" \
--obfuscate --split-debug-info=build/symbols
- if: vars.FIREBASE_ANDROID_APP_ID != ''
run: npx firebase-tools@latest crashlytics:symbols:upload --app=${{ vars.FIREBASE_ANDROID_APP_ID }} build/symbols
- uses: r0adkll/upload-google-play@v1
with:
serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
packageName: com.example.myapp
releaseFiles: build/app/outputs/bundle/prodRelease/app-prod-release.aab
tracks: internal
status: completed
mappingFile: build/app/outputs/mapping/prodRelease/mapping.txt
# .github/workflows/release-ios.yml
name: Release iOS
on: { push: { tags: ["v*.*.*"] } }
permissions: { contents: read }
jobs:
ios:
runs-on: macos-latest
environment: production
env: { ASC_KEY_ID: ${{ vars.APPSTORE_API_KEY_ID }}, ASC_ISSUER: ${{ vars.APPSTORE_ISSUER_ID }} }
steps:
- uses: actions/checkout@v7
- uses: subosito/flutter-action@v2
with: { channel: stable, flutter-version-file: .fvmrc, cache: true }
- run: |
mkdir -p ~/.appstoreconnect
echo "${{ secrets.APPSTORE_API_PRIVATE_KEY }}" > ~/.appstoreconnect/AuthKey.p8
- run: |
flutter pub get && flutter gen-l10n && dart run build_runner build --delete-conflicting-outputs
flutter build ios --release --no-codesign --flavor prod -t lib/main_prod.dart \
--build-name "${GITHUB_REF_NAME#v}" --build-number "${{ github.run_number }}" \
--obfuscate --split-debug-info=build/symbols
- run: |
AUTH="-allowProvisioningUpdates -authenticationKeyPath $HOME/.appstoreconnect/AuthKey.p8 -authenticationKeyID $ASC_KEY_ID -authenticationKeyIssuerID $ASC_ISSUER"
xcodebuild -workspace ios/Runner.xcworkspace -scheme prod -configuration Release-prod -destination 'generic/platform=iOS' -archivePath build/Runner.xcarchive archive $AUTH
xcodebuild -exportArchive -archivePath build/Runner.xcarchive -exportOptionsPlist ios/ExportOptions.plist -exportPath build/ipa $AUTH
- if: vars.FIREBASE_IOS_APP_ID != ''
run: npx firebase-tools@latest crashlytics:symbols:upload --app=${{ vars.FIREBASE_IOS_APP_ID }} build/symbols
- uses: apple-actions/upload-testflight-build@v5
with:
app-path: build/ipa/Runner.ipa
issuer-id: ${{ vars.APPSTORE_ISSUER_ID }}
api-key-id: ${{ vars.APPSTORE_API_KEY_ID }}
api-private-key: ${{ secrets.APPSTORE_API_PRIVATE_KEY }}
Required GitHub Environment Secrets & Variables (production / staging)
| Secret / Variable | Used By | Creation |
|---|---|---|
FIREBASE_SERVICE_ACCOUNT (secret, per environment) |
deploy-web.yml |
production env → prod project SA, staging env → staging project SA (firebase init hosting:github) |
GCP_WIF_PROVIDER, GCP_DEPLOY_SA (vars) |
deploy-firebase.yml |
GCP Workload Identity Federation bound to this GitHub repo (keyless) |
ANDROID_KEYSTORE_BASE64, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD |
release-android.yml |
keytool + base64 |
PLAY_SERVICE_ACCOUNT_JSON (secret) |
release-android.yml |
Play Console Release Manager service account |
APPSTORE_API_PRIVATE_KEY (secret), APPSTORE_API_KEY_ID, APPSTORE_ISSUER_ID (vars) |
release-ios.yml |
App Store Connect API Key (cloud-managed signing via templates/ExportOptions.plist — zero .p12 certs in secrets) |
FIREBASE_ANDROID_APP_ID, FIREBASE_IOS_APP_ID (vars) |
release-*.yml |
Used by firebase crashlytics:symbols:upload after --split-debug-info |
5. Complete Test Templates (Unit, BLoC, Widget, Integration)
// test/unit/boards/create_board_test.dart
class MockBoardsRepository extends Mock implements BoardsRepository {}
void main() {
late CreateBoard usecase;
late MockBoardsRepository mockRepo;
setUp(() {
mockRepo = MockBoardsRepository();
usecase = CreateBoard(mockRepo);
registerFallbackValue(const CreateBoardParams(title: 't', color: '#000', userId: 'u1'));
});
const params = CreateBoardParams(title: 'My Board', color: '#6366F1', userId: 'user-1');
test('returns BoardEntity on success', () async {
when(() => mockRepo.createBoard(params)).thenAnswer((_) async => const Right(tBoardEntity));
final result = await usecase(params);
expect(result, const Right(tBoardEntity));
verify(() => mockRepo.createBoard(params)).called(1);
});
test('returns failure unchanged', () async {
when(() => mockRepo.createBoard(params)).thenAnswer((_) async => const Left(PermissionFailure()));
expect(await usecase(params), const Left(PermissionFailure()));
});
}
// test/unit/boards/boards_bloc_test.dart
blocTest<BoardsBloc, BoardsState>(
'emits loading then success when WatchBoardsStarted succeeds',
build: () {
when(() => mockWatchBoards(any())).thenAnswer((_) => Stream.value(Right([tBoardEntity])));
return BoardsBloc(mockWatchBoards, mockCreateBoard, mockDeleteBoard);
},
act: (b) => b.add(const WatchBoardsStarted('user-1')),
expect: () => [
const BoardsState(status: BoardsStatus.loading),
BoardsState(status: BoardsStatus.success, boards: [tBoardEntity]),
],
);
blocTest<BoardsBloc, BoardsState>(
'keeps existing boards and exposes the failure when the stream fails',
build: () {
when(() => mockWatchBoards(any())).thenAnswer(
(_) => Stream<Either<AppFailure, List<BoardEntity>>>.fromIterable(
[Right([tBoardEntity]), const Left(PermissionFailure())],
),
);
return BoardsBloc(mockWatchBoards, mockCreateBoard, mockDeleteBoard);
},
act: (b) => b.add(const WatchBoardsStarted('user-1')),
expect: () => [
const BoardsState(status: BoardsStatus.loading),
BoardsState(status: BoardsStatus.success, boards: [tBoardEntity]),
BoardsState(status: BoardsStatus.failure, boards: [tBoardEntity], failure: const PermissionFailure()),
],
);
blocTest<BoardsBloc, BoardsState>(
'refresh re-subscribes exactly once (restartable)',
build: () {
when(() => mockWatchBoards(any())).thenAnswer((_) => Stream.value(Right([tBoardEntity])));
return BoardsBloc(mockWatchBoards, mockCreateBoard, mockDeleteBoard);
},
act: (b) async {
b.add(const WatchBoardsStarted('user-1'));
await Future<void>.delayed(Duration.zero);
b.add(const BoardsRefreshed());
},
verify: (_) => verify(() => mockWatchBoards('user-1')).called(2),
);
// test/widget/boards/home_page_test.dart
class MockBoardsBloc extends MockBloc<BoardsEvent, BoardsState> implements BoardsBloc {}
Future<void> pumpHome(WidgetTester tester, MockBoardsBloc bloc, BoardsState state) async {
whenListen(bloc, const Stream<BoardsState>.empty(), initialState: state);
await tester.pumpWidget(
BlocProvider<BoardsBloc>.value(
value: bloc,
child: const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: HomePage(),
),
),
);
}
// integration_test/boards_integration_test.dart
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
AppConfig.init(AppFlavor.dev);
await Firebase.initializeApp(options: AppConfig.instance.firebaseOptions);
FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
sl.registerSingleton<ErrorReporter>(WebErrorReporter());
await configureDependencies();
});
testWidgets('create board appears in home list', (tester) async {
await FirebaseAuth.instance.createUserWithEmailAndPassword(email: 'test@app.com', password: 'Password123!');
sl<AuthBloc>().add(const AuthWatchStarted());
await tester.pumpWidget(const App());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('create_board_fab')));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('board_title_field')), 'Sprint 1');
await tester.tap(find.byKey(const Key('submit_btn')));
await tester.pumpAndSettle();
expect(find.text('Sprint 1'), findsOneWidget);
});
}
Drop-In Templates
Copy these files into your project as described in the Canonical Project Layout.
.firebaserc
{
"projects": {
"dev": "your-app-dev",
"staging": "your-app-staging",
"prod": "your-app-prod"
}
}
analysis_options.yaml
include: package:very_good_analysis/analysis_options.yaml
analyzer:
exclude:
- "**/*.g.dart"
- "**/*.config.dart"
- "**/*.freezed.dart"
- "lib/l10n/generated/**"
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
invalid_annotation_target: ignore
missing_required_param: error
missing_return: error
linter:
rules:
public_member_api_docs: false
avoid_print: true
prefer_const_constructors: true
prefer_const_declarations: true
unawaited_futures: true
discarded_futures: true
use_build_context_synchronously: true
directives_ordering: true
app_ar.arb
{
"@@locale": "ar",
"appTitle": "لوحة المهام",
"offlineBanner": "أنت غير متصل بالإنترنت. ستتم مزامنة التغييرات تلقائياً.",
"retry": "إعادة المحاولة",
"errorNoInternet": "لا يوجد اتصال بالإنترنت. يرجى التحقق من الشبكة والمحاولة مرة أخرى.",
"errorNoPermission": "ليس لديك صلاحية لتنفيذ هذا الإجراء.",
"errorNotFound": "العنصر المطلوب غير موجود.",
"errorGeneric": "حدث خطأ غير متوقع. يرجى المحاولة مرة أخرى.",
"authInvalidCredential": "البريد الإلكتروني أو كلمة المرور غير صحيحة.",
"authEmailInUse": "يوجد حساب مسجل بهذا البريد الإلكتروني بالفعل.",
"authWeakPassword": "يرجى اختيار كلمة مرور أقوى.",
"authTooManyRequests": "تم إجراء محاولات كثيرة جداً. يرجى المحاولة لاحقاً.",
"authUserDisabled": "تم تعطيل هذا الحساب.",
"authRequiresRecentLogin": "لحماية حسابك، يرجى تسجيل الدخول مرة أخرى للمتابعة.",
"errorWriteRejected": "تعذّر حفظ آخر تعديل وتم التراجع عنه.",
"validationRequired": "هذا الحقل مطلوب.",
"validationTooLong": "النص طويل جداً.",
"validationInvalidEmail": "يرجى إدخال بريد إلكتروني صحيح.",
"validationInvalidPhone": "يرجى إدخال رقم هاتف صحيح."
}
app_en.arb
{
"@@locale": "en",
"appTitle": "TaskBoard",
"offlineBanner": "You are offline. Changes will sync automatically.",
"retry": "Retry",
"errorNoInternet": "No internet connection. Please check your network and try again.",
"errorNoPermission": "You do not have permission to perform this action.",
"errorNotFound": "The requested item was not found.",
"errorGeneric": "Something went wrong. Please try again.",
"authInvalidCredential": "Invalid email or password.",
"authEmailInUse": "An account already exists for this email.",
"authWeakPassword": "Please choose a stronger password.",
"authTooManyRequests": "Too many attempts. Please try again later.",
"authUserDisabled": "This account has been disabled.",
"authRequiresRecentLogin": "For your security, please sign in again to continue.",
"errorWriteRejected": "Your last change could not be saved and was undone.",
"validationRequired": "This field is required.",
"validationTooLong": "This text is too long.",
"validationInvalidEmail": "Please enter a valid email address.",
"validationInvalidPhone": "Please enter a valid phone number."
}
dependabot.yml
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: pub
directory: /
schedule:
interval: weekly
groups:
firebase:
patterns:
- "firebase_*"
- "cloud_*"
- package-ecosystem: npm
directory: /firebase/functions
schedule:
interval: weekly
ExportOptions.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>method</key><string>app-store-connect</string>
<key>signingStyle</key><string>automatic</string>
<key>teamID</key><string>YOUR_TEAM_ID</string>
<key>uploadSymbols</key><true/>
</dict>
</plist>
firebase.json
{
"firestore": {
"rules": "firebase/firestore.rules",
"indexes": "firebase/firestore.indexes.json"
},
"storage": {
"rules": "firebase/storage.rules"
},
"functions": [
{
"source": "firebase/functions",
"codebase": "default"
}
],
"hosting": {
"public": "build/web",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "**",
"headers": [
{
"key": "Content-Security-Policy",
"value": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval' https://www.gstatic.com https://apis.google.com https://www.google.com https://www.recaptcha.net; connect-src 'self' https://*.googleapis.com https://*.firebaseio.com wss://*.firebaseio.com https://*.cloudfunctions.net https://*.run.app https://www.google.com https://www.gstatic.com https://fonts.gstatic.com; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; frame-src https://*.firebaseapp.com https://accounts.google.com https://www.google.com https://www.recaptcha.net https://appleid.apple.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
},
{
"key": "Strict-Transport-Security",
"value": "max-age=31536000; includeSubDomains"
},
{
"key": "X-Frame-Options",
"value": "DENY"
},
{
"key": "X-Content-Type-Options",
"value": "nosniff"
},
{
"key": "Referrer-Policy",
"value": "strict-origin-when-cross-origin"
},
{
"key": "Permissions-Policy",
"value": "camera=(), microphone=(), geolocation=()"
}
]
},
{
"source": "firebase-messaging-sw.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
}
]
}
}
firestore.indexes.json
{
"indexes": [
{
"collectionGroup": "boards",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "memberIds", "arrayConfig": "CONTAINS" },
{ "fieldPath": "updatedAt", "order": "DESCENDING" }
]
}
],
"fieldOverrides": []
}
l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-dir: lib/l10n/generated
nullable-getter: false
pubspec.yaml
name: my_app
description: Production Flutter + Firebase + BLoC Application
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.12.0
flutter: ">=3.44.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
# Firebase (versions verified on pub.dev, Nov 2026)
firebase_core: ^5.2.0
firebase_auth: ^7.1.0
cloud_firestore: ^7.2.0
cloud_functions: ^7.1.0
firebase_messaging: ^17.1.0
firebase_storage: ^14.0.1
firebase_analytics: ^13.1.0
firebase_crashlytics: ^6.1.0
firebase_performance: ^0.12.1
firebase_remote_config: ^7.0.1
firebase_app_check: ^0.5.2
google_sign_in: ^7.2.0
sign_in_with_apple: ^8.2.0
# State & DI
flutter_bloc: ^9.1.1
bloc_concurrency: ^0.3.0
equatable: ^2.0.7
get_it: ^9.3.0
injectable: ^3.0.0
# Navigation, Functional & Streams
go_router: ^18.1.4
fpdart: ^1.2.0
rxdart: ^0.28.0
# Notifications & UI
flutter_local_notifications: ^23.0.3
app_badge_plus: ^1.4.0
cached_network_image: ^3.4.1
# Network, Storage & Utils
connectivity_plus: ^7.3.2
shared_preferences: ^2.5.6
flutter_secure_storage: ^11.2.0
dio: ^5.11.1
intl: any # pinned by flutter_localizations
crypto: ^3.0.6
package_info_plus: ^10.2.2
pub_semver: ^2.2.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
very_good_analysis: ^11.0.0
bloc_test: ^10.0.0
mocktail: ^1.0.4
fake_cloud_firestore: ^4.5.0
build_runner: ^2.17.1
injectable_generator: ^3.1.3
flutter:
generate: true
uses-material-design: true
How to Install & Use This Skill Anywhere
Copy the flutter-firebase-bloc/ folder (containing SKILL.md, references/, and templates/) into your preferred tool:
| IDE / Agent | Where to Place It | Notes |
|---|---|---|
| Claude Code | ~/.claude/skills/flutter-firebase-bloc/ (global) or .claude/skills/flutter-firebase-bloc/ (project) |
Automatically discovered via SKILL.md frontmatter |
| Cursor | .cursor/skills/flutter-firebase-bloc/ (or copy SKILL.md into .cursor/rules/flutter-firebase.mdc) |
Supports full references/ progressive loading |
| Windsurf | .windsurf/skills/flutter-firebase-bloc/ (or .windsurfrules) |
Point rules to read references/*.md on demand |
| GitHub Copilot (VS Code) | .github/copilot-instructions.md (paste SKILL.md) or .github/skills/flutter-firebase-bloc/ |
Keep references/ in .github/skills/flutter-firebase-bloc/references/ |
| OpenAI Codex CLI | ~/.codex/skills/flutter-firebase-bloc/ or project AGENTS.md |
Standard Agent Skills folder layout |
| Gemini CLI / Antigravity / AI Studio | ~/.gemini/skills/flutter-firebase-bloc/ or .agent/skills/flutter-firebase-bloc/ |
SKILL.md + references/ + templates/ |
| ChatGPT / Claude Web / Gemini Gem | Upload SKILL.md + references/*.md as Knowledge files, and paste SKILL.md into System Instructions |
Works in any chat UI without an IDE |