{

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


Private Variable examples in Dart and Flutter

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.

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart