Skip to main content

prefer-widget-private-members

added in: 1.3.0
⚙️🛠
Pro+

Warns when a widget or widget state have public methods, getter or setters. For widget state, it additionally checks whether its fields are private.

⚙️ Config

Set ignore-static (default is false) to allow widgets to have static public members (example).

Set ignored-names (default is empty) to ignore specific member names (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-widget-private-members:
ignore-static: false
ignored-names:
- some
- name

Example

❌ Bad:

class SomeStatefulWidget extends StatefulWidget {

_someStatefulWidgetState createState() => _SomeStatefulWidgetState();
}

class _SomeStatefulWidgetState extends State<InspirationCard> {
String _privateState;
bool publicState; // LINT: Prefer declaring widget or state class members as private.


void initState() {
super.initState();
}

void _somePrivateCallback() {}

// LINT: Prefer declaring widget or state class members as private.
void somePublic() {}


Widget build(BuildContext context) {
return StatefulWidget();
}
}

✅ Good:

class SomeStatefulWidget extends StatefulWidget {

_someStatefulWidgetState createState() => _SomeStatefulWidgetState();
}

class _SomeStatefulWidgetState extends State<InspirationCard> {
String _privateState;


void initState() {
super.initState();
}

void _somePrivateCallback() {}


Widget build(BuildContext context) {
return StatefulWidget();
}
}

Example with "ignore-static"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-widget-private-members:
ignore-static: true

✅ Good:

class SomeStatefulWidget extends StatefulWidget {

_someStatefulWidgetState createState() => _SomeStatefulWidgetState();
}

class _SomeStatefulWidgetState extends State<InspirationCard> {
static String? someState; // Correct, ignored
}

Example with "ignored-names"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-widget-private-members:
ignored-names:
- someCallback

✅ Good:

class SomeStatefulWidget extends StatefulWidget {

_someStatefulWidgetState createState() => _SomeStatefulWidgetState();
}

class _SomeStatefulWidgetState extends State<InspirationCard> {

void initState() {
super.initState();
}

// Correct, 'someCallback' is ignored
void someCallback() {}


Widget build(BuildContext context) {
return StatefulWidget();
}
}