import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class ProfileAvatar extends StatelessWidget { final String? name; final String? imageUrl; final double size; final VoidCallback? onTap; const ProfileAvatar({ super.key, this.name, this.imageUrl, this.size = 40, this.onTap, }); @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child: Container( width: size, height: size, decoration: BoxDecoration( shape: BoxShape.circle, color: _getAvatarColor(name ?? 'User'), boxShadow: [ BoxShadow( color: Colors.black.withValues(alpha: 0.1), blurRadius: 8, offset: const Offset(0, 2), ), ], ), child: imageUrl != null && imageUrl!.isNotEmpty ? ClipOval( child: Image.network( imageUrl!, width: size, height: size, fit: BoxFit.cover, errorBuilder: (context, error, stackTrace) { return _buildInitialsAvatar(); }, ), ) : _buildInitialsAvatar(), ), ); } Widget _buildInitialsAvatar() { final initials = _getInitials(name ?? 'User'); return Center( child: Text( initials, style: GoogleFonts.poppins( fontSize: size * 0.4, fontWeight: FontWeight.w600, color: Colors.white, ), ), ); } String _getInitials(String name) { final words = name.trim().split(' '); if (words.isEmpty) return 'U'; if (words.length == 1) { return words[0].substring(0, 1).toUpperCase(); } return '${words[0].substring(0, 1)}${words[1].substring(0, 1)}'.toUpperCase(); } Color _getAvatarColor(String name) { // Generate a consistent color based on the name final colors = [ const Color(0xFF6366F1), // Indigo const Color(0xFF8B5CF6), // Purple const Color(0xFFEC4899), // Pink const Color(0xFFEF4444), // Red const Color(0xFFF59E0B), // Amber const Color(0xFF10B981), // Emerald const Color(0xFF06B6D4), // Cyan const Color(0xFF3B82F6), // Blue const Color(0xFF84CC16), // Lime const Color(0xFFF97316), // Orange ]; // Use the name's hash to consistently pick the same color final hash = name.hashCode; return colors[hash.abs() % colors.length]; } }