Programming in Dart: Classes

Jun 28 2022 · Dart 2.17, Flutter 3.0, DartPad

Part 1: Understand Classes

07. Define Multiple Constructors

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 06. Utilize Initialization Lists Next episode: 08. Create Static Members

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 07. Define Multiple Constructors

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!