I am trying to reverse Map values. But didin’t get proper one,
here my Map
Map<String, dynamic> details = {
"sms": {
"very_low": false,
"low": false,
"medium": false,
"high": false,
"very_high": true
}
};
I want to get like this ;
{
sms: {
very_high: true,
high: false,
medium: false,
low: false,
very_low: false
}
}
If Anyone please share your ideas
4
Answers
Let’s say this is your "map":
You can use this
extension
:and use it like this:
A solution that works for any
Map
no matter how much nested it is:usage:
Prints:
Please note that this only works because
Map
behind the scenes constructs aLinkedHashMap
that is insertion-ordered. If you construct other types ofMap
that are not, this may not work. Generally speaking, it might be wise to not rely on the order of items in aMap
because it is not guaranteed unless you created theMap
yourself.Since this looks like it should be JSON: don’t bother sorting this. It is supposed to be a machine-to-machine protocol, machines do not care if it looks neat. The less uneccessary code you write, the less bugs you produce.