Flutter: How to Highlight a Substring in Text Widget

Görkem
1 min readMay 28, 2023

As front-end developers, there are times we would like to render a text content with a highlighted sub string. Especially in some cases such as searching, we want our app to show a list of the search results are emphasises the target string to achieve a better user experience for our apps.

So, coming back to our point, in Fluter it is easy to achieve that by creating an extension on Text widget.

import 'package:flutter/material.dart';

extension BoldSubString on Text {
Text boldSubString(String target) {
final textSpans = List.empty(growable: true);
final escapedTarget = RegExp.escape(target);
final pattern = RegExp(escapedTarget, caseSensitive: false);
final matches = pattern.allMatches(data!);

int currentIndex = 0;
for (final match in matches) {
final beforeMatch = data!.substring(currentIndex, match.start);
if (beforeMatch.isNotEmpty) {
textSpans.add(TextSpan(text: beforeMatch));
}

final matchedText = data!.substring(match.start, match.end);
textSpans.add(
TextSpan(
text: matchedText,
style: const TextStyle(fontWeight: FontWeight.bold),
),
);

currentIndex = match.end;
}

if (currentIndex < data!.length) {
final remainingText = data!.substring(currentIndex);
textSpans.add(TextSpan(text: remainingText));
}

return Text.rich(
TextSpan(children: <TextSpan>[...textSpans]),
);
}
}

The extension above provides a function boldSubString which takes the target parameter and returns a Text including only the target string is bold.

Usage of the extension is pretty straight forward by calling the boldSubString function.

Text('Here is the bold string.').boldSubString('the bold')

The line above is going to return a Text and only the “the bold” is going to be rendered with a bold text style.

For sure, you can customize the text style as you wish.

--

--