CFClient class

Main SDK client for CustomFit feature flags, analytics, and configuration management.

The CFClient is the primary interface for interacting with the CustomFit SDK. It provides feature flag evaluation, event tracking, user management, and session handling.

Usage

Initialize the client once in your application:

final config = CFConfig.builder('your-client-key')
  .setDebugLoggingEnabled(true)
  .build();

final user = CFUser.builder('user123')
  .addStringProperty('plan', 'premium')
  .build();

final client = await CFClient.initialize(config, user);

Features

  • Feature Flags: Boolean, string, number, and JSON configuration values
  • Event Tracking: Analytics and user behavior tracking
  • User Management: User properties, contexts, and targeting
  • Session Management: Automatic session lifecycle handling
  • Offline Support: Queue operations when network is unavailable
  • Real-time Updates: Live configuration updates via listeners

Thread Safety

All methods are thread-safe and can be called from any isolate. The client uses internal synchronization to ensure data consistency.

Constructors

CFClient.withDependencies(CFConfig config, CFUser user, DependencyFactory dependencyFactory)
Constructor with dependency injection (for testing only)

Properties

backgroundStateMonitor → BackgroundStateMonitor
no setter
configFetcher → ConfigFetcher
no setter
configManager ConfigManager
no setter
connectionManager → ConnectionManagerImpl
no setter
environmentManager EnvironmentManager
no setter
events CFClientEvents
Access to events functionality
no setter
eventTracker EventTracker
no setter
featureFlags CFClientFeatureFlags
Access to feature flags functionality
no setter
hashCode int
The hash code for this object.
no setterinherited
isSuccess bool
CFResult compatibility methods for tests
no setter
listenerManager ListenerManager
no setter
listeners CFClientListeners
Access to listeners functionality
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
summaryManager → SummaryManager
Expose managers via DependencyContainer
no setter
typed FeatureFlags
Access to type-safe feature flags
no setter
userManager UserManager
no setter

Methods

addAllFlagsListener(void listener(Map<String, dynamic>, Map<String, dynamic>)) → void
Add all flags listener
addBooleanProperty(String key, bool value) CFResult<void>
Add a boolean property to the user
addConfigListener<T>(String key, void listener(T)) → void
Add a config listener for a specific feature flag
addContext(EvaluationContext context) CFResult<void>
Add an evaluation context to the user
addFeatureFlagListener(String flagKey, void listener(String, dynamic, dynamic)) → void
Add feature flag listener
addJsonProperty(String key, Map<String, dynamic> value) CFResult<void>
Add a JSON property to the user
addMapProperty(String key, Map<String, dynamic> value) CFResult<void>
Add a map property to the user
addNumberProperty(String key, num value) CFResult<void>
Add a number property to the user
addPrivateBooleanProperty(String key, bool value) CFResult<void>
Add a private boolean property to the user
addPrivateJsonProperty(String key, Map<String, dynamic> value) CFResult<void>
Add a private JSON property to the user
addPrivateMapProperty(String key, Map<String, dynamic> value) CFResult<void>
Add a private map property to the user
addPrivateNumberProperty(String key, num value) CFResult<void>
Add a private number property to the user
addPrivateStringProperty(String key, String value) CFResult<void>
Add a private string property to the user
addSessionRotationListener(SessionRotationListener listener) → void
Add a session rotation listener
addStringProperty(String key, String value) CFResult<void>
Add a string property to the user
addUserProperties(Map<String, dynamic> properties) CFResult<void>
Add multiple properties to the user
addUserProperty(String key, dynamic value) CFResult<void>
Add a property to the user
clearConfigListeners(String key) → void
Clear all listeners for a specific configuration
clearFlagCache(String key) Future<void>
Clear cache for a specific flag
clearGracefulDegradationCache() Future<void>
Clear graceful degradation cache
clearUser() Future<CFResult<void>>
Clear the current user by setting an anonymous user
fetchAndGetAllFlags({String? lastModified}) Future<Map<String, dynamic>>
Synchronizes fetching configuration and getting all flags
flagExists(String key) bool
Check if a specific flag exists
flushEvents() Future<CFResult<void>>
Flush all pending events immediately
forceRefresh() Future<bool>
Force a refresh of the configuration
forceSessionRotation() Future<String?>
Force session rotation with a manual trigger
getAllFlags() Map<String, dynamic>
Get all available feature flags
getBoolean(String key, bool defaultValue) bool
Get a boolean feature flag value
getBooleanWithDegradation(String key, bool defaultValue, {FallbackStrategy? strategy}) Future<bool>
Evaluate a boolean flag with full graceful degradation
getCacheStats() Future<Map<String, dynamic>>
Get cache statistics
getContexts() List<EvaluationContext>
Get all evaluation contexts for the user
getCurrentSessionData() SessionData?
Get current session data with metadata
getCurrentSessionId() String
Get the current session ID
getErrorMessage() String?
getFeatureFlag<T>(String key, T defaultValue) → T
Get a feature flag value with generic type support
getGracefulDegradationMetrics() Map<String, dynamic>
Get graceful degradation metrics
getJson(String key, Map<String, dynamic> defaultValue) Map<String, dynamic>
Get a JSON feature flag value
getJsonWithDegradation(String key, Map<String, dynamic> defaultValue, {FallbackStrategy? strategy}) Future<Map<String, dynamic>>
Evaluate a JSON flag with full graceful degradation
getNumber(String key, double defaultValue) double
Get a number feature flag value
getNumberWithDegradation(String key, double defaultValue, {FallbackStrategy? strategy}) Future<double>
Evaluate a number flag with full graceful degradation
getOrNull() CFClient?
getOrThrow() CFClient
getPendingEventCount() int
Get the count of pending events in the queue
getSessionStatistics() Map<String, dynamic>
Get session statistics
getSingletonStats() Map<String, dynamic>
Get singleton registry statistics (for debugging)
getString(String key, String defaultValue) String
Get a string feature flag value
getStringWithDegradation(String key, String defaultValue, {FallbackStrategy? strategy}) Future<String>
Evaluate a string flag with full graceful degradation
getUser() CFUser
Get the current user
getUserProperties() Map<String, dynamic>
Get all user properties
incrementAppLaunchCount() → void
Increment the application launch count
isOffline() bool
Returns whether the client is in offline mode
markPropertiesAsPrivate(List<String> keys) CFResult<void>
Mark multiple existing properties as private
markPropertyAsPrivate(String key) CFResult<void>
Mark an existing property as private
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onUserAuthenticationChange(String? userId) Future<void>
Handle user authentication changes
performAutoRecovery() Future<CFResult<List<String>>>
Perform automatic recovery based on current system state
performSystemHealthCheck() Future<CFResult<SystemHealthStatus>>
Perform comprehensive system health check and recovery
recoverConfiguration() Future<CFResult<Map<String, dynamic>>>
Recover from configuration corruption or update failures
recoverEvents({int maxEventsToRetry = 50}) Future<CFResult<EventRecoveryResult>>
Recover failed events and retry offline events
recoverSession({String? reason, Future<String?> authTokenRefreshCallback()?}) Future<CFResult<String>>
Recover from session-related errors
removeAllFlagsListener(void listener(Map<String, dynamic>, Map<String, dynamic>)) → void
Remove all flags listener
removeConfigListener(String key) → void
Remove a config listener for a specific feature flag
removeContext(ContextType type, String key) CFResult<void>
Remove an evaluation context from the user
removeFeatureFlagListener(String flagKey, void listener(String, dynamic, dynamic)) → void
Remove feature flag listener
removeProperties(List<String> keys) CFResult<void>
Remove multiple properties from the user
removeProperty(String key) CFResult<void>
Remove a property from the user
removeSessionRotationListener(SessionRotationListener listener) → void
Remove a session rotation listener
safeConfigUpdate(Map<String, dynamic> newConfig, {Duration validationTimeout = const Duration(seconds: 30)}) Future<CFResult<bool>>
Perform safe configuration update with automatic rollback on failure
setOffline(bool offline) → void
Puts the client in offline mode
setUser(CFUser user) Future<CFResult<void>>
Set the current user
shutdown() Future<void>
Shutdown the client
toString() String
A string representation of this object.
inherited
trackConversion(String conversionName, Map<String, dynamic> properties) Future<CFResult<void>>
Track a conversion event
trackEvent(String eventType, {Map<String, dynamic>? properties}) Future<CFResult<void>>
Track an analytics event with optional properties
updateSessionActivity() Future<void>
Update session activity

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Properties

completedInitializationSteps List<String>
Get completed initialization steps for debugging
no setter
initializationState → InitializationState
Get the current initialization state
no setter

Static Methods

clearInstance() → void
Clear the singleton instance for testing purposes
clearSingletonRegistry() → void
Clear singleton registry (for testing only)
createDetached(CFConfig config, CFUser user) CFClient
Create a detached (non-singleton) instance of CFClient Use this only if you specifically need multiple instances (not recommended) Most applications should use init() for singleton pattern
getInstance() CFClient?
Get the current singleton instance if it exists
initialize(CFConfig config, CFUser user, {DependencyFactory? dependencyFactory}) Future<CFClient>
Initialize the singleton instance of CFClient with configuration and user.
initializeWithRetry(CFConfig config, CFUser user, {int maxRetries = 3, int initialDelayMs = 1000, DependencyFactory? dependencyFactory}) Future<CFClient>
Initialize with automatic retry on failure
isInitialized() bool
Check if the singleton instance is initialized
isInitializing() bool
Check if initialization is currently in progress
reinitialize(CFConfig config, CFUser user, {DependencyFactory? dependencyFactory}) Future<CFClient>
Force reinitialize the singleton with new configuration
setTestInstance(CFClient instance) → void
Internal method for setting test instance (testing only)
shutdownSingleton() Future<void>
Shutdown and clear the singleton instance