0

I am using Freezed for serialization. I need to get the colour from the database which is String like this "#FFFFFF". I need when I get this string, converting it to int to as a colour. but I get the error:

I/flutter ( 4483): ** [Error] type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast. isError: [true]

The code is:

@freezed
class Categories with _$Categories {
  factory Categories({
    required int id,
    @ColorResponseConverter() required int colour,
  }) = _Categories;

  factory Categories.fromJson(Map<String, dynamic> json) =>
      _$CategoriesFromJson(json);
}

the code of the converter is:

class ColorResponseConverter implements JsonConverter<int, Map<String, dynamic>> {
  const ColorResponseConverter();

  @override
  int fromJson(Map<String, dynamic> json) {
    if (json['color'] != null) {
      return int.parse((json['color'] as String).replaceFirst("#", "0xFF"));
    } else {
      return 0xFFFFFFFF;
    }
  }

  @override
  Map<String, dynamic> toJson(int color) =>
      {"color": color.toString().replaceFirst("0xFF", "#")};
}

1 Answers1

0

From database was return type Map of string dynamic but not String like you example.

Use debug mode:

  • put a break point on line where you have 'int fromJson(Map<String, dynamic> json) {'. And check what data you got.
Ronya
  • 19
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '22 at 05:45