google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 393 forks source link

Can't create constructor with required nullable property and ignored in to/from json #1304

Open MiniSuperDev opened 1 year ago

MiniSuperDev commented 1 year ago

I want to serialized this class, and I want that the property be required to have static analysis when I used so I don't forget to assign it.

The default value when de/serialize should be null

import 'package:json_annotation/json_annotation.dart';

part 'failure.g.dart';

@JsonSerializable()
class Failure {
  Failure({
    required this.message,
    required this.stackTrace,
  });

  factory Failure.fromJson(Map<String, dynamic> json) =>
      _$FailureFromJson(json);

  final String message;

  @JsonKey(
    includeFromJson: false,
    includeToJson: false,
    defaultValue: null,
  )
  final StackTrace? stackTrace;

  Map<String, dynamic> toJson() => _$FailureToJson(this);
}
Cannot populate the required constructor argument: stackTrace. It is assigned to a field not meant to be used in fromJson.

This work if is not required, but I need to be required because in code I ever want to assign it, the only case when not is in serialization.

    Failure({
    required this.message,
    this.stackTrace,
  });
mvarendorff commented 1 year ago

What value should stackTrace have when serialized from json?