buildSearchSpan function

Widget buildSearchSpan(
  1. String content,
  2. String searchText, {
  3. Color searchTextColor = Colors.red,
  4. TextStyle style = const TextStyle(color: Colors.black, fontSize: 16),
  5. bool insensitiveCase = true,
})

创建搜索内容

Implementation

Widget buildSearchSpan(
  String content,
  String searchText, {
  Color searchTextColor = Colors.red,
  TextStyle style = const TextStyle(color: Colors.black, fontSize: 16),
  bool insensitiveCase = true,
}) {
  String _content = insensitiveCase ? content.toLowerCase() : content;
  String _searchText = insensitiveCase ? searchText.toLowerCase() : searchText;

  List<TextSpan> spans = [];
  int _cLength = _content.length;
  int _sLength = _searchText.length;
  int _start = 0;
  for (int i = 0; _sLength > 0 && i <= _cLength - _sLength; i++) {
    if (_content.substring(i, i + _sLength) == _searchText) {
      spans.addAll([
        TextSpan(text: content.substring(_start, i), style: style),
        TextSpan(
            text: content.substring(i, _sLength + i),
            style: style.copyWith(color: searchTextColor))
      ]);
      _start = i + _sLength;
      i = _start - 1;
    }
  }
  if (_start != _cLength) {
    spans.add(TextSpan(text: content.substring(_start), style: style));
  }
  return RichText(text: TextSpan(style: style, children: spans));
}