Programming in Dart: Classes

Jun 28 2022 · Dart 2.17, Flutter 3.0, DartPad

Part 1: Understand Classes

08. Create Static Members

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: 07. Define Multiple Constructors Next episode: 09. Utilize Enumerations

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: 08. Create Static Members

When you define a class, you define methods and properties for that class. Each instance of the class maintains its own state. This is useful, but there are times that you want to keep track of items on a class level.

For this, we use the static keyword. Static means the variable is associated with the class itself. You don’t even need an instance of the class available to access it.

Whereas an instance variable will hold a value for the object who owns it, a class member exists for the entire class.

Now an easy beginning mistake is to create a static method, and then start interacting with the your object methods or object variables. You can’t do this. A static method or property exists on the class and it has no idea about individual instances.

Static properties are used a lot. Often times, you’ll define static constants that is used in your objects. That way, you are only dealing with one value versus creating and removing that value with each object. Static methods are often used as utility methods. You’ll see them used all the time. Lets see static in action.

To get started, we’re going to revisit our User class. Open up DartPad.dev and let’s add the following code:

class User {
  final int id;
  final String name;
  
  User(this.id, this.name); 
  User.anonymous() : id = 0, name = 'anonymous';
}

User.maxAttribute

This is where we last worked on it. We have an id and a name as well as a constructor and a named constructor. With the named constructor, we can convert the id and the name to use static constants.

static const anonymousUserId = 0;

Here we’ve defined an anonymous user id. This is a constant set to zero. Now lets add the name.

static const anonymousUserName = 'anonymous';

Now we update our anonymous constructor to use our static variables.

User.anonymous() : id = anonymousUserId, name = anonymousUserName;

Our constructor is looking much better. But there’s something to keep in mind. The static variables can be accessed outside of the class without a class instance. Let’s print out the anonymous user id.

void main() {
  print(User.anonymousUserId);
}

In a lot of ways, the static method looks a lot like a named constructor. We always must preface the class name. Except in this case, it doesn’t make sense that an external class should access the anonymousUserId. That’s an implementation detail for the User.

Most languages have some sort of access control. So in a language like Swift, we’d do something like this:

private static const anonymousUserId = 0;

Dart does have access control but it occurs on the library level. In Dart, a library is a Dart app. We mark private items with an underscore before the name.

static const _anonymousUserId = 0;
static const _anonymousUserName = 'anonymous';

This indicates a private field and that it shouldn’t be used outside the class. But of course, being it is still part of the same library, we can still access it.

print(User._anonymousUserId);

However, this would not be the case had we imported this code. In general, if you find yourself accessing private members outside the class, then you need to reevaluate either the way you are accessing those members is correct or whether they should even marked as private. That way, your code is consistent with you and any external folks who import it.

Okay, you’ve seen static properties. Let’s make a static method. Often times, you’ll be converting strings to base64 as a way to transfer data over a network. Let’s create an encode method. First, we need to import the convert library.

import 'dart:convert';

Now let’s define our encode method.

static String encode(User user) {

}

Here we are passing in a user. Even though the method is part of the User class, it has no idea about each individual user. In fact, let’s try to print out name.

print(name);

You’ll see we run into an error that informs us that we can’t access instance members inside of a static method. This is because when this method is called, there is no instance of an object. Let’s now encode the string.

final encodedString = utf8.encode(user.name);
final base64String = base64.encode(encodedString);
return base64String;

Don’t worry about what is going here. We’re simply converting our string from text and into binary which is compact and more efficient when sending over a network.

Now let’s encode our user name. This is a class method so we preface the class first.

User.encode();

Then we pass in the user.

User.encode(user)

And we print out the result.

print(User.encode(user));

Now run the program. We get our name encoded.