Static Methods (aka Class Methods) and Variables

Dart includes the concept of class variables and methods, though it takes a dim view of them. It regards them as a necessary evil, which, of course, they are. These are introduced with the static keyword.

classes/static_methods.dart
 
class​ Planet {
 
static​ List rocky_planets = ​const​ [
 
'Mercury'​, ​'Venus'​, ​'Earth'​, ​'Mars'
 
];
 
static​ List gas_giants = ​const​ [
 
'Jupiter'​, ​'Saturn'​, ​'Uranus'​, ​'Neptune'
 
];
 
static​ List ​get​ known {
 
var​ all = [];
 
all.addAll(rocky_planets);
 
all.addAll(gas_giants);
 
return​ all;
 
}
 
}

Invoking a static method is just like invoking an instance method, except the class itself is the receiver.

 
Planet.known
 
// => ['Mercury', ...

Get Dart 1 for Everyone now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.