Reputation: 1556
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.
Upvotes: 1
Views: 128
Reputation: 25030
In the first example:
It is using
shorthand syntax
for creating a new map and addingkey-value
pairs to it.
In the second example:
You create an empty map and then add
key-value
pairs to it using theaddAll()
method.
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 new map
and add key-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.
Upvotes: 1
Reputation: 4576
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
Upvotes: 1
Reputation: 420
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.
Upvotes: 1
Reputation: 1119
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.
Upvotes: 1