flutter enum to json

To convert a Flutter enum to JSON, you can use the toJson() method. Here's an example:

enum Color {
  red,
  green,
  blue,
}

class Example {
  Color color = Color.blue;

  Map<String, dynamic> toJson() {
    return {
      'color': color.toString().split('.').last,
    };
  }
}

In this example, we have an enum called Color with three values: red, green, and blue. We also have a class called Example that has a property color of type Color.

The toJson() method converts the color property to a JSON representation. It does this by calling toString() on the color property, which returns a string representation of the enum value. We then use split() to remove the enum prefix (e.g., Color.) and get the last part of the string. Finally, we create a map with the key 'color' and the enum value as the corresponding value.

To use this, you can create an instance of the Example class and call its toJson() method:

Example example = Example();
Map<String, dynamic> json = example.toJson();
print(json); // Output: {'color': 'blue'}

This will print the JSON representation of the color property, which in this case is {'color': 'blue'}.