Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help me understand fromMap and toMap from this code?

Tags:

flutter

dart

I got this code from the internet and I can not seem to understand it or find anything on the internet for it.

In the code below toMap is a method that returns 2 items, How is that possible?

And what is fromMap, is it a user created method? I thought methods used {} or => so it is a bit confusing.

Also, what is the key here for the Map? Can the map only store 2 categories of items? One is the key and the other is the value. Or it can have one key but multiple categories of values.

For example, there might be a single unique key, which could help take out the task title, time, reminder data, notes, etc as values of the map.

class Task {
  String title;
  bool completed;

  Task({
    this.title,
    this.completed = false,
  });

  Task.fromMap(Map<String, dynamic> map): title = map['title'],completed = map['completed'];

  updateTitle(title) {
    this.title = title;
  }

  Map toMap() {
    return {
      'title': title,
      'completed': completed,
    };
  }
}
like image 461
AriGold Avatar asked Oct 02 '19 10:10

AriGold


3 Answers

In the code below toMap is a method that returns 2 items, How is that possible?

No, it returns a Map (with two items). More about maps can be found here.

And what is fromMap, is it a user created method? I thought methods used {} or => so it is a bit confusing.

Task.fromMap(Map<String, dynamic> map) is called "named constructor". The : title = map['title'],completed = map['completed'] part is initializer list

like image 88
janstol Avatar answered Oct 14 '22 00:10

janstol


My understanding is;

In fromMap, you retrieve the title and completed from some map, and save it in your local variables.

In the toMap you take the saved values in your local variables and can return a Map.

The key is whatever you put you chose it to be, but here you chose one key to be titleand one to be completed.

Does this help you?

like image 26
Thor Avatar answered Oct 14 '22 01:10

Thor


First of all we discuss about FormMap So what is fromMap()? whenever you have any api and at firetime you will get json format so when you want to convert that data into any class format then you have to do like

Map temp = json.decode(response.body);

so your function can understand map key and retrieve that value and set in class local variable and now Second point is toMap So what is toMap()? Whenever you want to post something into api or somewhere you have map data so you can post in api like

Abc a = Abc(name:"hari",address:"india");
a.toMap();
like image 31
Hardik Kumbhani Avatar answered Oct 13 '22 23:10

Hardik Kumbhani