getMarkedText function

String getMarkedText({
  1. required String text,
  2. required List<WordMarker> markers,
  3. String tags = '[]',
})

Adds tags to the given text to mark words/blocks enclosed by the given markers. The tags must be exactly 2 characters - one opening and one closing tag.

Implementation

String getMarkedText({
  required final String text,
  required final List<WordMarker> markers,
  final String tags = '[]',
}) {
  assert(
    tags.length == 2,
    'tags must be exactly 2 characters, one as opening and one as closing tag',
  );

  int runningIndex = 0;
  String markedText = '';
  final List<String> _tags = tags.split('');
  final String open = _tags[0];
  final String close = _tags[1];

  for (WordMarker marker in markers) {
    final String substring = text.substring(runningIndex, marker.index);

    markedText += substring + (marker.type == MarkerType.start ? open : close);

    runningIndex = marker.index;
  }
  markedText += text.substring(runningIndex);

  return markedText;
}