{

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 a 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 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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example