devashish-patel
devashish-patel

Reputation: 723

How to convert Class object to data structure `Map` or a `List of Maps` in Dart?

How to convert an Object type to a Map or a List of Maps in Dart, so the variables become key/value pairs?

Upvotes: 44

Views: 61924

Answers (4)

Edie Kamau
Edie Kamau

Reputation: 270

You can check out this package class_to_map

import 'package:class_to_map/class_to_map.dart';
class Test {
  String val1 = "value 1";
  int val2 = 2;
  Map val3 = {"a": "another value"};
}
print(Test().toMap());

// converting map to class
{"val1": 'value 1', "val2": 2, "val3": {"a": "another value"} }.toClass<Test>();

Upvotes: 2

Terblanche Daniel
Terblanche Daniel

Reputation: 1465

This is a much easier and error-prone-free approach, (And if you are already using these classes as DTO objects that need to be serialized this is a double win).

Add the following 3 dependenciess in your pubsec.yaml

dependencies:
  flutter:
    sdk: flutter
  json_annotation:^3.1.1

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^1.10.11
  json_serializable: ^3.2.5

In the class that you want to get the Map for do the following.

part 'person.g.dart';

@JsonSerializable(explicitToJson: true)
class Person{
String name;
String surname;
Person(this.name,this.surname);

//make sure you have the (Just change part of the method name to your class name)

 factory Person.fromJson(Map<String, dynamic> json) =>
      _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);//Replace 'Person' with your class name


}

That's it, you then just have to run the following command in your terminal so flutter can generate the "toMap()" method for you.

flutter pub run build_runner build --delete-conflicting-outputs

Then use it like such.

var person =Person('somename','some surname');//This is object
Map personMap =person.toJson();

Ez. This is a much better approach especially if you have complex objects with multiple objects inside. Just make sure that each nested object contains these changes as well (JsonSerializable annotation, the 'part 'class.g.dart'' , and the 2 methods)

NOTE: that if property changes are made to the classes, just run this command again.

flutter pub run build_runner build --delete-conflicting-outputs

Upvotes: 8

abgd1712
abgd1712

Reputation: 70

You can try this:

var data = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
};

var myMap = Map<String, dynamic>.from(data);
print(myMap);

With dynamic in Map<String, dynamic> we can have the values of the map of any type. In the example above, it is String.

Upvotes: -1

Haqqi
Haqqi

Reputation: 1079

Based on my experience, dart does not provide that kind of system yet. So, basically we create function like toMap() that manually convert the object to a key-value pair of map.

For example:

class Human {
  String name;
  int age;

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'age': age,
    };
  }
}

So, later when you have a Human object, you just can call human.tomap().

I do this in most of my entity classes.

Upvotes: 79

Related Questions