Home > Mobile >  how can i return String value from list by it's name value in dart list
how can i return String value from list by it's name value in dart list

Time:02-02

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'
      }
    });
  }

CodePudding user response:

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);
}

CodePudding user response:

try this , give "book1" to the methode as a parameter

String getTextWidget(String nameofbook) {
 if(books.contains(nameofbook)==true){
 return nameofbook;
 }
 else return null;
}
  •  Tags:  
  • Related