pull/241/head
Sultan khan 1 day ago
parent 772f6caa38
commit 69310575e5

@ -94,24 +94,33 @@ class AppState {
String? get getProfileImageData => _profileImageData; String? get getProfileImageData => _profileImageData;
set setProfileImageData(String? value) { set setProfileImageData(String? value) {
// Clear old data first
if (_profileImageData != null && _profileImageData != value) {
print('🔄 Replacing profile image: old data length=${_profileImageData!.length}, new data length=${value?.length ?? 0}');
}
// Set new value directly WITHOUT caching
_profileImageData = value; _profileImageData = value;
// Persist to cache
if (value != null && value.isNotEmpty) { if (value != null && value.isNotEmpty) {
cacheService.saveString(key: _profileImageKey, value: value); print('✅ Profile image set (length: ${value.length}) - NO CACHE');
} else { } else {
cacheService.remove(key: _profileImageKey); print('🗑️ Profile image cleared - NO CACHE');
} }
} }
/// Load profile image from cache on app initialization /// Load profile image from cache on app initialization - DISABLED
void _loadProfileImageFromCache() { void _loadProfileImageFromCache() {
_profileImageData = cacheService.getString(key: _profileImageKey); // DO NOT LOAD FROM CACHE - always fetch fresh from API
_profileImageData = null;
print('📂 Profile image cache disabled - will fetch from API');
} }
/// Clear profile image from cache (e.g., on logout) /// Clear profile image data (e.g., on logout or user switch)
void clearProfileImageCache() { void clearProfileImageCache() {
print('🧹 Clearing profile image data (was: ${_profileImageData != null ? "${_profileImageData!.length} chars" : "null"})');
_profileImageData = null; _profileImageData = null;
cacheService.remove(key: _profileImageKey); print('✅ Profile image data cleared - NO CACHE');
} }
SelectDeviceByImeiRespModelElement? _selectDeviceByImeiRespModelElement; SelectDeviceByImeiRespModelElement? _selectDeviceByImeiRespModelElement;

@ -1240,6 +1240,12 @@ class AuthenticationViewModel extends ChangeNotifier {
try { try {
log("Fetching profile image for patient ID: $patientID"); log("Fetching profile image for patient ID: $patientID");
// IMPORTANT: Clear old cache BEFORE fetching new image
// This ensures old data is removed immediately
_appState.clearProfileImageCache();
log("🧹 Cleared profile image cache before fetch");
final profileSettingsRepo = GetIt.instance<ProfileSettingsRepo>(); final profileSettingsRepo = GetIt.instance<ProfileSettingsRepo>();
final result = await profileSettingsRepo.getProfileImage(patientID: patientID); final result = await profileSettingsRepo.getProfileImage(patientID: patientID);
@ -1247,6 +1253,8 @@ class AuthenticationViewModel extends ChangeNotifier {
(failure) { (failure) {
// Silently fail - profile image is optional // Silently fail - profile image is optional
log("Failed to fetch profile image: ${failure.message}"); log("Failed to fetch profile image: ${failure.message}");
// Ensure cache is cleared even on failure
_appState.setProfileImageData = null;
}, },
(apiResponse) { (apiResponse) {
if (apiResponse.data != null && apiResponse.data['Patient_GetProfileImageDataList'] != null) { if (apiResponse.data != null && apiResponse.data['Patient_GetProfileImageDataList'] != null) {
@ -1254,21 +1262,26 @@ class AuthenticationViewModel extends ChangeNotifier {
if (imageList is List && imageList.isNotEmpty) { if (imageList is List && imageList.isNotEmpty) {
String? imageData = imageList[0]['ImageData']; String? imageData = imageList[0]['ImageData'];
if (imageData != null && imageData.isNotEmpty) { if (imageData != null && imageData.isNotEmpty) {
// Set new profile image data - this will update cache and notify all listeners
_appState.setProfileImageData = imageData; _appState.setProfileImageData = imageData;
log("✅ Profile image loaded and cached successfully"); log("✅ Profile image loaded and cached successfully for patient: $patientID");
} else { } else {
log("⚠️ Profile image data is empty"); log("⚠️ Profile image data is empty for patient: $patientID");
_appState.setProfileImageData = null;
} }
} else { } else {
log("⚠️ Profile image list is empty"); log("⚠️ Profile image list is empty for patient: $patientID");
_appState.setProfileImageData = null;
} }
} else { } else {
log("⚠️ No profile image data in response"); log("⚠️ No profile image data in response for patient: $patientID");
_appState.setProfileImageData = null;
} }
}, },
); );
} catch (e) { } catch (e) {
log("❌ Error fetching profile image: $e"); log("❌ Error fetching profile image: $e");
_appState.setProfileImageData = null;
} }
} }
} }

@ -151,7 +151,7 @@ class ProfileSettingsRepoImp implements ProfileSettingsRepo {
} }
@override @override
Future<Either<Failure, GenericApiModel<dynamic>>> getProfileImage({ Future<Either<Failure, GenericApiModel<dynamic>>> getProfileImage({
required int patientID, required int patientID,
}) async { }) async {
final Map<String, dynamic> body = { final Map<String, dynamic> body = {

@ -189,19 +189,15 @@ class ProfileSettingsViewModel extends ChangeNotifier {
Function(String)? onError, Function(String)? onError,
bool forceRefresh = false, // Add flag to force refresh bool forceRefresh = false, // Add flag to force refresh
}) async { }) async {
// Skip API call if image is already loaded and not forcing refresh print('🌐 Fetching profile image from API for patient: $patientID (forceRefresh: $forceRefresh)');
if (!forceRefresh && GetIt.instance<AppState>().getProfileImageData != null) {
// Use cached data // IMPORTANT: Always clear old data BEFORE fetching
profileImageData = GetIt.instance<AppState>().getProfileImageData; // Do NOT use cached data - always fetch fresh from API
if (onSuccess != null) { profileImageData = null;
onSuccess(profileImageData);
}
return;
}
isProfileImageLoading = true; isProfileImageLoading = true;
profileImageError = null; profileImageError = null;
notifyListeners(); notifyListeners(); // Notify to show loading state
final result = await profileSettingsRepo.getProfileImage(patientID: patientID); final result = await profileSettingsRepo.getProfileImage(patientID: patientID);
@ -209,6 +205,11 @@ class ProfileSettingsViewModel extends ChangeNotifier {
(failure) { (failure) {
isProfileImageLoading = false; isProfileImageLoading = false;
profileImageError = failure.message; profileImageError = failure.message;
print('❌ Failed to fetch profile image: ${failure.message}');
// Ensure data is cleared on failure
profileImageData = null;
notifyListeners(); notifyListeners();
if (onError != null) { if (onError != null) {
onError(failure.message); onError(failure.message);
@ -216,44 +217,48 @@ class ProfileSettingsViewModel extends ChangeNotifier {
}, },
(response) { (response) {
isProfileImageLoading = false; isProfileImageLoading = false;
// Extract image data from response // Extract image data from response
if (response.data != null && response.data['Patient_GetProfileImageDataList'] != null) { if (response.data != null && response.data['Patient_GetProfileImageDataList'] != null) {
var imageList = response.data['Patient_GetProfileImageDataList']; var imageList = response.data['Patient_GetProfileImageDataList'];
if (imageList is List && imageList.isNotEmpty) { if (imageList is List && imageList.isNotEmpty) {
profileImageData = imageList[0]['ImageData']; profileImageData = imageList[0]['ImageData'];
// Store in AppState for global access
GetIt.instance<AppState>().setProfileImageData = profileImageData;
if (profileImageData != null && profileImageData!.isNotEmpty) {
// ONLY store in ViewModel - AppState will be updated separately by auth flow
print('✅ Profile image loaded from API (length: ${profileImageData!.length})');
} else {
profileImageData = null;
print('⚠️ Profile image data is empty in API response');
}
} else { } else {
profileImageData = null; profileImageData = null;
GetIt.instance<AppState>().setProfileImageData = null; print('⚠️ Profile image list is empty in API response');
} }
} else { } else {
profileImageData = null; profileImageData = null;
GetIt.instance<AppState>().setProfileImageData = null; print('⚠️ No profile image data in API response');
} }
notifyListeners();
notifyListeners(); // Notify to update UI with new/null data
onSuccess?.call(response.data); onSuccess?.call(response.data);
}, },
); );
} }
/// Clear cached profile image data /// Clear profile image data from ViewModel
void clearProfileImageCache() { void clearProfileImageCache() {
print('🧹 Clearing profile image from ViewModel');
profileImageData = null; profileImageData = null;
GetIt.instance<AppState>().setProfileImageData = null;
notifyListeners(); notifyListeners();
} }
/// Sync profile image data from AppState /// Sync profile image data from AppState - DISABLED
/// Profile Settings screen uses only ViewModel data from API
void syncProfileImageFromAppState() { void syncProfileImageFromAppState() {
final appStateImageData = GetIt.instance<AppState>().getProfileImageData; // DO NOTHING - Profile Settings uses only direct API data
if (appStateImageData != null && appStateImageData.isNotEmpty) { // No syncing from AppState to avoid stale cache issues
if (profileImageData != appStateImageData) { print('⚠️ syncProfileImageFromAppState called but disabled - use API data only');
profileImageData = appStateImageData;
notifyListeners();
}
}
} }
Future<void> uploadProfileImage({ Future<void> uploadProfileImage({

@ -34,13 +34,12 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
void initState() { void initState() {
super.initState(); super.initState();
_currentPatientId = _appState.getAuthenticatedUser()?.patientId; _currentPatientId = _appState.getAuthenticatedUser()?.patientId;
print('🎬 ProfilePictureWidget initState - patient: $_currentPatientId');
// Use addPostFrameCallback to ensure widget is built before loading // Use addPostFrameCallback to ensure widget is built before loading
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return; if (!mounted) return;
final profileVm = context.read<ProfileSettingsViewModel>();
final patientID = _appState.getAuthenticatedUser()?.patientId; final patientID = _appState.getAuthenticatedUser()?.patientId;
if (patientID == null) { if (patientID == null) {
@ -48,20 +47,9 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
return; return;
} }
// Check if we have data in AppState that matches current user // Always load fresh data from API - do NOT use AppState cache
final appStateImageData = _appState.getProfileImageData; print('📥 Loading fresh profile image from API for patient: $patientID');
_loadProfileImage(forceRefresh: true);
if (appStateImageData != null && appStateImageData.isNotEmpty) {
// Sync to ViewModel if it doesn't have data
if (profileVm.profileImageData == null || profileVm.profileImageData!.isEmpty) {
print('🔄 Syncing AppState data to ViewModel');
profileVm.syncProfileImageFromAppState();
}
} else {
// No cached data - load from API
print('📥 No cached data - loading from API for patient: $patientID');
_loadProfileImage(forceRefresh: false);
}
}); });
} }
@ -88,13 +76,25 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
final oldPatientId = _currentPatientId; final oldPatientId = _currentPatientId;
_currentPatientId = currentPatientId; _currentPatientId = currentPatientId;
// Clear the old profile image data // Clear the old profile image data from BOTH AppState and ViewModel
try { try {
final profileVm = context.read<ProfileSettingsViewModel>(); final profileVm = context.read<ProfileSettingsViewModel>();
print('🧹 Clearing cache for old user: $oldPatientId'); print('🧹 Clearing cache for old user: $oldPatientId');
// Clear AppState cache first
_appState.clearProfileImageCache();
// Then clear ViewModel cache
profileVm.clearProfileImageCache(); profileVm.clearProfileImageCache();
// Force rebuild to show default avatar immediately
if (mounted) {
setState(() {
_selectedImage = null; // Clear any selected image
});
}
print('📥 Loading profile image for new user: $currentPatientId'); print('📥 Loading profile image for new user: $currentPatientId');
// Load the new user's profile image immediately // Load the new user's profile image immediately
profileVm.getProfileImage( profileVm.getProfileImage(
@ -455,6 +455,7 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
Widget _buildProfileImage(ProfileSettingsViewModel profileVm) { Widget _buildProfileImage(ProfileSettingsViewModel profileVm) {
// Always get fresh user data // Always get fresh user data
final currentUser = _appState.getAuthenticatedUser(); final currentUser = _appState.getAuthenticatedUser();
final currentPatientId = currentUser?.patientId;
final gender = currentUser?.gender ?? 1; final gender = currentUser?.gender ?? 1;
final age = currentUser?.age ?? 0; final age = currentUser?.age ?? 0;
@ -480,11 +481,22 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
); );
} }
// Use ViewModel data if available, otherwise fall back to AppState // // IMPORTANT: Verify the cached image belongs to the current user
// This ensures we show the current logged-in user's image (same as homepage profile icon) // // If _currentPatientId doesn't match currentPatientId, don't show cached image
final String? imageData = profileVm.profileImageData ?? _appState.getProfileImageData; // if (currentPatientId != _currentPatientId) {
// print('⚠️ Patient ID mismatch - showing default avatar (current: $currentPatientId, cached: $_currentPatientId)');
// return Image.asset(
// defaultImage,
// width: 136.w,
// height: 136.h,
// );
// }
// IMPORTANT: Use ONLY ViewModel data, DO NOT fallback to AppState
// This prevents showing stale cached data when switching users
final String? imageData = profileVm.profileImageData;
print('🖼️ Building profile image - has data: ${imageData != null && imageData.isNotEmpty}, patient: ${currentUser?.patientId}'); print('🖼️ Building profile image - has data: ${imageData != null && imageData.isNotEmpty}, patient: $currentPatientId (ViewModel ONLY)');
// Show uploaded image if available // Show uploaded image if available
if (imageData != null && imageData.isNotEmpty) { if (imageData != null && imageData.isNotEmpty) {
@ -510,7 +522,7 @@ class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
} }
// Show default image (no image data or user has no uploaded image) // Show default image (no image data or user has no uploaded image)
print('📷 Showing default avatar for user ${currentUser?.patientId}'); print('📷 Showing default avatar for user $currentPatientId');
return Image.asset( return Image.asset(
defaultImage, defaultImage,
width: 136.w, width: 136.w,

Loading…
Cancel
Save