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.
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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