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', 'Venus', 'Earth', 'Mars', |
| // 'Jupiter', 'Saturn', 'Uranus', 'Neptune' ] |
Interestingly, instance methods can treat static methods as if they are other instance methods.
classes/mix_static_and_instance_methods.dart | |
| class Planet { |
| // ... |
| static List get known { ... } |
| String name; |
| Planet(this.name); |
| bool get isRealPlanet => |
| known.any((p) => p == this.name); |
| } |
In the previous code, the instance method isRealPlanet invokes the static method known just like it would any instance method. In this way, we can find that Neptune is a real planet but Pluto is not.
| var neptune = new Planet('Neptune'); |
| var pluto = new Planet('Pluto'); |
| neptune.isRealPlanet // => true |
| pluto.isRealPlanet // => false |
Recipe 12 | Warning: Because Dart treats static methods as instance methods in this fashion, it is illegal to have an instance method with the same name as a class method. |
3.149.213.44