commonPrefix method
Returns the longest common prefix of all strings in this list.
Returns empty string if list is empty or any element is empty. Compares whole characters (grapheme clusters), so the result never ends in half an emoji or a letter without its combining mark.
Example:
['flower', 'flow', 'flight'].commonPrefix(); // 'fl'
['a', 'b'].commonPrefix(); // ''
['👋a', '👍b'].commonPrefix(); // ''
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String commonPrefix() {
if (isEmpty) return '';
// Graphemes, not code units: '👋' and '👍' share their high surrogate, so
// the code-unit scan returned a lone surrogate as the "common prefix".
List<String> prefix = this[0].characters.toList();
for (final String s in skip(1)) {
prefix = prefix.sublist(0, _leadingMatchCount(prefix, s.characters.toList()));
if (prefix.isEmpty) return '';
}
return prefix.join();
}