google/protobuf.dart

FEATURE: Only optional fields nullable in generate message constructor

Opened this issue · 0 comments

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:

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:

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.