language
language copied to clipboard
Static nested classes
Allow declaring a class in the body of another class.
class Person {
class Occupation {
String jobTitle;
Occupation(this.jobTitle);
String named(String name) =>
moniker(Person(name, this));
}
String name;
Occupation occupation;
Person(this.name, this.occupation);
static String moniker(Person p) =>
'${p.name} The ${p.occupation.jobTitle}';
}
Person p = Person("Rosie", Person.Occupation("Riveter"));
I'd expect that Occupation
is not an instance variable of Person
, if that would even be a sensible notion in Dart, instead the outer class acts as a namespace containing the inner class. The inner class cannot be accessed from a Person
instance. The inner class cannot capture instance variables from the outer class. It can howewer access static methods and fields.
Nested classes could be used for:
- Indicating a relationship between classes / encapsulating classes which only serve to complement another (e.g. Flutter
StatefulWidget
s and their respectiveState
s) - Creating arbitrary namespaces like
export _ as _
but without a library declaration file - Encapsulating many related methods under a namespace