Sobes.tech
Junior

How to develop a Dart class so that all its fields are accessible only within the class itself and are not accessible from outside?

sobes.tech AI

Answer from AI

class _MyPrivateClass {
  // Field accessible only within this class and file.
  String? _privateField;

  // Constructor is also private.
  _MyPrivateClass(this._privateField);

  // Method accessible only within this class and file.
  void _privateMethod() {
    print('This is a private method.');
  }

  // Example getter, which can be public,
  // but returns the value of the private field.
  String? get publicGetter => _privateField;

  // Example public setter.
  set publicSetter(String? value) {
    _privateField = value;
  }
}

// Another class in the same file can access private members.
class AnotherClassInSameFile {
  void accessPrivateClass() {
    var privateInstance = _MyPrivateClass('Hello');
    print(privateInstance._privateField); // Access is allowed
    privateInstance._privateMethod(); // Access is allowed
  }
}

// In another file:
// import 'your_file_name.dart'; // Import the file

// void main() {
//   var privateInstance = _MyPrivateClass('Hello'); // Error: _MyPrivateClass is not accessible
//   print(privateInstance._privateField); // Error: _privateField is not accessible
// }
How to develop a Dart class so that all its fields… - sobes.tech