google / google/json_serializable.dart

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

Open
#1,304 1 comment 1 reaction 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

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

```dart
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 json) =>
_$FailureFromJson(json);

final String message;

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

Map toJson() => _$FailureToJson(this);
}
```

```text
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.

```dart
Failure({
required this.message,
this.stackTrace,
});
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.