getSelectionSpans method
Returns the spans covered by selection, with chips as ChipSpans.
Runs of plain text become TextSpans and each chip becomes a ChipSpan carrying its value. Used to serialize a selection to the clipboard so chips copy as their value instead of their placeholder codepoint.
Implementation
List<InlineSpan> getSelectionSpans(TextSelection selection) {
final String text = value.text;
if (!selection.isValid) return const [];
final int start = selection.start.clamp(0, text.length);
final int end = selection.end.clamp(0, text.length);
final List<InlineSpan> spans = [];
final StringBuffer buffer = StringBuffer();
for (int i = start; i < end; i++) {
int codeUnit = text.codeUnitAt(i);
if (codeUnit >= _chipStart && codeUnit <= _chipEnd) {
if (buffer.isNotEmpty) {
spans.add(TextSpan(text: buffer.toString()));
buffer.clear();
}
T? chip = _chipMap[codeUnit - _chipStart];
if (chip != null) {
spans.add(ChipSpan<T>(value: chip, child: const SizedBox.shrink()));
}
} else {
buffer.writeCharCode(codeUnit);
}
}
if (buffer.isNotEmpty) {
spans.add(TextSpan(text: buffer.toString()));
}
return spans;
}