Home > database >  search List and remaining word in the list in dart
search List and remaining word in the list in dart

Time:10-04

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());
}

I have a list of about 50-60 words. If i search 'tech' it will show "Technology" but i want remaining words also(like that)...

Technology
Photography
News
Facts
How-to
Science
Space

CodePudding user response:

You can use this trick.

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

It creates a map, where your filtered values put in first. The map removes the duplicates and generates the full list.

Full code

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]
}
  • Related