'how can i return String value from list by it's name value in dart list
How can i handle the following code
List books = ['book1', book2]
String getTextWidget() {
return // here i need to only return the element which is 'book1' such as if books.contains('book1') return this element as String ;
}
the i need to put it in Text Widget like so
Container(
child Text(getTextWidget())
)
i tried the following code , it is work but it does not accept String Widget
getTextWidget() {
books .forEach((element) {
if(element.contains('book1')){
'book1'
}
});
}
Solution 1:[1]
I think you'd benefit from the .firstWhere method on your list.
void main() {
// an arbitrary object that is not type String
final book2 = Object();
List books = ['book1', book2];
print(getTextElement(books)); // book1
}
String? getTextElement(List list) {
return list.firstWhere((e) => e is String);
}
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 | Apealed |
