Search code examples
listdartfluttercontains

Display items in a list containing a specific name - flutter


In this list, I want to display out all the items that contains this specific name.

My list items: ['US', 'SG', 'US']

print(list.contains("US"));

Using .contains() returns me a true or false but it doesn’t return me the list of strings that contains that. I want to only extract out the items that has 'US' from the list. In this case, there's 2 of it. Please help!


Solution

  • You can try doing it the following way -

    List<String> myList = ['US', 'SG', 'US'];
    print(myList.where((item) => item.contains("US")));
    

    You can also display it directly inside a Text widget in the following way -

    Text(
       myList.where((item) => item.contains("US")).join(" "),
       //The join function joins the elements of the Iterable into a single string with the separator provided as an argument.
    ),
    

    Hope this helps!

    UPDATE:

    To display each of the word separately as a list you can display them inside a Column in the following way -

    Column(
      children: myList.map((value) {
        if(value.contains("US")){
          return Text(value,);
        } else {
          return Container();
          //Return an empty Container for non-matching case
        }
      }).toList(),
    )
    

    The same thing can be used inside a ListView instead of Column if you want it to be scrollable.