在飞镖中搜索列表和列表中的剩余单词

search List and remaining word in the list in dart

void main(){
List<String> topics = [
  'Photography',
  'News',
  'Facts',
  'How-to',
  'Technology',
  'Science',
  'Space',
];
  
 var text='tech';
 var _searchResult = topics.where(
                    (topics) => (topics.contains(text) || 
                    topics.toLowerCase().contains(text))
                );
  
 print(_searchResult.toString());
}

我有一个大约 50-60 个单词的列表。如果我搜索 'tech' 它会显示“技术”,但我也想要剩余的词(像那样)...

Technology
Photography
News
Facts
How-to
Science
Space

你可以使用这个技巧。

final result = {..._searchResult, ...topics}.toList();

它会创建一个地图,将过滤后的值放在首位。该地图删除重复项并生成完整列表。

完整代码

List<String> topics = [
  'Photography',
  'News',
  'Facts',
  'How-to',
  'Technology',
  'Science',
  'Space',
];

void main() {
  final text = 'tec';
  final _searchResult = topics
      .where((i) => i.toLowerCase().contains(text.toLowerCase()))
      .toList();

  final result = {..._searchResult, ...topics}.toList();
  
  print(result); // [Technology, Photography, News, Facts, How-to, Science, Space]
}