Flutter: check if a list contains only a certain value

833

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"));
Share:
833
Admin
Author by

Admin

Updated on January 03, 2023

Comments

  • Admin
    Admin over 1 year

    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' !");
    }
    
    • pskink
      pskink about 2 years
      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."
    • Arslan Kaleem
      Arslan Kaleem about 2 years
      use list.contains method like state_str_list.contains("value");
    • lava
      lava about 2 years
      List<String> state_str_list = ["Validated", "Draft", "Draft", "Waiting", "Validated"].where((element) => element.contains("Validated")).toList();
    • pskink
      pskink about 2 years
      @lava he wants a true / false boolean, not a list - this is where List.every should be used, not List.where
    • lava
      lava about 2 years
      var d = ["Validated", "Draft", "Draft", "Waiting", "Validated"] .contains("Validated");
  • pskink
    pskink about 2 years
    or more simple: _list.every((element) => element == e);