Leave a rating/review
A few episodes back, we created RPGCharacter class.
We defined a constructor that took in its name as well as the stats. This is good when you have the stats already pre-generated, but sometimes, you’ll want to provide other options. For instance, you may want to provide another option where the caller just passes in the character name and have the character attributes be all set to ten.
Dart allows us to do this by way of named constructors. We create a constructor by providing a name. We can also define parameters as well. Finally, we must make sure to initialize all variables that aren’t declared as nullable. We do this by way of an initialization list which we just learned in the previous episode.
Interestingly enough, when you call a named constructor, you put the name of it almost like you are calling a method. Let’s play around with named constructors.
To get started, open up DartPad.dev. Let’s recreate our User class that we created in a previous episode.
class User {
int id;
String name;
User(this.id, this.name);
}
Here we have our user class that has a simple constructor that takes in an id and a name. We want to provide another option to allow for anonymous users. Let’s create an anonymous constructor. First, let’s define the name.
User.anonymous()
This isn’t taking an parameters. But we’re getting an error since we have two non-nullable instance variables not being initialized. Let’s do this now.
User.anonymous() : id = 0, name = 'anonymous';
Now we can create an anonymous user. First let’s create a normal one.
var user1 = User(42, 'Ray');
Now for our anonymous one.
var user2 = User.anonymous();
Finally, we’ll print out both of their names.
print(user1.name);
print(user2.name);
Run the program. As you can see, we have Ray as a user and we also have an anonymous user. Nice work!