What is private variable in Dart?

We declare a private variable in Dart by the (_) sign inside a class. Like variables, we can also make a method private. 

Dart doesn’t have keywords like, public, private or protected.

But why do we need to make a variable private?

There are many reasons to do that. 

One of the reasons is with a private variable we can work within the class. 

However, outside the class, when we try to use the private variable, it raises errors.

Let’s see a simple Dart code.

class Bear {
  final int _age;
  //int get age => _age;
  int height;

  Bear(this._age, this.height);
}

void main(List<String> args) {
  var bear = Bear(2, 3);
  print('Age of bear: ${bear._age} year.');
  print('Age of bear: ${bear.height} feet.');
}

The above code will give us outputs. 

Why?

Because we have made it public by passing through the constructor.

The same way, we can access the private variable inside the same class library.

Although we have not declared it public, still it works.

As a result, it doesn’t raise any errors.

Let’s see an example.

class Bear {
  int _age = 0;
  //int get age => _age;
  int height = 0;
}

void main(List<String> args) {
  var bear = Bear();
  bear._age = 1;
  bear.height = 3;
  print('Age of bear: ${bear._age} year.');
  print('Age of bear: ${bear.height} feet.');
}

// this is not raising error because we call the private property inside the class library

Here is one interesting point to note. Dart treats every small app, like we see above, as a library.

As a result, we can import the Bear class as follows. 

import 'bear_second.dart';

void main(List<String> args) {
  var bear = Bear();
  bear.height = 3;
  bear._age
  /// this will raise error
  /// the getter _age isn't defined
}

However, it will not work anymore. Now we are trying to access a private variable outside the class library.

Not only in Dart, but also in many Flutter apps like the Mobile App we’ve been building we will find this implementation.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

TensorFlow, Machine Learning, AI and Data Science

Twitter

Comments

3 responses to “What is private variable in Dart?”

  1. […] In our previous discussion we have seen how we can make a member variable private. […]

  2. […] In the previous section we have seen how we can use the private variable by using the get method. […]

  3. […] In the last section we have discussed the private member variable in Dart.  […]

Leave a Reply