CodeBlanks Logo Icon CodeBlanks

Instance variables

Learn to declare instance variables in a class.

Instance variables

Instance variables are pieces of data held by each instance of a class. They are declared inside the class body. Example: class User { String name; int age; }.

You reach them through the instance with a dot: u.name, u.age. Each instance has its own values; two User objects may have different name fields.

An instance variable can have an initial value: String name = 'Guest';. Or it is set in the constructor. If the type is non-nullable, either an initial value or a constructor assignment is required.

Non-nullable instance variable

If an instance variable is non-nullable, you must give it an initial value or assign it in the constructor. Otherwise it is a compile error. Example: class User { String name = 'Guest'; } — name always has a value.

A constructor assignment is enough too: class User { String name; User(this.name); }. Here the constructor forces name, so it can stay non-nullable.

Making it nullable lifts the requirement: String? name; starts as null. Pick based on your data; null safety was the topic of the previous group.

Practice User with two fields

Define a User class with String name and int age fields. Write the constructor User(this.name, this.age). Inside main create a User('Ayşe', 28) instance and print name and age on separate lines.

Starter code

main.dart
void main() {
  // define the User class

  // create an instance and print both fields
}

Sample solution

main.dart
class User {
  String name;
  int age;
  User(this.name, this.age);
}

void main() {
  var u = User('Ayşe', 28);
  print(u.name);
  print(u.age);
}

Expected output

Ayşe
28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Two User instances' name?

  • Each has its own value Correct answer
  • Throws
  • Share the same value
  • Becomes null

Explanation: each instance has its own values.

2 Two fields

Question
class User {
  String name;
  ____ age;
}
Answer
class User {
  String name;
  int age;
}

Explanation: Use the integer type for age.

3 Match the field types

Term Meaning
String name Text
int age Integer
double score Decimal
bool active Boolean

All lessons in Beginner