Programming in Dart: Classes

Jun 28 2022 · Dart 2.17, Flutter 3.0, DartPad

Part 1: Understand Classes

02. Create a Class

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: 01. Introduction Next episode: 03. Challenge: Create a Custom Class
Transcript: 02. Create a Class

Dart is known as an object oriented language. This means, we use objects as a way to organize our code. But what does this even mean? Well, when you start writing a program, you end up breaking that program into smaller tasks. For instance, some parts of the program will respond to user input. Other parts will save or load data. Other parts may even fetch things over a network and so forth.

Now we could write our code in one giant long list but that quickly becomes unwieldy. Rather, we break each task down into a objects that handle one specific thing.

These objects are basically metaphors that we use to define a task. These objects should do only one thing because that is their task. That’s an object, but you often hear the word class thrown around with it.

A class represents the template for the object. We create individual objects from our class definition. The class is just the definition. You think of a class like a cookie cutter.

The class creates cookies, but each cookie is unique. One cookie may have red frosting.

Another may have green frosting. But they all share the same characteristics of their shape. Another example are role playing games. When you make a character, you often pick a class such as a fighter, wizard, or bard. Each character is unique but a wizard can cast spells whereas a fighter swings a sword.

When we define a class, we give it state and behavior. This is just a fancy way of saying, we can give it variables and functions. The object will remember the variables throughout the life of the object. Best still, you can pass around objects into other objects and all that state and behavior go with it.

Okay, that was a lot of information. Let’s go see classes and objects in action.

To get started, open a browser and head over to DartPad.dev. If you have code already present that’s not the example code, click the New Pad button and select the Dart option. Then click create. Alternatively, you can click the reset button to clear the old code.

We’re going to create a person class that will keep track of the person’s first name and the person’s last name.

We will start by defining a new class. We use the class keyword followed by the class name. By convention, we start our class name with an uppercase.

class Person {

}

Everything in our class is defined in the braces. Okay, next we’re going to give it a couple of variables. These are also called instance variables or properties. We’re going to set them to empty strings.

var firstName = '';
var lastName = '';

We can actually set them to nothing as opposed to an empty string, but you’ll learn about that when we work with constructors. Now we want to create a method that will say the person’s name. We will call this sayHello.

void sayHello() {
    print('Hello, my name is $firstName $lastName');
}

Here we are referring to the properties. If you place this method outside of the class, you’d get an error because variables only have scope inside the class. Try it out. Move it outside and you’ll see that you get an undefined error.

Okay, move it back. It’s time to create a couple of people. First let’s create a weatherman.

var weatherMan = Person();

To create an instance of an object, you simply put the class name followed by parenthesis. That object is stored in the variable. We will set the weatherman’s name to Phil Connors.

weatherMan.firstName = 'Phil';
weatherMan.lastName = 'Connors';

We access each instance variable by putting a period after the variable name, followed by the name of the instance variable. And that’s it! If you wanted to print just the first name, you’d do the same.

print(weatherMan.firstName);

In our case, we’re using our sayHello method so let’s delete that line. Let’s also make a singer. This time I’m going to create a person using the new keyword.

var singer = new Person();

This used to the be the way to create objects in Dart. As for Dart 2, you no longer need the new keyword. You may see this used in older code, but for new code, it’s a good idea not to use the new keyword.

var singer = Person();

Okay, now lets assign the first name and the last name.

singer.firstName = 'Janet';
singer.lastName = 'Joplin';

Now let each one say hello. We do the same thing we do when access an instance variable except we are using a function. When referring to functions on objects, we call them methods.

weatherMan.sayHello();
singer.sayHello();

Now run the program. Both people say hello.

Now, you may be wondering why we wrote a sayHello method that printed out the first name and last name versus just using a print statement to print out the first name and last name You can do this and it may be fine in some situations. Generally speaking, a good idea is to let the object manage its own state. As a benefit, other parts of your code can now use that sayHello method.

Also, when writing your class methods, you want to keep them small. If you find yourself writing a lot of code in a single method, a good idea is to break that method into smaller methods as a way to organize your code.

As you can see, object orientated programming isn’t just about learning syntax, but there’s a lot of best practices and design patterns as well. Don’t worry about learning them all at once. It will all come in time.