skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. In the first example:

    It is using shorthand syntax for creating a new map and adding key-value pairs to it.

    In the second example:

    You create an empty map and then add key-value pairs to it using the addAll() 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search