Filter strings containing a word in Flutter
Solution 1:
Might not be the most performant, but unless you're doing this on millions of items, there shouldn't be any problem:
final l = [
'That is a list of some animals',
'That is a list of something like animals',
'That is a list of handsome animals',
];
l.retainWhere((str) => str.split(' ').any((word) => word.startsWith('some')));
Solution 2:
The question is already been answered in the simplest form of code. But I am doing it in a layman's way.
final list = [
'That is a list of some animals',
'That is a list of something like animals',
'That is a list of handsome animals',
];
for(var i = 0 ; i < list.length ; i++){
var sentence = list[i].split(' ');
bool found = false;
for(var j = 0 ; j < sentence.length ; j++){
if (sentence[j].startsWith('some')){
found = true;
}
}
if(!found){
list.removeAt(i);
found = false;
}
}
- Stored three sentences in the list.
- Used a loop to get each sentence.
- Split the sentence on the basis of space, to get each word.
- Used an array to check each word of the sentence, whether it is starting from some
- If any word of the sentence is starting from some, then I removed that sentence from the list