0

The "interface segregation" principle (the I in SOLID) tells us to keep the API's of our classes as small as necessary. Following this principle I would think you would want to make any properties on a Widget private if they don't need to be accessed outside the widget.

In Flutter you can't define a named property in a constructor with _, so the following is not possible:

// throws: Named parameters can't start with an underscore.
String _somePrivateProperty;
Foo({required this._somePrivateProperty})

You can get around this my making the property positional, OR, you can use constructor lists, as follows:

String _somePrivateProperty;
Foo({required String somePrivateProperty}) : _somePrivateProperty = somePrivateProperty;

Here is my question: I rarely see Flutter example code making properties passed in via a constructor private. Why? Is there something about how Dart works that makes this redundant? If not, am I correct to follow SOLID principles and use constructor lists to init private properties via the constructor?

thecloud_of_unknowing
  • 1,103
  • 14
  • 23
  • I believe using an initializer list is the way to go. See also https://stackoverflow.com/questions/69421872/named-parameters-cant-start-with-an-underscore-on-null-safe-flutter – Ivo Jun 02 '23 at 10:49
  • @Ivo I know using initialiser list is a way to do this. But that wasn't my question. – thecloud_of_unknowing Jun 02 '23 at 13:16
  • Your question literally is "Am I correct .. and use constructor list?". And I say yes – Ivo Jun 02 '23 at 13:18
  • @ivo thanks, but you saying yes isn't a good enough reason to do it. Why do so few examples on line - including Flutter's own classes - make properties private? – thecloud_of_unknowing Jun 02 '23 at 13:22
  • 1
    Good question. I don't know. I'm guessing making as much private as possible is less embraced in Flutter development. Principles are kinda subjective and not everyone agrees about them. Personally I'm also more like "If it doesn't harm being public just let it be public". Private is more for when you really don't want other packages to access it. Also, Dart's `_` isn't really "class private", it's "package private". Define two classes in the same file and you will notice that they can access each other's private properties. Maybe this also plays a role – Ivo Jun 02 '23 at 13:28

0 Answers0