4

I need to know if there are only string equals to "Validated" in the list, how can I check it in 1 line of code ? (If the list is empty, I already checked the condition before so this particular case isn't important).

List<String> state_str_list = ["Validated", "Draft", "Draft", "Waiting", "Validated"];
if (???) {
    print("all values in state_str_list are equals to 'Validated' !");
}
5
  • 1
    check List.every method - the docs say: "Checks whether every element of this iterable satisfies test. Checks every element in iteration order, and returns false if any of them make test return false, otherwise returns true." Commented Feb 24, 2022 at 11:32
  • use list.contains method like state_str_list.contains("value"); Commented Feb 24, 2022 at 11:49
  • List<String> state_str_list = ["Validated", "Draft", "Draft", "Waiting", "Validated"].where((element) => element.contains("Validated")).toList(); Commented Feb 24, 2022 at 12:42
  • @lava he wants a true / false boolean, not a list - this is where List.every should be used, not List.where Commented Feb 24, 2022 at 12:46
  • var d = ["Validated", "Draft", "Draft", "Waiting", "Validated"] .contains("Validated"); Commented Feb 24, 2022 at 12:51

1 Answer 1

6

Thanks to you, I came to this:

contains_only(var _list, var e) {
  _list.every((element) => element == e);
}
print(contains_only(["Validated", "Draft", "Draft", "Waiting", "Validated"], "Validated"));
Sign up to request clarification or add additional context in comments.

1 Comment

or more simple: _list.every((element) => element == e);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.