Toggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage
Current user service
• Section: Services
Current User Service
Overview
1. Clear Provider Delegation
// New - all user-related providers delegate to AuthService
@riverpodUserModel?currentUser(Refref){returnref.watch(authServiceSimpleProvider).user;// Single source
}@riverpodboolcurrentUserIsAuthenticated(Refref){returnref.watch(authServiceSimpleProvider).isAuthenticated;// Single source
}@riverpodboolcurrentUserIsLoading(Refref){finalauthLoading=ref.watch(authServiceSimpleProvider).isLoading;finaluserLoading=ref.watch(currentUserServiceProvider).isLoading;returnauthLoading||userLoading;// Combines both loading states clearly
}
2. Clear Separation of Responsibilities
// AuthService: Manages authentication and user state
classAuthService{Future<void>signIn(AuthAttemptattempt){/* handles auth */}Future<void>signOut(){/* handles auth */}voidupdateUser(UserModeluser){/* updates user state */}}// CurrentUserService: Manages user operations only
classCurrentUserService{Future<void>updateUser(UserModeluser){/* API calls, then delegates to AuthService */}Future<void>updateUserField(Stringfield,dynamicvalue){/* user operations */}Future<void>refreshUser(){/* refresh from server */}}
Usage Examples
// Single source of truth - always consistent
finalauthState=ref.watch(authServiceSimpleProvider);if(authState.isAuthenticated){// authState.user is guaranteed to be non-null
print('User: ${authState.user!.email}');// Always safe!
}// Clear loading state
if(ref.watch(currentUserIsLoadingProvider)){showLoadingSpinner();// Combines both loading states intelligently
}
Usage Patterns
User Authentication State
// Always get from auth service - single source
finalisAuth=ref.watch(isAuthenticatedProvider);finaluser=ref.watch(currentUserProvider);// Delegates to auth service
User Operations
// Use current user service for operations
finaluserService=ref.read(currentUserServiceProvider.notifier);awaituserService.updateUserField('displayName','New Name');// Automatically updates auth service state too
Loading States
// Intelligent loading state combining both services
finalisLoading=ref.watch(currentUserIsLoadingProvider);// Shows loading for auth operations OR user operations