Iman Kamali
Iman Kamali

Reputation: 47

How to make toMap and fromMap method for Enums class dart flutter?

I used an enum variable in a class. Now I want to implement the toMap and fromMap methods for the class.

enter code here
enum ColorNumber { inc, dec, none }


class CounterState extends Equatable {
  int value;
  ColorNumber ColorNumber;
  CounterState({this.value, this.colorNumber});
  @override
  List<Object> get props => [value, colorNumber];

  Map<String, dynamic> toMap() {
    return {
      'value': value,
      'colorNumber': colorNumber.toMap(),   //error to toMap
    };
  }

  factory CounterState.fromMap(Map<String, dynamic> map) {
    return CounterState(
      value: map['value'],
      none: ColorNumber.fromMap(map['colorNumber']),   //error to fromMap
    );
  }

}

Upvotes: 1

Views: 2605

Answers (2)

David Timothy
David Timothy

Reputation: 31

While the above method worked, I had problems trying to send the toMap value to an api as it would send an integer and not the value,This worked for me:

 enum FormType {
  pre,
  post,
}


    class NewClass {
  final FormType assessmentForm;
  NewClass({
    required this.assessmentForm,
  });

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

  factory NewClass.fromMap(Map<String, dynamic> map) {
    return NewClass(
      assessmentForm: FormType.values.byName(map['assessmentForm']),
    );
  }

  String toJson() => json.encode(toMap());

  factory NewClass.fromJson(String source) =>
      NewClass.fromMap(json.decode(source) as Map<String, dynamic>);
}

Upvotes: 3

Nikhil Badyal
Nikhil Badyal

Reputation: 1697

Simple store the enum as int representing thier position.

See below

Map<String, dynamic> toMap() {
    return {
      'value': value,
      'colorNumber': colorNumber.index, 
    };
  }
factory CounterState.fromMap(Map<String, dynamic> map) {
    int val = map['colorNumber'];
    return CounterState(
      value: map['value'],
      colorNumber: ColorNumber.values[val],  
    );
  }

Upvotes: 6

Related Questions