Leave a rating/review
So far, we’ve been creating objects and then setting up values after the fact. This can lead to cases where you might operate on an object before setting it. Now you can promise yourself to be vigilant, but you’re just setting yourself up for an error. Thankfully, we can use a constructor.
A constructor allows us to setup values at the time creation. A constructor is really just a specialized method. You can pass in values to the class which it will use to construct your object. Hence the name, constructor.
Believe it or not, all Dart classes come with a default constructor. It has no parameters and returns a single instance of the class. It’s what we’ve been using all along.
We want to create a custom constructor where we pass in values. A custom constructor allows us to pass in different values, giving us flexibility. But, when we add a custom constructor, we lose our default constructor.
To use multiple constructors, you need to use something known as named constructors which you’ll learn about in a little bit.
We are going to define a user class. This object will have two properties a name and an id. Open dartpad.dev in a browser. Let’s define this class.
class User {
int id = 0;
String name = '';
}
Here we set some default values for now. We’ll clear those out momentarily. First, let’s create an instance of our class. Before we use a constructor, you can also use something called cascade notation. Add the following.
var user = User()
..name = 'Ray'
..id = 42;
This basically combines three operations into a single statement. It creates an object, assigns a name, and then an id. Instead, let’s define our own constructor. But that’s not what this episode. We want to create a constructor. In the User class, add the following:
User(int id, String name) {
this.id = id;
this.name = name;
}
All constructors start with the name of the class followed by the parameters being passed it. After which, we assign the id and name. Notice, that we are using the this keyword. The this is referring to the instance variables versus the parameter being passed into the method.
Let’s remove the this keyword for now.
User(int id, String name) {
id = id;
name = name;
}
Now, in main, we’ll create a new user and print out the id.
var user = User(42, 'ray');
print(user.id);
Now run the program, and the id is zero. This is because the id is being assigned to itself. Adding the this keyword back, we assign the values to the instance variables.
User(int id, String name) {
this.id = id;
this.name = name;
}
Rerun the program and we get the expected result. Notice that we are getting a blue squiggle warning. This is because we are assigning the values in an incorrect manner. In Dart, we assign our values in the constructor signature. Update the constructor to the following:
User(this.id, this.name);
We’ve assigned the id and the name and it works the exact same way. If you need to do additional processing, just put a code block after the constructor.
User(this.id, this.name) {
print('this space for rent');
}
Run the program and you’ll see our message. Nice! Now let’s try to create another user. The keyword being try.
var user2 = User();
Notice that we’ve received a compile error. When we add a constructor to a class, the default constructor goes away. Dart does support multiple constructors, but you have to use named constructors as you’ll see in another video. For now, delete the second user.
Now notice we are setting default value. Once we have a constructor, we don’t have to assign a value when we define the instance variable. Null safety lets us know there must be a value or variable should be declared as nullable. But, since a user object can only be created with a constructor, we can guarantee there will never be null values, thus we can remove the default value.
Update it to the following:
class User {
final int id;
final String name;
User(this.id, this.name);
}
Now once a value has been assigned, it will be locked in place. Nice job.