Skip to content
DeveloperMemos

What Are Underscore Variables in Dart?

Dart, Programming, Variables1 min read

In Dart, using an underscore (_) as a prefix for a variable or identifier gives it a private status. This means that the variable or identifier is intended for internal use within the library or file where it's defined. By using underscore variables, developers can clearly indicate which components are meant to be private and not exposed for external consumption(in other languages an actual "private" keyword exists). This practice promotes encapsulation and helps prevent unintended access or modification from other parts of the codebase.

Example of Underscore Variables

Let's consider a simple example to illustrate the use of underscore variables:

1class _InternalData {
2 String _secretKey = 'abc123';
3
4 void _processData() {
5 // Perform data processing
6 }
7}
8
9void main() {
10 var data = _InternalData();
11 print(data._secretKey); // This will result in a compilation error
12 data._processData(); // This will result in a compilation error
13}

In the above example, the _InternalData class contains a private variable _secretKey and a private method _processData. Attempting to access these private members from outside the class, such as in the main function, will result in compilation errors, emphasizing their restricted visibility.

Benefits of Using Underscore Variables

The use of underscore variables offers several benefits:

  1. Encapsulation: By marking variables or identifiers as private, developers can hide implementation details and prevent direct access from external code, promoting better encapsulation.

  2. Code Clarity: The presence of underscore variables provides clear visual cues about the intended scope of specific components, aiding in code comprehension and maintenance.

  3. Avoidance of Name Collisions: Using underscore variables reduces the likelihood of naming conflicts with external libraries or frameworks, as private components are kept separate from public interfaces.