I was seeing that when you generate the .toMap
return function in a Model
, you could return the map as follows:
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
};
}
However, in new versions I see code from people who do it in the following way :
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'id': id});
result.addAll({'name': name});
return result;
}
But I would like to know what are their differences or which one is more optimal.
4
Answers
There is no any difference in terms of result of the functions.
But I prefer first one as it has fewer code and you are just creating and returning Map at once.
In second way, you are creating an empty Map then adding items to it.
I am not sure about it, but I think it is less optimal in terms of hardware resource using, as there are more actions than first way.
No any difference but first one is very optimal because in second you are defining a variable and so variable can initialise and then return.
You can choose either of these two ways to do this. You just choose the one you like better.
If I have to choose, I will choose the old one, because the data in it is ready when the map returns the result, and the second one needs to add an empty map, adding data one by one
In the first example:
In the second example:
Both ways are perfectly fine and will produce the same result. It’s mostly a matter of personal preference and coding style.
In terms of
performance
, both ways are equivalent, as they both create a newmap
and addkey-value
pairs to it. So you can choose the one that you feel more comfortable with.In my opinion, the first one is cleaner and readable but the second one is more explicit and could be more useful if you need to add some more logic or check some conditions before adding the
key-value
pairs.