How to Create Private Variables in Dart

How to Create Private Variables in Dart?

Earlier we have been through what is the difference between the “const” and “final” keywords in Dart. And now it’s time to go through How to Create Private Variables in Dart.

In Dart, creating private variables is an essential technique for encapsulating and securing your code. This blog post walks you through the process of defining private variables in Dart, ensuring that they are accessible only within their respective classes or libraries. Discover the benefits of private variables, including improved code organization, reduced coupling, and enhanced data protection. With step-by-step instructions and code examples, you’ll gain the knowledge and skills to create private variables effectively in your Dart projects. Elevate your code quality and maintainability by implementing this fundamental concept. Don’t miss out on this valuable resource for Dart developers seeking to optimize their code structure and security.

How to Create Private Variables in Dart?

From Dart documentation:

” Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private to its library ”

Libraries not only provide APIs but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.

A few words about libraries:

” Every Dart app is a library, even if it doesn’t use a library directive. The import and library directives can help you create a modular and shareable code base ”

You may have heard of the part directive, which allows you to split a library into multiple Dart files.

Privacy in Dart exists at the library, rather than the class level.

If you were to put class A into a separate library file (eg, other.dart), such as:

library other;

class A {
  int _private = 0;

  testA() {
    print('int value: $_private');  // 0
    _private = 5;
    print('int value: $_private'); // 5
  }
}

and then import it into your main app, such as

import 'other.dart';

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


class B extends A {
  String _private;

  testB() {
    _private = 'Hello';
    print('String value: $_private'); // Hello
    testA();
    print('String value: $_private'); // Hello
  }
}

You get the expected output:

String value: Hello
int value: 0
int value: 5
String value: Hello

That’s just not how Dart is intended to be written, partly because library-private members make it easier to define operators like ==. (Private variables of a second object couldn’t be seen for the comparison.

If one class has no business seeing variables on another class, you might ask yourself whether they really belong in the same library:

//This should be in a separate library from main() for the reason stated in the main method below.

    class MyClass {
      //Library private variable
      int _val = 0;

      int get val => _val;
      set val(int v) => _val = (v < 0) ? _val : v;

      MyClass.fromVal(int val) : _val = val;
    }

    void main() {
      MyClass mc = MyClass.fromVal(1);
      mc.val = -1;
      print(mc.val); //1

      //main() MUST BE IN A SEPARATE LIBRARY TO 
      //PREVENT MODIFYING THE BACKING FIELDS LIKE:
      mc._val = 6;
      print(mc.val); //6
    }

Though you technically aren’t allowed to create private variables, you could emulate it using the following closure technique.

Conclusion:

Thanks for Reading !!! Hope you liked the topic 🙂

In this article, we have been through how to create private variables in dart.

Keep Learning !!! Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields