portal_platform library

Shared auth, API client, session management, config, deep-link routing, and offline-first sync for Portal apps.

Offline-first sync (Firebase-style)

The sync module provides a drop-in offline-first data layer. Reads and writes always hit a local cache first, then sync with the server in the background. Failed mutations are queued and replayed automatically when the device reconnects.

Quick start

1. Define a repository by extending SyncableRepository:

class RecipeRepository extends SyncableRepository<Recipe> {
  @override String get entityType  => 'recipe';
  @override String get cacheKey    => 'portal_recipe_recipes';
  @override String get apiBasePath => '$_baseUrl/recipes';
  @override Recipe fromJson(Map<String, dynamic> j) => Recipe.fromJson(j);
  @override Map<String, dynamic> toJson(Recipe r) => r.toJson();
  @override String getId(Recipe r) => r.id;
}

2. Wire up services in main() (order matters):

// 1. Connectivity monitor
await Get.putAsync(() => ConnectivityService().init());

// 2. Persistent operation queue
await Get.putAsync(() => SyncQueue().init());

// 3. Sync manager — register repos, then init
final syncManager = SyncManager();
syncManager.register(RecipeRepository());
syncManager.register(CookbookRepository());
await Get.putAsync(() => syncManager.init());

3. Use the repository — same CRUD interface, now offline-aware:

final repo = RecipeRepository();
final recipes = await repo.getAll();   // cache or server
await repo.save(myRecipe);             // instant local + queued push
await repo.delete(id);                 // instant local + queued push

Architecture overview

┌──────────────────────────────────────────────────────┐
│  ConnectivityService                                 │
│  Monitors network state, fires reconnect callbacks   │
└────────────────┬─────────────────────────────────────┘
                 │ offline → online
                 ▼
┌──────────────────────────────────────────────────────┐
│  SyncManager                                         │
│  Iterates registered repos and calls sync()          │
└────────────────┬─────────────────────────────────────┘
                 │ for each repo
                 ▼
┌──────────────────────────────────────────────────────┐
│  SyncableRepository<T>                               │
│  1. _pushPending()  →  replay queued ops to server   │
│  2. _pullFromServer() → GET all, merge into cache    │
└─────┬────────────────────────────┬───────────────────┘
      │                            │
      ▼                            ▼
┌────────────┐            ┌───────────────┐
│ SyncQueue  │            │ SharedPrefs   │
│ (pending   │            │ (local cache) │
│  ops)      │            │               │
└────────────┘            └───────────────┘

Key classes

Class Role
ConnectivityService Reactive isOnline flag + reconnect events
SyncQueue Persistent, deduplicated mutation queue
SyncOperation Data class for a single queued mutation
EntitySyncOutbox Typed outbox wrapper over SyncQueue
SyncMutation Interface for queued client mutations
SyncAfterWrite Enqueue + optional online push helper
BaseEntitySyncService Shared sync observables for batch sync
SyncableRepository Experimental — simple SharedPrefs CRUD only
Syncable Non-generic interface used by SyncManager
SyncManager Orchestrates startup & reconnect sync

For rich local stores with batch /sync endpoints (Portal Task tasks, habits, boards), use EntitySyncOutbox + BaseEntitySyncService instead of SyncableRepository.

Classes

ApiClient
API Client for backend communication. Base URL is provided at init from AppConfig.apiBaseUrl.
AppConfig
Immutable app configuration. Single source of truth for bootstrap and env-derived settings. Use AppConfig.fromEnv after dotenv.load() to build from .env; use copyWith for overrides (e.g. tests).
BackendReadinessResult
Result of ApiClient.checkBackendReadiness.
BaseEntitySyncService
Shared sync observables and connectivity guard for entity sync services.
ConnectivityService
Reactive network-connectivity monitor built on connectivity_plus.
DeepLinkEnv
Environment-driven deep link settings (read after dotenv.load in main).
DeepLinkRegistry
App-provided deep link resolution. Register in main() before handling links.
DeepLinkResolution
Result of mapping a path string to an app route location.
DeepLinkService
Subscribes to app / universal links and navigates via PortalNavigation.
DeviceSecurityBinding
Registers DeviceSecurityController for device-security features.
DeviceSecurityController
Manages app lock state and the device-security preference.
DeviceSecurityPreferences
Reads/writes the device-security toggle in the host app's GetStorage box.
DeviceSecurityReturnPath
Query-parameter helpers for device-security unlock → return navigation.
DeviceSecurityService
Wraps LocalAuthentication so apps can unlock with biometrics or device PIN.
EntitySyncOutbox<M extends SyncMutation>
Generic outbox over SyncQueue for a single entityType.
LocalUserAuth
Ensures a device-local Portal user exists via POST /auth/local.
LocalUserIdentity
Reads the OS username and machine identity for local Portal accounts.
PortalAccountMenuButton
App-bar avatar that opens settings.
PortalApiPaths
Builds module URLs from ApiClient.baseUrl (http://host:3000/api).
PortalAppsSection
The other Portal apps, installable from inside this one.
PortalAppVersion
Loads and caches PackageInfo for the host app.
PortalAppVersionText
Displays the host app's version string from platform package info.
PortalAuthBinding
Shared binding that lazily registers PortalAuthController. Use as-is in your app's route definitions.
PortalAuthConfig
Branding and feature configuration for the shared auth UI.
PortalAuthController
Shared authentication controller used by all Portal apps that use email/password auth. Handles login, registration, demo login, and optional server health-check.
PortalAuthMiddleware
Redirects unauthenticated users away from protected routes.
PortalAuthView
Shared authentication view for all Portal apps using email/password auth.
PortalAvatar
The signed-in user's photo, falling back to their initials.
PortalBootstrap
Registers shared platform services used by standalone Portal apps.
PortalChangePasswordForm
The change-password form, without a scaffold around it.
PortalChangePasswordPage
Change the password of the signed-in Portal account, on its own screen.
PortalDatabase
The one local SQLite database every Portal app writes through.
PortalDeviceSecurityGate
Overlays PortalDeviceSecurityLockView when device security is enabled and locked.
PortalDeviceSecurityLockView
Full-screen unlock UI shown when the app is locked.
PortalDeviceSecuritySettingsTile
Reusable settings row with a switch for device security.
PortalDeviceSecurityStrings
Localized copy for device-security UI. Host apps supply translated strings.
PortalErrorHandlers
PortalGetNavigation
PortalNavigation over GetX named routes, for apps on GetMaterialApp.
PortalGoogleSignInRegistry
Shared GoogleSignIn for Portal login and Google Drive vault.
PortalGuestOnlyMiddleware
Redirects authenticated users away from login-only routes.
PortalImageField
The one way a Portal form asks for an image.
PortalImagePickerSheet
The bottom sheet every Portal app uses to pick an image.
PortalImageResult
One photo returned by the server's Unsplash proxy.
PortalImageSearchService
Client for the server's cached Unsplash proxy.
PortalInstalledApp
What a sibling Portal app's installed build is, when it is installed.
PortalInstalledApps
The PackageManager questions the app list asks: what is installed, and please uninstall this.
PortalLogger
PortalMediaService
Uploads to the shared media store and hands back the URL to persist.
PortalNavigation
App-wide navigation facade (GoRouter, GetX, etc.).
PortalPaletteOption
One selectable palette, as the host app describes it.
PortalPasswordResetView
Request a reset code by email, then set a new password with that code.
PortalProfileTile
The signed-in profile: photo, name, email, and a tap to rename.
PortalRelease
One app's published build, as named in the manifest.
PortalSentry
Optional Sentry integration for Portal Flutter apps.
PortalSentryEnv
Dotenv keys used by PortalSentry. Values are read from each app's .env.
PortalServerPage
Dev/QA tool: point this app install at a different Portal server.
PortalServerPrefs
Persists a dev/QA override of which Portal API server this app install talks to, and the one-time gesture that reveals the setting.
PortalSettingsLabels
Every user-visible string on the shared settings page and its widgets.
PortalSettingsPage
The settings every Portal app has, in one page.
PortalSettingsSection
One group of rows on PortalSettingsPage.
PortalStatusSection
Server reachability and assistant availability, checked on demand.
PortalStatusTile
One "is this thing up" row: icon, name, detail, and a state dot.
PortalThemeController
The appearance choices every Portal app shares: light/dark/system, and an optional palette id for apps whose themes come from the UI kit registry.
PortalUpdateCheck
PortalUpdateManifest
The decoded updates.json.
PortalUpdateService
Checks for, downloads and hands off sideloaded APK updates.
PortalUpdateTile
The app version panel: what is installed, what is published, and when that was last checked. Tapping it checks again and offers the update.
PortalXp
The fleet's single XP ledger, client side.
SessionController
Holds the cached user profile from storage and refreshes after auth. Registered as permanent in main.dart.
Syncable
Non-generic interface used by SyncManager to trigger sync on repositories without caring about the entity type parameter.
SyncableRepository<T>
Abstract offline-first repository for simple entities stored in PortalDatabase.
SyncAfterWrite
Enqueues a mutation and triggers an online push when sync is enabled.
SyncFeedback
App-supplied feedback for the offline-first write path.
SyncManager
Central orchestrator that keeps all registered repositories in sync with the server.
SyncMutation
A client-side change queued for SyncQueue push.
SyncOperation
A single queued mutation that has not yet been pushed to the server.
SyncQueue
Persistent, deduplicated queue of mutations waiting to be pushed to the server.
SyncStatusBanner
TokenStorage
JWT and user profile storage (Android Keystore / iOS Keychain).
UserStorageScope
Prefixes storage keys with the signed-in user id so caches stay isolated.

Enums

DataStorageMode
Where task/habit/board entity payloads are persisted (build-time config).
PortalAppAction
What tapping an app row does.
PortalLogSeverity
PortalSettingsGroup
The groups this page can build for itself, in the order it builds them.
PortalStatusState
What one dependency looked like the last time it was asked.
PortalUpdateStatus
Why an update check produced no update. Surfaced so the UI can say "you're up to date" and "couldn't reach the server" differently.
SyncOperationType
The kind of mutation a SyncOperation represents.

Extensions

PortalUriNormalize on Uri
Collapses duplicate slashes in URI paths for HTTP requests.

Constants

kPortalUpdateSchema → const int
Manifest schema this client understands.

Functions

createPortalGoogleSignIn({required String webClientId, List<String> scopes = const ['email', 'profile']}) → GoogleSignIn
Creates GoogleSignIn using the GCP Web application OAuth client ID.
formatGbp(double amount) → String
formatGbpCompact(double amount) → String
formatTimeLeftTo(DateTime? payoff) → String
Human-readable countdown to payoff (exclusive of time-of-day).
isPermanentSyncFailure(Object error) → bool
True when error means "the server refused this change" rather than "the server was not reachable".
A link is usable if it parses as an absolute http(s) URL. Anything stricter (sniffing for a file extension) rejects the perfectly valid extensionless CDN URLs the photo proxy itself returns.
normalizeDeepLinkPath(String path) → String
Normalizes path to a leading /, no trailing slash (except /).
parseDataStorageMode(String? raw) → DataStorageMode
Parses DATA_STORAGE from dotenv. Defaults to DataStorageMode.server.
parseHexColor(String? hex) → Color?
Unsplash hands back a #rrggbb dominant colour; null when it is missing or malformed, so callers fall back to a theme surface.
parseMoneyInput(String s) → double?
parsePercentInput(String s) → double?
parseVersionCode(String buildNumber) → int?
Reads the running app's versionCode from a PackageInfo.buildNumber.
pathFromDeepLinkUri(Uri uri) → String
Extracts app path from a deep link uri (fragment ignored).
portalAppActionFor(PortalRelease release, PortalInstalledApp? installed) → PortalAppAction
What a row offers for release given the installed build, if any.
portalAppAvatar(PortalRelease release, Color color) → Widget
The app's own published launcher icon, falling back to the glyph.
portalAppIconFor(String slug) → IconData
Best-effort icon per app. An unknown slug still lists and still installs.
portalAppUri(String slug) → Uri
The scheme a Portal app answers on: portal-gym -> portal-gym://open.
portalAppVersionLine(PortalRelease release, PortalInstalledApp? installed) → String
v1.2.0 when it matches, v1.2.0 → v1.4.0 when the publish is ahead of what is installed. Size trails both; an app that is not installed shows the published version alone.
portalCanInstallApps(PortalUpdateService service) → bool
Whether this build can show and install sibling apps at all.
portalErrorMessage(Object error, {String? offlineHint}) → String
One line of copy a user can act on, for any error thrown by ApiClient.
portalFormatDate(DateTime at) → String
8 Sep 2026 in the device locale.
portalFormatSince(DateTime? at, {DateTime? now}) → String
2 hours ago, falling back to the absolute date once the gap stops being the useful way to read it.
portalImportTopImage(String query, {bool preferThumb = false, PortalImageSearchService? search, PortalMediaService? media}) → Future<String?>
Searches the photo library and stores our own copy of the top hit, returning its URL — or null when nothing matched.
portalInstallSyncFeedback({String? entityLabel(String entityType)?}) → void
Give the offline-first data layer a voice, in one call.
portalPromptForUpdateOnLaunch(BuildContext context, PortalUpdateService service) → Future<void>
One-shot launch check: prompts only when there is a newer build the user has not already refused.
shouldLog(PortalLogSeverity message, PortalLogSeverity minimum) → bool
showPortalPasswordReset(BuildContext context, {String? email}) → Future<void>
Opens the shared two-step password reset screen.
showPortalUpdateDialog(BuildContext context, PortalUpdateService service, PortalRelease release, {String? title, bool rememberRefusal = true}) → Future<bool>
Offers release, then downloads and installs it if the user accepts.

Typedefs

DeepLinkPathResolver = DeepLinkResolution? Function(String normalizedPath, {Map<String, String> queryParameters})
Resolves a normalized app path to a GetX route, or null if unknown.

Exceptions / Errors

ApiException
API Exception
PortalUpdateException