flutter
flutter

Reputation: 6786

Convert class variables to a map in dart

class A extends State<A>{
String name1 = '';
String name2 = '';
String name3 = '';

}

I've 3 methods that return Strings that are assigned to the variables with a setState. What is the best way to put these values in the map like this

{'name1': 'Tom',
 'name2':'Mike',
 'name3':'Jim'
}

Upvotes: 2

Views: 930

Answers (1)

NqbraL
NqbraL

Reputation: 573

You can do a function like this :

Map<String, dynamic> toMap() => {
  'name1': this.name1,
  'name2': this.name2,
  'name3': this.name3,
};

Sample how to use it :

final itemA = A('myName 1', 'myName 2', 'myName 3');
Map<String, dynamic> myMap = itemA.toMap();

I use this function to convert my object to a json personally.

Upvotes: 3

Related Questions