Skip to content

Add private set property modifier #4206

Open
@tilucasoli

Description

@tilucasoli

Introduce a property-level modifier similar to Swift’s private(set) functionality. This would allow a class to expose a property for reading externally while restricting write access.

Motivation

In Swift, a common pattern is to declare properties as public private(set), which makes them publicly readable but only privately (or internally) writable. However, Dart does not have a similar feature, so we have to create a private variable along with a getter to achieve the same functionality.

Swift Example:

public class SomeClass {
    public private(set) var count: Int = 0
    
    public func increment() {
        count += 1
    }
}

Dart Example:

class SomeClass {
  int _count = 0;
  
  int get count => _count;
  
  void increment() {
    _count++;
  }
}

Proposed Solution

_set

class SomeClass {
  // Publicly readable, privately writable
   _set int count = 0;

  void increment() {
    count += 1; // Allowed
  }
}

// Outside SomeClass
void main() {
  final obj = SomeClass();
  print(obj.count); // Allowed
  // obj.count = 5; // Not allowed: write access is private
}

@nonVisibleSet

Alternatively, a annotation-based could be another option.

class SomeClass {
  @nonVisibleSet
  int count = 0; // read from anywhere, write only from within this class
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions