Flutter中实现文本部分匹配搜索高亮及代码优化咨询
Flutter RichText 部分匹配高亮+空格优化方案
针对你的需求,这里给出具体的实现代码和优化方案:
一、实现部分字符匹配高亮
原来的精确匹配逻辑仅对完全一致的单词生效,修改为包含匹配并忽略大小写后,输入部分字符(如Flut)就能高亮对应单词:
- 将判断条件从
e!=txtsearch.text替换为!e.toLowerCase().contains(txtsearch.text.toLowerCase()) - 这样不管输入大小写,只要单词包含搜索子串就会被高亮。
二、添加空格的替代方案
你当前用e+' '的方式会导致最后多一个多余空格,推荐以下两种更优雅的方式:
方式1:单独插入空格TextSpan
遍历单词时,给每个单词(除最后一个)后添加独立的空格TextSpan:
children: [ for (int i = 0; i < mywords.length; i++) ...[ TextSpan( text: mywords[i], style: mywords[i].toLowerCase().contains(txtsearch.text.toLowerCase()) ? TextStyle(color: Colors.blue, fontSize: 20) : TextStyle(color: Colors.black, fontSize: 20), ), // 最后一个单词不添加空格 if (i != mywords.length - 1) TextSpan(text: ' ', style: TextStyle(fontSize: 20)), ], ]
方式2:用WidgetSpan自定义间距
如果需要更灵活的间距宽度,可以替换空格为SizedBox:
if (i != mywords.length - 1) WidgetSpan(child: SizedBox(width: 6)), // 可根据需求调整宽度
完整修改后的代码
Widget build(BuildContext context) { String mystring = 'Welcome to Flutter'; List<String> mywords = mystring.split(' '); return MaterialApp( home: Scaffold( body: Padding( padding: const EdgeInsets.symmetric(vertical: 30.0, horizontal: 10), child: Column( children: [ SizedBox(height: 20), TextField(controller: txtsearch), ElevatedButton( onPressed: () => setState(() {}), child: Text('Search Word in String'), ), SizedBox(height: 40), // 合并两个SizedBox减少冗余 RichText( text: TextSpan( style: TextStyle(fontSize: 20, color: Colors.black), children: [ for (int i = 0; i < mywords.length; i++) ...[ TextSpan( text: mywords[i], style: mywords[i].toLowerCase().contains(txtsearch.text.toLowerCase()) ? TextStyle(color: Colors.blue) : null, ), if (i != mywords.length - 1) TextSpan(text: ' '), ], ], ), ), ], ), ), ), ); }
内容的提问来源于stack exchange,提问作者Irfan Ganatra
相关产品推荐
相关产品推荐

