'Search value in list
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}]
Solution 1:[1]
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}]
To seperate numbers from the text, you can use the function below;
List<String> splitTextAndNumber(String text){
String stringText = "";
String numberText = "";
for(int i = 0; i < text.length; i++){
var char = text[i];
try{
var parsedValue = int.parse(char);
numberText += char;
}catch(e){
stringText += char;
}
}
return [stringText, numberText];
}
You can basically call function in this way below;
String text = "table15";
List<String> splitedValues = splitTextAndNumber(text);
print(splitedValues); // returns [table, 15]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
