primekit 2.0.0
primekit: ^2.0.0 copied to clipboard
A modular Flutter toolkit — networking, auth, notifications, storage, Firebase adapters, Riverpod helpers, and more.
Changelog #
All notable changes to Primekit will be documented here.
Format follows Keep a Changelog. Versioning follows Semantic Versioning.
1.0.0 #
Breaking Changes #
ToastService,LoadingOverlay,SkeletonLoadernow respectPkUiThemeThemeExtension. AddPkUiTheme()to yourThemeData.extensionsto customise colors. Default colors are unchanged — no visual breaking change unless customised.
New Modules #
- Design System (
primekit/design_system.dart):PkSpacing,PkRadius,PkAvatar,PkBadge - Riverpod (
primekit/riverpod.dart):PkAsyncNotifierMixin,PkStreamNotifierMixin,PkPaginationNotifierMixin, ready-to-use providers - Calendar (
primekit/calendar.dart):CalendarService,CalendarProvider,CalendarEvent
Enhancements #
- Auth: Added
FirebaseAuthInterceptor— zero-config Firebase ID token injection - Notifications: Added
NotificationPreferences— per-user preference management - i18n: Added
CurrencyRateProvider,ExchangeRateApiProvider,CachedRateProvider - Sync: Added
PkSyncStatusenum withisOnline/hasErrorextensions - UI: Added
PkUiThemeThemeExtension — fully customisable component colors - Forms: Added
PkStringSchema.url(),.matches(),.noWhitespace(),.alphanumeric() - Forms: Added
PkNumberSchema.integer(),.positive(),.negative(),.multipleOf() - Forms: Added
PkObjectSchema.refine()for cross-field validation - Forms: Added
ValidationResult.firstErrorgetter - AsyncState: Fixed race condition in
AsyncStateNotifier.execute()
Bug Fixes #
ToastService: Removed hardcoded success/error colors (now viaPkUiTheme)AsyncStateNotifier: Added operation ID to prevent stale state updates
0.4.1 — 2026-03-05 #
Fixed #
- Bump
permission_handlerto^12.0.0(was^11.0.0) — fixes pub.dev lower-bound analysis failure due toPermission.calendarWriteOnlynot existing in 11.0.0, and unlocks latest stable (12.0.1). - Bump
google_sign_into^7.0.0(was'>=6.0.0 <8.0.0') — fixes pub.dev lower-bound analysis failure due toGoogleSignIn.instancenot existing in 6.x.
0.4.0 — 2026-03-04 #
Added #
primekit/notifications.dart — LocalNotifier (runtime permission API)
- Added
bool get hasPermission— reflects the last known permission state. - Added
Future<bool> checkPermission()— queries the OS for current permission status and updateshasPermission. - Added
Future<bool> requestPermission()— requests permission from the user; on iOS/macOS shows the system prompt, on Android 13+ requestsPOST_NOTIFICATIONS, on other platforms returns current state. - Implemented across all three platform branches:
local_notifier_io.dart(iOS viaIOSFlutterLocalNotificationsPlugin, macOS viaMacOSFlutterLocalNotificationsPlugin, Android viaAndroidFlutterLocalNotificationsPlugin),local_notifier_web.dart(browser Notification API), andlocal_notifier_stub.dart(returnsfalse).
primekit/notifications.dart — LocalNotifier now exported
LocalNotifieris now exported frompackage:primekit/notifications.dart.- Previously callers had to import
package:primekit/src/notifications/local_notifier.dart, which triggered theimplementation_importslint. - Fixed by re-exporting
local_notifier.dartwhich already uses conditional exports (dart.library.html/dart.library.io/ stub), making the re-export safe on all platforms.
primekit/notifications.dart — PushHandler fully implemented
- Wired
PushHandlerwith thefirebase_messagingSDK (^15.0.0), which is now a declared dependency. initialize()requests permission, subscribes toFirebaseMessaging.onMessageandFirebaseMessaging.onMessageOpenedApp, listens for token refreshes, and handles the initial message when the app launches from a terminated state.getToken()returnsFirebaseMessaging.instance.getToken().requestPermission()callsFirebaseMessaging.instance.requestPermission()and returnstruewhenauthorizationStatus == authorized.handleBackground()registers_firebaseBackgroundHandlerviaFirebaseMessaging.onBackgroundMessage().
0.3.0 — 2026-02-24 #
Changed — Breaking #
primekit/media.dart — ImageCompressor (all 6 platforms)
- Replaced
flutter_image_compresswith the pure-Dartimagepackage (^4.0.0), eliminating the native channel dependency and enabling full cross-platform compression. CompressFormat.webpnow falls back to JPEG (WebP encoding is not supported by theimagepackage; decoding still works).CompressFormat.heicfalls back to JPEG on all platforms (unchanged behaviour).maxWidth/maxHeightnow only downscale — images smaller than the target are left at their original size.
primekit/media.dart — ImageCropperService (all 6 platforms)
- Replaced
image_cropperwith the pure-Fluttercroppypackage (^1.4.1), which has no platform channel dependencies. - API change:
aspectRatioparameter type changed fromCropAspectRatio(image_cropper type) to a Dart record({int x, int y})?. Migration:CropAspectRatio(ratioX: 16, ratioY: 9)→(x: 16, y: 9). - Removed
presetsandcropStyleparameters (not supported by croppy's API). toolbarColoris now applied viaThemeData;toolbarTitleis accepted for API compatibility but not rendered (croppy uses its own chrome).ImageCropperServiceis now exported fromprimekit/media.dart(no longer requires a direct import).
primekit/permissions.dart — PermissionHelper / PermissionGate / PermissionFlow (all 6 platforms)
- Replaced
permission_handlerwithflutter_permission_handler_plus(^0.1.0), which declares full six-platform support. PkPermission.bluetooth,.phone, and.sensorshave no equivalent in the new SDK and are treated as granted on all platforms.PermissionHelper,PermissionGate, andPermissionFloware now exported fromprimekit/permissions.dart(no longer require direct imports).
primekit/background.dart — TaskScheduler (all 6 platforms)
- The barrel-export router now uses a new
task_scheduler_timer.dart(DartTimer-based) for thedart:iobranch instead oftask_scheduler_mobile.dart(WorkManager). TaskScheduler,ExistingWorkPolicy, andcallbackDispatcherare now exported fromprimekit/background.dart.- Android/iOS consumers who need true OS-managed background execution should import
task_scheduler_mobile.dartdirectly.
primekit/device.dart — BiometricAuth (all 6 platforms)
BiometricAuthis now exported fromprimekit/device.dartvia a newbiometric_auth_barrel.dartthat routes to the stub on all native platforms and to the WebAuthn implementation on Web.- Direct import of
biometric_auth.dart(→local_auth) still works for Android/iOS/macOS/Windows native biometrics.
Changed — Dependencies #
| Removed | Added |
|---|---|
permission_handler: ^12.0.1 |
flutter_permission_handler_plus: ^0.1.0 |
flutter_image_compress: ^2.3.0 |
image: ^4.0.0 |
image_cropper: ^11.0.0 |
croppy: ^1.4.1 |
0.2.1 — 2026-02-24 #
Changed #
- Full cross-platform support (Android · iOS · macOS · Windows · Linux · Web): removed platform-restricted packages from module barrels so every platform gets a clean import graph.
primekit/notifications.dart:LocalNotifierremoved from barrel (imports directly viaprimekit/src/notifications/local_notifier.dart;flutter_local_notificationshas Windows/Linux-only transitive sub-packages).primekit/permissions.dart:PermissionHelper,PermissionGate,PermissionFlowremoved from barrel (import directly;permission_handler 12.xdoes not declare macOS/Linux platform support).primekit/media.dart:ImageCompressor,ImageCropperServiceremoved from barrel (import directly;flutter_image_compresshas no Windows/Linux support,image_cropperpulls indart:iowhich blocks Web).primekit/device.dart:BiometricAuthremoved from barrel (import directly;local_authhas no Linux support).primekit/background.dart:TaskSchedulerremoved from barrel (import directly;workmanageris Android/iOS only).
- Social module Firebase decoupling: extracted platform-agnostic abstract interfaces (
ActivityFeedSource,FollowDataSource,FollowService) into*_base.dartfiles so the social barrel no longer pulls incloud_firestoreon all platforms. pubspec.yaml: updatedtimezoneconstraint to'>=0.10.1 <0.12.0'so pana sees the latest 0.11.x release as compatible.- All dependencies upgraded to latest major versions.
Fixed #
- Static analysis: removed 3 unnecessary imports (
dart:typed_data,pk_permission.dart) and fixedcurly_braces_in_flow_control_structureslint inpermission_helper_web.dart. - Applied
dart formatto all files inlib/.
Score #
- pub.dev pana score: 160 / 160 (Follow conventions 30/30, Documentation 20/20, Platform support 20/20, Static analysis 50/50, Dependencies 40/40).
0.2.0 — 2026-02-22 #
Added #
Realtime Module (primekit/realtime.dart)
PkWebSocketChannel— auto-reconnecting WebSocket with exponential backoff, ping/pong keepalive, and connect timeoutFirebaseRtdbChannel— Firebase Realtime Database channel implementationRealtimeManager— multi-channel coordinator with named channel registryPresenceService— online/away/offline presence tracking with last-seen timestampsMessageBuffer— persistent offline message buffer backed by SharedPreferences with FIFO evictionRealtimeChannel— abstract interface for all channel implementations
Crash Module (primekit/crash.dart)
CrashReporter— abstract crash reporting interfaceFirebaseCrashReporter— Firebase Crashlytics implementationSentryCrashReporter— Sentry Flutter implementationMultiCrashReporter— fan-out reporter dispatching to multiple backendsErrorBoundary— Flutter widget that catches render errors and reports themCrashConfig— global configuration (user info, custom keys, log limits)
Feature Flags Module (primekit/flags.dart)
FlagService— feature flag resolution with caching and fallbackFlagProvider— abstract provider interfaceFirebaseFlagProvider— Firebase Remote Config implementationMongoFlagProvider— MongoDB Atlas Data API implementationLocalFlagProvider— in-memory provider for tests and overridesFlagCache— TTL-based local flag cache with SharedPreferences persistenceFeatureFlag— typed flag definition with default values
Async State Module (primekit/async_state.dart)
AsyncStateValue<T>— sealed class:IdleState,LoadingState,SuccessState,FailureStateAsyncStateNotifier<T>— ChangeNotifier wrapper for async operations withexecute()AsyncBuilder<T>— widget that rebuilds for each async state with typed buildersPaginatedStateNotifier<T>— paginated async state with page tracking and append-on-load
Dependency Injection Module (primekit/di.dart)
ServiceLocator— singleton registry with lazy factories and eager singletonsPkServiceScope— inherited widget providing aServiceLocatorto the widget treePkServiceScopeWidget— root widget for scoped DIModule— abstract interface for grouping related registrationsDisposable— mixin for services that need lifecycle cleanup
Offline Sync Module (primekit/sync.dart)
SyncRepository<T>— generic offline-first repository with optimistic updatesSyncDataSource— abstract local/remote data source interfacePendingChangeStore— SharedPreferences-backed queue of unsynced operationsConflictResolver— pluggable conflict resolution (local-wins, remote-wins, merge)SyncDocument<T>— versioned document wrapper withupdatedAttrackingSyncState— sealed sync status: idle, syncing, synced, conflict, error
Media Module (primekit/media.dart)
MediaPicker— unified photo/video/file picker wrapping image_pickerImageCompressor— quality/size/dimension compression via flutter_image_compressImageCropperService— interactive cropping via image_cropperMediaUploader— chunked upload with progress stream and cancellationMediaFile— typed value object (path, mime, size, dimensions)UploadTask— observable upload task with progress, pause, resume, cancel
RBAC Module (primekit/rbac.dart)
RbacService— role resolution and permission checkingRbacPolicy— declarative permission policy definitionRbacContext— request context (user, resource, action)RbacProvider— abstract role/permission data sourceRbacGate— widget that conditionally renders based on permission checkPermissionDeniedWidget— fallback widget for insufficient permissions
Social Module (primekit/social.dart)
FollowService— follow/unfollow with follower/following count streamsProfileService— user profile CRUD with avatar and display name managementActivityFeed— paginated activity/notification feedActivityFeedSource— abstract feed data sourceShareService— native share sheet integrationSocialAuthProvider— abstract interface for Google/Apple sign-inUserProfile— typed value object with copyWith
Background Tasks Module (primekit/background.dart)
TaskScheduler— Workmanager-backed one-off and periodic task schedulerTaskRegistry— static callback dispatcher required by WorkmanagerBackgroundTask— typed task definition with constraints and payloadTaskResult— success/failure/retry result type for background callbacksCommonTasks— pre-built task factories (sync, cache refresh, cleanup)
Changed #
pubspec.yaml: bumped version to0.2.0; addedweb_socket_channel,sentry_flutter,workmanager,image_picker,flutter_image_compress,image_cropper,google_sign_independencies
Fixed #
Result.when()pattern variable shadowing inFailurebranch (failure: final f)Result.asyncMap()return type: removedasync, wrapped failure branch inFuture.value()list_extensions.dartflattenedgetter: added explicit type parameterexpand<T>to fixList<Object?>inferencewebsocket_channel.dart:_closeSocket()now fire-and-forgetssink.close()with timeout to prevent indefinite hang on unestablished socketswebsocket_channel.dart: stale socket leaked whenready.timeout()threw; now captured, nulled, and abandoned immediately in the catch block
0.1.0 — 2026-02-19 #
Added #
Core Infrastructure
PrimekitConfig— global initialization and configurationResult<S, F>— type-safe discriminated union for error handlingPrimekitExceptionhierarchy — typed exceptions for every modulePrimekitLogger— structured internal logging respecting log levels- Extension methods on
String,DateTime,List,Map
Analytics Module
EventTracker— singleton multi-provider analytics dispatcherAnalyticsProvider— abstract interface for custom providersAnalyticsEvent— typed events with factory constructors (screenView, purchase, signIn, etc.)FunnelTracker— multi-step conversion funnel trackingSessionTracker— session start/end, duration, session countEventCounter— persistent action counter with SharedPreferences backend
Auth Module
TokenStore— secure JWT storage with expiry checking (flutter_secure_storage)AuthInterceptor— Dio interceptor with auto-refresh and session expiry handlingSessionManager— ChangeNotifier-based auth state managementOtpService— OTP generation, storage, validation with TTL and attempt limitsProtectedRouteGuard— go_router redirect guard for authenticated routes
Billing Module
ProductCatalog— typed product registry with pricing metadataSubscriptionManager— active subscription queries and change streamsEntitlementChecker— feature-to-product mapping with access checksBillingEvent— sealed class of billing lifecycle eventsPaywallController— ChangeNotifier paywall display manager with impression trackingPricingFormatter— locale-aware price, period, and savings formatting
Ads Module
AdManager— central ad coordinator for banners, interstitials, and rewardedAdUnitConfig— typed ad unit IDs per platform with test IDs factoryAdCooldownTimer— enforces minimum delay between interstitial showsAdFrequencyCap— per-session and per-day impression limitsAdEventLogger— typed ad event tracking with CTR calculationPkBannerAd— drop-in banner widget with auto-load and error handling
Membership Module
MembershipTier— typed tier system with level-based comparisonAccessPolicy— declarative feature-to-tier mappingTierGate— widget that conditionally renders based on user tierUpgradePrompt— standardized CTA widget (card, banner, dialog, inline styles)MembershipService— ChangeNotifier membership state providerMemberBadge— visual tier badge widgetTrialManager— trial period tracking with event stream
Email Module
EmailProvider— abstract interface (SendGrid, Resend, SMTP implementations)EmailService— singleton email dispatcherEmailMessage/EmailAttachment— typed email compositionContactFormMailer— pre-built contact form email sender with HTML formattingVerificationMailer— OTP and verification link emails with HTML templatesEmailQueue— persistent offline-resilient email queue with retry
Storage Module
SecurePrefs— typed flutter_secure_storage wrapperJsonCache— TTL-based JSON cache with prefix invalidationAppPreferences— typed SharedPreferences for common app settingsMigrationRunner— version-ordered data migrationsFileCache— local file caching with LRU eviction
Permissions Module
PermissionGate— widget that requests and gates on permission statusPermissionFlow— multi-step permission request with rationale dialogsPermissionHelper— static helpers for common permission operations
Forms Module
PkSchema— root schema builder (string, number, bool, object, list, date)PkStringSchema— string validation: email, URL, phone, length, pattern, credit cardPkNumberSchema— numeric validation: min, max, positive, integer, multipleOfPkObjectSchema— composite object schema with field-level error reportingValidationResult— immutable validation result with field error mapPkFormField— Flutter form field backed by PkSchema with debounced validationPkForm— schema-driven form container with PkFormController
Notifications Module
LocalNotifier— local notification scheduling and cancellationPushHandler— FCM/APNs push message handler with permission flowInAppBanner— slide-in in-app notification banner with auto-dismissNotificationChannel— Android notification channel configuration
Network Module
ApiResponse<T>— loading/success/failure sealed classConnectivityMonitor— debounced connectivity streamOfflineQueue— queue-and-flush for offline-resilient API callsRetryInterceptor— Dio interceptor with exponential backoffPrimekitNetworkClient— pre-configured Dio wrapper with typed responses
Device Module
DeviceInfo— cached device details (model, OS, screen, tablet detection)AppVersion— version info with semver comparison and store linksBiometricAuth— Face ID / fingerprint authentication wrapperClipboardHelper— copy/paste with automatic SnackBar feedback
UI Module
LoadingOverlay— global loading overlay withwrap<T>convenience methodToastService— typed snackbars (success, error, warning, info)ConfirmDialog— standardized confirm/cancel dialog with destructive variantSkeletonLoader— shimmer skeleton for any widget with pre-built variantsEmptyState— configurable empty state with pre-built variantsLazyList<T>— infinite-scroll paginated listAdaptiveScaffold— responsive scaffold (bottom nav / side nav / rail)
Routing Module
RouteGuard— composable go_router redirect guardsCompositeRouteGuard— sequential guard compositionDeepLinkHandler— URI pattern matching and go_router dispatchNavigationLogger— NavigatorObserver that logs route changes to analyticsTabStateManager— per-tab scroll position preservation
i18n Module
LocaleManager— ChangeNotifier locale storage with hot switchingPkDateFormatter— locale-aware date formatting presetsPkCurrencyFormatter— locale-aware currency formatting with compact notationPluralHelper— correct pluralization with locale support