getInitials static method

String getInitials(
  1. String name
)

Generates initials from a user's full name.

Creates appropriate initials for avatar display from a given name string. Uses intelligent logic to extract meaningful characters:

  • For single words: First two characters (e.g., "John" → "JO")
  • For multiple words: First character of first two words (e.g., "John Doe" → "JD")
  • Handles edge cases with proper capitalization

Parameters:

  • name (String): The full name to extract initials from

Returns: A String containing the generated initials, typically 1-2 characters.

Example:

String initials1 = Avatar.getInitials('John Doe'); // Returns 'JD'
String initials2 = Avatar.getInitials('Madonna'); // Returns 'MA'

Implementation

static String getInitials(String name) {
  final List<String> parts = name.split(r'\s+');
  if (parts.isEmpty) {
    // get the first 2 characters (title cased)
    String first = name.substring(0, 1).toUpperCase();
    if (name.length > 1) {
      String second = name.substring(1, 2).toUpperCase();
      return first + second;
    }
    return first;
  }
  // get the first two characters
  String first = parts[0].substring(0, 1).toUpperCase();
  if (parts.length > 1) {
    String second = parts[1].substring(0, 1).toUpperCase();
    return first + second;
  }
  // append with the 2nd character of the first part
  if (parts[0].length > 1) {
    String second = parts[0].substring(1, 2).toUpperCase();
    return first + second;
  }
  return first;
}