Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum serialization creates nullable type for non-nullable enums #1145

Closed
ssabdb opened this issue May 9, 2022 · 1 comment · Fixed by #1146
Closed

Enum serialization creates nullable type for non-nullable enums #1145

ssabdb opened this issue May 9, 2022 · 1 comment · Fixed by #1146

Comments

@ssabdb
Copy link
Contributor

ssabdb commented May 9, 2022

Using an Enum as a key in a map yields a field with type <String?, dynamic> (rather than the expected <String, dynamic>.

import 'package:json_annotation/json_annotation.dart';

part 'shape_sorter.g.dart';

enum shapeProperty { size, color }

@JsonSerializable()
class ShapeSorter {
  Map<shapeProperty, String> shapeProperties;

  ShapeSorter(this.shapeProperties);
}

This leads to the generated code;

Map<String, dynamic> _$ShapeSorterToJson(ShapeSorter instance) =>
    <String, dynamic>{
      'shapeProperties': instance.shapeProperties
          .map((k, e) => MapEntry(_$shapePropertyEnumMap[k], e)),
    };
    

const _$shapePropertyEnumMap = {
  shapeProperty.size: 'size',
  shapeProperty.color: 'color',
};

This is because _$shapePropertyEnumMap[k] yields type String?, even though the value - I think - is guaranteed to exist in the map. This isn't a major problem unless you have post processing (I'm using FakeFirebaseFirestore, but there could be otherwise).

This causes a problem with anything which is doing null-aware runtime typechecking for Map<String, dynamic>.

json_serializable: "6.2.0"

@ssabdb
Copy link
Contributor Author

ssabdb commented May 9, 2022

Potentially resolved by #1146

@ssabdb ssabdb changed the title Using an enum as a key in a map leads to incorrect type in toJson() Enum serialization creates incorrect type May 10, 2022
@ssabdb ssabdb changed the title Enum serialization creates incorrect type Enum serialization creates nullable type May 10, 2022
@ssabdb ssabdb changed the title Enum serialization creates nullable type Enum serialization creates nullable type for non-nullable enums May 10, 2022
kevmoo pushed a commit that referenced this issue Jun 25, 2022
#1146)

Before this change, serializing non-nullable enums in a subtype was incorrectly producing nullable string types.

For example, serializing a class member of type Map<enum, String> produced a type Map<String?, dynamic> where Map<String, dynamic> should have been produced.

Nullable enums should still produce nullable types, eg. serializing List<enum?> should produce List<String?>

fixes #1145
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant