A Dart constructor is a special function that initialises the variables in the class. Dart uses the class name to name the constructor.
Besides, since a constructor is a function, we can pass parameters through it.
However, the number of parameters may vary. Number of parameters changes with the number of the variables.
We will see that in a minute.
For example we consider a class Car.
Let’s see the code first, after that, we will discuss the code.
class Car {
int accelerator;
int _speed = 0;
int get speed => _speed;
int gear;
Car(this.accelerator, this.gear);
int brake(int applyPressureOnBrake) {
_speed -= applyPressureOnBrake * 10;
return _speed;
}
int accelerate(int pressureOnAccelerator) {
_speed += 10 * pressureOnAccelerator;
return _speed;
}
@override
String toString() => 'Car: $_speed mph';
}
void main() {
var bike = Car(0, 0);
print(bike);
bike._speed = bike.accelerate(2);
print('When the pressure on Accelerator is 2, the speed is ${bike._speed}');
bike._speed = bike.brake(2);
print('When the pressure on Brake is 2, the speed is ${bike._speed}');
}
In the previous section we have seen how we can use the private variable by using the get method.
Let us run the code. And see the output first.
Car: 0 mph
When the pressure on Accelerator is 2, the speed is 20
When the pressure on Brake is 2, the speed is 0
Let us look at the member variables first. Between three, one is private.
As a result, we have made it public by using the get method so that we can use them later.
int _speed = 0;
int get speed => _speed;
Not only that, according to the rule, we have declared a constructor and passed two variables as its parameters.
Car(this.accelerator, this.gear);
As an outcome, when we create an object, we need to pass two values.
Initially, when the car has no accelerator and no gear, it has no speed.
var bike = Car(0, 0);
print(bike);
// output: Car: 0 mph
However, when we call the methods, the output changes.
How the dart methods work, we’ll discuss in the next section.
So stay tuned.
Leave a Reply