Is it possible to get access from the constructor to a List dot Parameter?
What I want is one function instead of 2 or more something like this.
void somethingA()
{ someList.where((item) => item.A == "123") }
void somethingB()
{ someList.where((item) => item.B == "456") }
to something like this
void something(List list.XY)
{ someList.where((item) => item.list.XY == "123") }
thanks for the help.
CodePudding user response:
if you want to get a list based on its items :
List<List> someList = [["a", "b"], ["c", "d"]];
void something(List<List> list){
list.where((element){
return element == ["a", "b"];
});
}
based on its specific item :
List<List> somethingB(List<List> list){
List<List> result = [];
list.where((element){
element.map((e){
if(e == "a"){
result.add(e);
}
if(e == "b"){
result.add(e);
}
}).toList();
});
return result;
}
CodePudding user response:
You cannot reall pass something like list.XY, but you can come close:
Iterable<T> itemsWithValue5<T>(Iterable<T> values, int Function(T) selector) {
return values.where((value) => selector(value) == 5);
}
void main() {
const words = ['Hello', 'World'];
final wordsWithLength5 = itemsWithValue5<String>(words, (word) => word.length);
print(wordsWithLength5);
}
The selector
parameter takes a function that gets an item (in this case of type string) and transforms it into something else, in this case an int
. This allows you to write something like (word) => word.length
as your selector, which is alreasy pretty close to list.XY
.