Reputation: 593
How can I convert map to list of objects in flutter.
Sample data,
Model (
key1: value1,
key2: value2,
key3:value 3,
)
Expected result,
[0]: Model {key1:value1},
[1]: Model {key2:value2},
[2]: Model {key3:value3}
Upvotes: 4
Views: 3490
Reputation: 366
class SomeDataClass {
final String option1;
final String option2;
final String option3;
final String option4;
final String option5;
const SomeDataClass({
@required this.option1,
@required this.option2,
@required this.option3,
@required this.option4,
@required this.option5,
});
factory SomeDataClass.fromMap(Map<String, dynamic> map) {
return SomeDataClass(
option1: map['option1'] as String,
option2: map['option2'] as String,
option3: map['option3'] as String,
option4: map['option4'] as String,
option5: map['option5'] as String,
);
}
Map<String, dynamic> toMap() {
return {
'option1': this.option1,
'option2': this.option2,
'option3': this.option3,
'option4': this.option4,
'option5': this.option5,
};
}
}
void main(){
final optionsList = [
{
'option1': 'you can use fromMap and toMap methods',
'option2': 'you can use some serialization libraries such as metinoned in opton 3',
'option3': 'json_serializable',
'option4': 'I am going to show you the from and to map method',
'option5': 'good luck',
}
// there could be other options in the list.
];
final someMappedObjectList = <SomeDataClass>[];
for(var map in optionsList){
final someObject = SomeDataClass.fromMap(map);
someMappedObjectList.add(someObject);
}
// now you can use the someMappedObjectList.
}
Upvotes: 1