Tags

, , , , ,

Learn Dart the Hard Way

To implement class-wide variables and methods, we use the static keyword. Static variables are also called class variables. Let us first see a code snippet and after that, we will discuss the advantages and disadvantages of static variables and methods.

//code 7.1
// static variables and methods consume less memory
// they are lazily initialized
class Circle{
static const pi = 3.14;
static Function drawACircle(){
//from static method you cannot call a normal function
print(pi);
}
Function aNonStaticFunction(){
//from a normal function ou can call a static meethod
Circle.drawACircle();
print("This is normal function.");
}
}
main(List arguments){
var circle = Circle();
circle.aNonStaticFunction();
Circle.drawACircle();
}

And here is the output:

3.14
This is normal function.
3.14

As you see, static variables are useful for class-wide state and constants. So in the main() method we can add this line at the end:

main(List arguments){
var circle = Circle();
circle.aNonStaticFunction();
Circle.drawACircle();
print(Circle.pi);
}

And get the value of constant ‘pi’ again. Here, ‘Circle.pi’ is the class variable. And the class method is: ‘Circle.drawACircle();’. The biggest advantage of using static variables and methods is it consumes less memory. An instance variable once instantiated, consumes memory whether it is being used or not. The static variables and methods are not initialized until they are used in the program. It consumes memory when they are used.

A few things to remember:

1. From a normal function, you can call a static method.
2. From a static method, you cannot call a normal function.
3. In a static method, you cannot use the ‘this’ keyword. It is because the static methods do not operate on an instance and thus do not have access to this.

So, in the end, we can conclude that using static variables and methods depend on the context and situations. In the next part of the book, where we will build native iOS and Android mobile apps with the help of Flutter framework, you will see how and when we use static variables and methods.