Class Variables & Methods
This lesson covers Dart's Class level variable(s) and method(s).
Introduction
The variables and methods of a class are shared across all instances of the class. They are not called on any specific object instance of the class.
In the Dart language, there are two ways to implement such variables and methods.
- Using the
static
keyword - Without the
static
keyword
The class-level variable(s) is useful to declare constants and implement a class-wide state. Generally, utility classes use class variables and methods to provide quick and easy access to methods and constants.
With the static
keyword
The static
keyword is used to declare class level variables and methods.
The class methods can be called from other classes using the class names they are defined in.
Let’s take an example of a string utility class called StringUtils
. This class contains a convenience method called reverse(String str)
to reverse the given string. This utility class has a constant dart
which is inferred to contain a string value of “oh dart.”
class StringUtils {
static const dart = "oh dart";
static String reverse(String str) {
return String.fromCharCodes(str.runes.toList().reversed);
}
}
Note: If you are interested in learning about runes
used in code above to reverse the string, check out my article on Runes.
Using a Class variable
Let’s reiterate the facts about class variables:
- Static variables are not initialized until they are used.
- They are useful for representing class state and constants.
- Constants names are declared using the lowerCamelCase convention.
- The class-level variable can be accessed using the class name.
In the code below, StringUtils
is needed to access constant dart
.
Get hands-on with 1400+ tech skills courses.