How to prevent parent class method access in nested child class in the flutter

How to prevent parent class method access in nested child class in the flutter

Hello Friends

During a development. Sometimes the requirement is parent class method available only in child class. Prevent nested child class to access parent class method.

Now the question is how to achieve this requirement in a flutter?

So using a library, part, and part of in flutter. We achieve this requirement.

Let's start implementation...

Let's first create our parent class and child class. define parent class as a library and child class as a part of the parent class.

library parent_class;

part 'child_class.dart';

class ParentClass {
  _printParentClassName() {
    print("ParentClass");
  }
}

The library keyword is used to create a class as a library. The part keyword is used to indicate the number of files or class parts of this library.

Now let's create our child class.

part of "parent_class.dart";

class ChildClass extends ParentClass {
  ChildClass() {
    _printParentClassName();
    printChildClassName();
  }

  printChildClassName() {
    print("ChildClass");
  }
}

So here we used part of the keyword.

Part of the keyword is used to indicate this class is part of the library. So in this class, We extend our parent class. Now all private and public methods of parent class are available to access in child class.

printChildClassName();
printNestedChildClassName();

Now let's create our nested child class.

import 'package:excel/parent_class.dart';

class NestedChildClass extends ChildClass {
  NestedChildClass() {
    printChildClassName();
    printNestedChildClassName();
  }

  printNestedChildClassName() {
    print(NestedChildClass);
  }
}

So nested child class is not part of the library. So nested child classes have only access to the child class method and public method of the parent class.

Thank you for reading this blog. Hope you all enjoyed it. Please share your feedback and suggestion to learn more.