Home > Back-end >  Why do state's class variable are often done as private in Flutter?
Why do state's class variable are often done as private in Flutter?

Time:12-13

Why do state's class variable are often done as private? What are the cases when using public variables is bad for state classes? Who is going to use variable from state class like this: _SplashState.storage?

class _SplashState extends State<Splash> {
  var_storage = Storage(); // it could be public

CodePudding user response:

It's not necessary to create the State as private but it makes sense. The State class should be private indicating it should not be created anywhere outside createState override, as you are not creating/managing State object instance at all.

We can also say that it's good practice to declare a variable as private which is not to be accessed outside of the scrop.

CodePudding user response:

Private fields have the advantage that Lint can identify which fields were declared or instantiated and not used, which helps identify human errors.

If you declare a public field, the field can be accessed by outside classes, so Lint cannot warn you if you added the field by mistake.

  • Related