buildEmphasizedTextWidgets function

List<TextSpan> buildEmphasizedTextWidgets({
  1. required String text,
  2. required List<WordMarker> markers,
})

Returns a list of widgets representing texts parts, each with its own style. Text enclosed by start and end markers, gets the emphasized style. Text not enclosed by markers, gets the text style.

Implementation

List<TextSpan> buildEmphasizedTextWidgets({
  required final String text,
  required List<WordMarker> markers,
}) {
  TextStyle textStyle = const TextStyle(
    color: Colors.black,
    fontWeight: FontWeight.normal,
  );

  TextStyle wordStyle = textStyle.copyWith(
    fontWeight: FontWeight.bold,
  );

  int runningIndex = 0;
  List<TextSpan> emphasizedTextWidgets = <TextSpan>[];

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

    if (marker.type == MarkerType.start) {
      emphasizedTextWidgets.add(TextSpan(text: substring, style: textStyle));
    } else if (marker.type == MarkerType.end) {
      emphasizedTextWidgets.add(TextSpan(text: substring, style: wordStyle));
    }

    runningIndex = marker.index;
  }

  // add last part of text
  final String substring = text.substring(runningIndex, text.length);
  emphasizedTextWidgets.add(TextSpan(text: substring, style: textStyle));

  return emphasizedTextWidgets;
}