Flutter: What is MyClass_.() ? aka Private Constructor 2022

Oflutter Private Constructor

While reading some Flutter blogs or watching Flutter tutorials, you might see that some developers are using _.() aks private constructor after creating a Class. And you might be wondering what is [MyClass] _.() do and why we even need it? As a quick answer _.() – is a Private Constructor. But let’s dive into more details about the private constructor.

Defenition – Private Constructor _.()

Private Constructor – is an exclusive instance constructor that restricts this class from being instantiated in other classes. This class is mainly used when you need to have static members only e.g static variables or static methods.

For example, in Flutter (Dart), you might want to use a static method such as a convertDateTime(String datetime) converter from String to DateTime which you gonna use within the whole app. Another example is when you want to have static custom Colors which also will be used somewhere in your flutter app when designing UI.

You might ask, what is the purpose of having only static variables or methods (functions)? Well, the static methods and variables belong to the class but not to the class objects which means that it can be invoked without using a class object. For example, when having a regular class constructor, you would have to invoke a class object e.g final initMyClass = MyClass(); And then, you would use initMyClass to access some data or methods like initMyClass.getAge. However, if you have a private constructor, you directly access the static methods or variables without creating an object e.g MyClass.getAge.

Coding example – How to create a Private Constructor?

To create a private constructor you should type ClassName._(); after creating a class.

class MyClass {
  MyClass._();
}

Now, we can create some static methods. For example, let’s have a static method that converts double to N decimal points.

class MyClass {
  MyClass._();
  
  /// Round double to specific decimal
  static double toDecimal(double value, int decimal){
    return double.parse(value.toStringAsFixed(decimal));
  }
}

As you can see inside MyClass we have created a simple static method that takes two arguments one is a value, and the second one is a decimal number for which we want to round.

Next, let’s try to call this method from main.dart file

main(){
  double longNumber = 159.2381927403827192385941;
  
  print(MyClass.toDecimal(longNumber, 3));
  
  // Output: 159.238
}

As you can see, we did not invoke any class object or instantiated MyClass class, we accessed the toDecimal method directly from main.dart file and as the output, we have 159.238.

When should I use private constructor ._()?

As we have talked about earlier, you should use the private contractor when you need to create static variables or methods.

For example, we can create a private contractor if we want to have a custom app color scheme. This is commonly used while developing the flutter app. It’s very useful to manage the color schemes using private constructor

class AppColors {
  AppColors._();
  
  static const Color purpleColor = Color(0xFF7C6BEA);
  static const Color darkRedColor = Color(0xFF4D1325);
    
}

Or if you want to create a static method like show alert dialog. Usually, developers create a separate class AppUtils where they create a static method such as alert dialog or convert some date time e.g if you receive a date-time from the database as milliseconds or seconds (int) you can create a static method that takes input as integer and convert it to date time. But let’s continue with the alert dialog.

class AppUtils{
  AppUtils._();
  
   static AlertDialog showAlertDialog({
    required String title,
    required Widget content,
    required Function() action1,
    required Function() action2,
 
  }) {
    return AlertDialog(
      title: Text(title),
      content: content,
      actions: [
        TextButton(onPressed: action1, child: const Text('Action 1')),
        TextButton(onPressed: action2, child: const Text('Action 2'))
      ],
    );
  }

}

And now, we can use our AppColors.purpleColor to change a UI color somewhere in the app or use AppUtils.showAlertDialog().

Conclusion

Now you know a bit more about private constructors and what does _.() mean. I hope you found this article useful!

By the way! Check out my youtube video: Link

You May Also Like

Leave a Reply

Your email address will not be published.

two × 1 =