search List and remaining word in the list in dart

292

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]
}
Share:
292
Sam
Author by

Sam

Updated on January 01, 2023

Comments

  • Sam
    Sam over 1 year
    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
    
  • Faiizii Awan
    Faiizii Awan over 2 years
    please add a reference of 3 dots so he clearly understands the operation
  • towhid
    towhid over 2 years
    ... its called spread operator. you can find more about it here. dart.dev/guides/language/language-tour#spread-operator