Skip to content

[bug] json_serializable is unable to handle enum with generics #1507

@lucavenir

Description

@lucavenir

Hello there.

Try this out:

import 'package:json_annotation/json_annotation.dart';

part 'asdlol_dto.g.dart';

enum Slug<T> {
  asd<String>(),
  lol<int>(),
  rofl<double>(),
  lmao<(int, int)>();

  const Slug();
}

@JsonSerializable()
class Serializable<T> {
  const Serializable(this.slug);
  final Slug<T> slug;
}

JsonSerializable generates this code:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'asdlol_dto.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Serializable<T> _$SerializableFromJson<T>(Map<String, dynamic> json) =>
    $checkedCreate('Serializable', json, ($checkedConvert) {
      final val = Serializable<T>(
        $checkedConvert('slug', (v) => $enumDecode(_$SlugEnumMap, v)),
      );
      return val;
    });

Map<String, dynamic> _$SerializableToJson<T>(Serializable<T> instance) =>
    <String, dynamic>{'slug': _$SlugEnumMap[instance.slug]!};

const _$SlugEnumMap = {
  Slug.asd: 'asd',
  Slug.lol: 'lol',
  Slug.rofl: 'rofl',
  Slug.lmao: 'lmao',
};

But the above errors at analysis time, since _$SlugEnumMap is incorrectly typed.

The argument type 'Map<Slug<Object>, String>' can't be assigned to the parameter type 'Map<Slug<T>, String>'. [[argument_type_not_assignable](https://dart.dev/tools/diagnostics/argument_type_not_assignable?utm_source=dartdev&utm_medium=redir&utm_id=diagcode&utm_content=argument_type_not_assignable)]

I'm not sure what I can do on my end to fix of even to circumvent this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions