excerpt static method

String? excerpt(
  1. String text,
  2. String phrase, {
  3. int radius = 100,
  4. String omission = '...',
})

Extracts a snippet of text around the first occurrence of phrase.

radius is the number of characters to keep on either side. Returns null if phrase is not found.

Implementation

static String? excerpt(
  String text,
  String phrase, {
  int radius = 100,
  String omission = '...',
}) {
  if (phrase.isEmpty) return null;
  final int i = text.indexOf(phrase);
  if (i == -1) return null;
  final int start = (i - radius).clamp(0, text.length);
  final int end = (i + phrase.length + radius).clamp(0, text.length);
  final String snippet = text.substring(start, end);
  final prefix = start > 0 ? omission : '';
  final suffix = end < text.length ? omission : '';
  return '$prefix$snippet$suffix';
}