Home > front end >  Search value in list
Search value in list

Time:04-23

I want to search value in list:

          String search = 'blue Table15';

                    List list = [
                      {"Label": "blue Table 15", "Value": "1"},
                      {"Label": "Table blue 15", "Value": "2"},
                      {"Label": " blue15 Table", "Value": "3"},
                      {"Label": "Chair red 14", "Value": "4"},
                      {"Label": "Chair 16 red ", "Value": "5"},
                      {"Label": " 17 Chair red", "Value": "6"},
                    ];

                    List<dynamic> values = list
                        .where((oldValue) =>
                            (oldValue['Label'].toString().contains(search)))
                        .toList();

                    print(values);

                    

expected return:

[{Label: blue Table 15, Value: 1}, {Label: Table blue 15, Value: 2}, {Label: blue15 Table, Value: 3}]

CodePudding user response:

You firstly need to split your search text into single words. Then check all splited single word with contain function in where filter like here; (If you have more than values in search string, you can also use loops to check all splited word)

   String search = 'blue Table 15';
   List<String> splitedValue = search.split(" ");
   List list = [
         {"Label": "blue Table 15", "Value": "1"},
         {"Label": "Table blue 15", "Value": "2"},
         {"Label": " blue15 Table", "Value": "3"},
         {"Label": "Chair red 14", "Value": "4"},
         {"Label": "Chair 16 red ", "Value": "5"},
         {"Label": " 17 Chair red", "Value": "6"},
   ];

   List<dynamic> values = list
                        .where((oldValue) =>
                            (oldValue['Label'].contains(splitedValue[0]) || 
                         oldValue['Label'].contains(splitedValue[1]) ||
                         oldValue['Label'].contains(splitedValue[2])))
                        .toList();

   print(values);
   //[{Label: blue Table 15, Value: 1}, {Label: Table blue 15, Value: 2}, {Label:  blue15 Table, Value: 3}]
  • Related