getRandomChar method

  1. @useResult
String getRandomChar()

Returns a random character (whole grapheme cluster) from this string.

Picks among user-perceived characters, so an emoji or a letter plus its combining mark is returned whole, never as a lone surrogate or mark. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String getRandomChar() {
  if (isEmpty) {
    return '';
  }

  // Index into graphemes, not code units: this[index] could return half a
  // surrogate pair (an invalid string) or a bare combining mark.
  final Characters chars = characters;
  final int index = DateTime.now().microsecondsSinceEpoch % chars.length;

  return chars.elementAt(index);
}