Dart| Flutter How to: Create a private variable with example

This tutorial shows how to write and declare private variables in Dart.

Dart Private Variables

There is no private keyword or private variables in Dart.

In dart, you can declare a variable name with an underscore(_) as a private variable.

Private variables are accessed inside the same class, not outside the classes or files.

In Dart, you can declare private variables in the classes


class Employee {
  int _privateVariable = 0;
  int id = 11;

  displayMessage() {
    print('$_privateVariable'); // 0
    print('$id'); // 11
  }
}

void main() {
  Employee employee = Employee();
  print(employee._privateVariable);
  print(employee.id);
}

The above code is defined in the single file

Declared a private variable ie added an underscore before a variable(_) in a class.

You can access the private variables inside the class as well as the same file.

The same concept in java throws an error, as variables declared in the class are not accessible outside classes.

In Dart, you can access the private variables in the same file, even though variables are declared in a different class.

In Dart, private variables have special use in libraries to provide privacy

let’s use the private variables in a library

Declare the hr library in the hr.dart file.

library hr;

class Employee {
  int _privateVariable = 0;
  int id = 11;

  displayMessage() {
    print('$_privateVariable'); // 0
    print('$id'); // 11
  }
}

void main() {
  Employee employee = Employee();
  print(employee._privateVariable);
  print(employee.id);
}

use hr.dart library in the sales.dart file

private variables declared hr library is not accessible in other classes

The below code throws an error if you try to access the private variable.

Here is a code

import 'hr.dart';

void main() {
  Employee emp = Employee();
  emp.displayMessage(); // this works

  print(emp._privateVariable); // throws compile time error
  print(emp.id);
}

You can use private variables in dart or flutter on libraries to provide privacy.