Open In App

Dart – Private Properties

Last Updated : 24 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A property is a field variable declared inside a class. There are three types of properties in Dart:

  • Read-only Property: You can only read these values, access to modifying them is not given
  • Write-Only Property: New Values can be set, but do not allow access to their values.
  • Read/Write-Only Property: Full access to read and modify these values is permitted.

In this article, we will understand what private properties are?

Private Properties are those properties that are accessible only inside the file they are defined or the class they are declared. Dart provided privacy at the library level rather than class level due to which keywords like public, private, and protected are not used, unlike most languages. Identifiers starting with an underscore “_” are visible inside the dart library. Thus, all the private properties inside dart are declared with an underscore at the start of their name. For instance,  A class is created with the name Fruit that contains a private property _hidden and a method FruitRun(). The file is named “ex.dart”

class Fruit {
  String _hidden = "";

  FruitRun() {
    print('String value: $_hidden');
    _hidden = "Mango";
    print('String value: $_hidden');
  }
}

In another file with the main method defined, to import the previous class inside the file use the .dart extension with the file name added previously i.e. “file_name.dart”.

import 'ex.dart';

void main() {
  var b = new Mango();
  b.testB();
}

class Mango extends Fruit {
  late String _hidden;

  testB() {
    _hidden = 'Heya';
    print('String value: $_hidden');
    FruitRun();
    print('String value: $_hidden');
  }
}

There are a few special points to keep in mind while working with dart:

  • Making a class private would never make its member privates. 
  • Making a class does not make its instances inaccessible.
  • In case a field is hidden from the user and is not being used openly, it is preferable to make it a private property

Implementation

Dart




class Code {
  String web_name = "GeeksforGeeks";
  int _hidden_id = 0;
  int platform_id = 1;
}
  
void main() { 
  Code name = Code();
  print(name.web_name);    // web_name ----> GeeksforGeeks
  print(name._hidden_id);  // Hidden Id ---> 0
  print(name.platform_id); // Platform Id ---> 1   
}


Output:

Output

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads