0

I have a simple map:

Map<String, bool> selection = {};

Then the entries are added. At some point, I want to reset the selection, i.e.:

for (var name in selection.keys) {
   selection[name] = false;
}

Is there a way to reset all values to false, using only one statement in Dart?

For example, the following statement is very convenient and concise to check if the selection is not empty:

if( selection.values.contains(true) )

So, I'm looking for something similar to reset all the values to false.

Rk: Out of scope answers ;-) :

  • forEach
  • writing a method/function to do the stuff

Addendum

Just found and tested this one:

selection.updateAll((name, value) => value = false);

But there could be something even more simple, i.e. without a lambda function.

Jacques
  • 301
  • 2
  • 13
  • It might make sense to use a `Set` instead of a `Map`. You can call `.clear()` in order to reset. https://api.dart.dev/stable/2.16.1/dart-core/Set/clear.html – mmcdon20 Mar 22 '22 at 03:00

1 Answers1

3

selection.forEach((name, value) => selection[name] = false);

I think this is what you are looking for. A simple one-liner solution.

Edit

selection.updateAll((name, value) => value = false);

is also an option, as you have added

Apart from those, there is no predefined method that allows you to achieve what you have described.

davdog00
  • 93
  • 2
  • 13
  • Gotcha! :-D I wrote that, obviously, forEach was out of scope. It just put the same stuff on one line. It is not more readable. Rk. For some reason Dart integration in Visual Studio Code often advices to replace "forEach" loops by "for in" loops. I don't know why (readability? efficiency? functional syntax?...) but they seem to consider the "for in" loop as a better practice. – Jacques Mar 21 '22 at 16:49
  • Well, answering your question, there is no pre-defined statement that allows you to do what you want :( The syntax in a `forEach` loop is highlighted because of readability only (lint settings). You can turn them off in `analysis_options.yaml` – davdog00 Mar 21 '22 at 16:51
  • That's my conclusion as well, but I wondered if I was missing something. – Jacques Mar 21 '22 at 16:53
  • 1
    @Jacques `for-in` is more performant, but IMO the main reason you should prefer `for-in` over `.forEach` is because `for-in` plays well with control flow keywords like `break`, `continue`, `return`, and `await`, and `.forEach` does not. See https://stackoverflow.com/questions/65884531/dart-how-to-break-foreach-in-if and https://stackoverflow.com/questions/50336082/how-to-return-from-a-foreach-loop-in-dart and https://stackoverflow.com/questions/63719374/how-to-wait-for-foreach-to-complete-with-asynchronous-callbacks – mmcdon20 Mar 22 '22 at 03:18