Sobes.tech
Junior

What are the access modifiers in Dart language?

sobes.tech AI

Answer from AI

In the Dart language, access modifiers are not present in the traditional sense (public, private, protected). Access control is implemented at the library (file) level.

  • Visibility within a file (module): All identifiers (variables, functions, classes, methods) that do not start with an underscore (_) are public and accessible outside the file in which they are declared.
  • Visibility within a library (file): Identifiers starting with an underscore (_) are "private" within the file (library) in which they are declared. They are not accessible from other files.

Example:

// file_a.dart

class PublicClass {
  // Public method
  void publicMethod() {
    print("This is a public method.");
  }

  // Private variable - accessible only within file_a.dart
  String _privateVariable = "Private variable";

  void accessPrivate() {
    print("Accessing private variable from the same file: $_privateVariable");
  }
}

// Public function
void publicFunction() {
  print("This is a public function.");
}

// Private function - accessible only within file_a.dart
void _privateFunction() {
  print("This is a private function.");
}
// file_b.dart - imports file_a.dart

import 'file_a.dart';

void main() {
  var publicObj = PublicClass();
  publicObj.publicMethod(); // Accessible
  //publicObj._privateVariable; // Error: _privateVariable is not accessible
  publicObj.accessPrivate(); // Accessible, as the method publicMethod is in PublicClass

  publicFunction(); // Accessible
  //_privateFunction(); // Error: _privateFunction is not accessible
}