FEATURE: Only optional fields nullable in generate message constructor
- Dominant language
- Dart
- Stars
- 572
- Forks
- 196
- Avg merge
- 1h 59m
- Merged PRs (30d)
- 2
Description
**Description**:
Currently, in the Dart protobuf implementation, all fields are nullable in the constructor of message classes, even if they are not optional. This makes it hard to know before runtime if a required field has been assigned, which can lead to runtime errors and harder-to-debug code.
I propose adding a feature that enforces nullability checks in the constructor of message classes based on whether the fields are optional or required. This would make it easier for developers to ensure that all required fields have been assigned before runtime.
**Example**:
Consider the following .proto file:
```protobuf
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
optional string address = 3;
}
```
The generated Dart code should have a constructor that enforces null checks for required fields, like so:
```dart
class Person extends $pb.GeneratedMessage {
Person({
required String name,
required int age,
String? address,
}) : super() {
this.name = name;
this.age = age;
if (address != null) {
this.address = address;
}
}
// ... rest of the generated code ...
}
```
This would allow developers to ensure that required fields have been assigned before creating an instance of the message class, preventing runtime errors and making the code more robust.
Contributor guide
Research direction
No source file or test is named; start by tracing the Dart protobuf generator that emits message-class constructors and compare its handling of optional fields with the example. Done means generated constructors require non-optional fields while leaving optional fields nullable, matching the proposed Person output.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100