Dart Classes and Objects
A class is a core concept of object-oriented programming; it is an abstract description of things in the real world.
An object is a concrete instance of a class. This chapter introduces class definitions, constructors, member variables and methods, getter/setter, and static members in Dart.
Class Definition and Instantiation
A class is a template for creating objects, defining what properties (data) and behaviors (methods) the objects have.
Example
// Define a User class
class
User
{
// Member variables (properties)
String name
=
''
;
int
age
=
0
;
// Member methods (behaviors)
void
introduce
(
)
{
(
'Hello, I am $name, $age years old this year.'
)
;
}
bool
isAdult
(
)
{
return
age
=
18
;
}
}
void
main
(
)
{
// Instantiation: use the new keyword (Dart 2.0+ allows omitting new)
var
user1
=
User
(
)
;
user1.
name
=
'runoob'
;
user1.
age
=
10
;
// Access member variables and methods
(
'Username: ${user1.name}'
)
;
user1.
introduce
(
)
;
(
'Is adult: ${user1.isAdult()}'
)
;
// Create another object; they are independent of each other
var
user2
=
User
(
)
;
user2.
name
=
'Xiao Ming'
;
user2.
age
=
20
;
user2.
introduce
(
)
;
}
用户名: runoob
你好,我是 runoob,今年 10 岁。
是否成年: false
你好,我是 小明,今年 20 岁。
Starting with Dart 2.0, the new keyword is optional during instantiation. The community convention is to omit new to keep code concise. All subsequent examples in this tutorial will omit new.
constructor
A constructor is a special method automatically called when an object is created, used to initialize the object's state.
Dart provides multiple forms of constructors, which are very flexible.
Default constructor
If you do not define a constructor, Dart automatically provides a parameterless default constructor.
Ordinary constructor
Example
class
Student
{
String name
;
int
age
;
// Ordinary constructor: same name as the class
Student
(
String name
,
int
age
)
{
this
.
name
=
name
;
this
.
age
=
age
;
}
void
printInfo
(
)
{
(
'Student: $name, age: $age'
)
;
}
}
void
main
(
)
{
var
s1
=
Student
(
'runoob'
,
10
)
;
var
s2
=
Student
(
'Xiao Ming'
,
15
)
;
s1.
printInfo
(
)
;
s2.
printInfo
(
)
;
}
学生: runoob, 年龄: 10
学生: 小明, 年龄: 15
Syntactic sugar constructor
When constructor parameters are directly assigned to member variables, Dart provides a shorthand syntax.
Example
class
Student
{
String name
;
int
age
;
// Syntactic sugar: this.paramName automatically assigns the parameter to the same-named member variable
// This is more concise than manually writing this.name = name
Student
(
this
.
name
,
this
.
age
)
;
void
printInfo
(
)
{
(
'RUNOOB student: $name, age: $age'
)
;
}
}
void
main
(
)
{
var
s
=
Student
(
'runoob'
,
10
)
;
s.
printInfo
(
)
;
}
RUNOOB 学生: runoob, 年龄: 10
Named constructor
A class can have multiple named constructors for different initialization logic.
Example
class
Point
{
double
x
;
double
y
;
// Default constructor
Point
(
this
.
x
,
this
.
y
)
;
// Named constructor: create the origin point
Point.
origin
(
)
:
x
=
0
,
y
=
0
;
// Named constructor: create from a single value (x and y are the same)
Point.
diagonal
(
double
value
)
:
x
=
value
,
y
=
value
;
@override
String toString
(
)
=>
'Point($x, $y)'
;
}
void
main
(
)
{
var
p1
=
Point
(
3
,
4
)
;
var
p2
=
Point.
origin
(
)
;
var
p3
=
Point.
diagonal
(
5
)
;
(
'RUNOOB coordinates: $p1, $p2, $p3'
)
;
}
RUNOOB 坐标: Point(3.0, 4.0), Point(0.0, 0.0), Point(5.0, 5.0)
Initialize the list
The initializer list runs before the constructor body executes; it is used to initialize final fields or validate parameters.
Example
class
Person
{
final
String name
;
// final fields must be initialized in the constructor
final
int
birthYear
;
final
int
age
;
// Initializer list: after the colon and before the function body
// The initializer list runs before the constructor body executes
Person
(
this
.
name
,
this
.
birthYear
)
:
age
=
2026
birthYear
,
// computed property
assert
(
birthYear
1900
,
'Unreasonable birth year'
)
;
// Assertion check
void
printInfo
(
)
{
(
'RUNOOB user: $name, born: $birthYear, age: $age'
)
;
}
}
void
main
(
)
{
var
p
=
Person
(
'runoob'
,
2016
)
;
p.
printInfo
(
)
;
// The following line triggers an assert failure (in development mode)
// var p2 = Person('error', 1800);
}
RUNOOB 用户: runoob, 出生: 2016, 年龄: 10
assert only takes effect in debug mode and is ignored in release mode. It is used to find logic errors early during development.
Member Variables and Methods
Member variables store an object's state; member methods define its behavior.
Example
class
BankAccount
{
// Private member: starts with an underscore, accessible only within this file
String _accountNumber
;
double
_balance
=
0
;
// Public member
String ownerName
;
BankAccount
(
this
.
ownerName
,
this
._accountNumber
)
;
// Public method
void
deposit
(
double
amount
)
{
if
(
amount
0
)
{
_balance
=
amount
;
(
'Deposit ¥$amount, current balance: ¥$_balance'
)
;
}
}
bool
withdraw
(
double
amount
)
{
if
(
amount
0
&&
amount
<=
_balance
)
{
_balance
=
amount
;
(
'Withdraw ¥$amount, current balance: ¥$_balance'
)
;
return
true
;
}
(
'Insufficient balance, withdrawal failed'
)
;
return
false
;
}
// Private method: for use only inside the class
void
_logTransaction
(
String type
,
double
amount
)
{
(
'[Internal log] $type: ¥$amount'
)
;
}
}
void
main
(
)
{
var
account
=
BankAccount
(
'RUNOOB'
,
'6222-0000-1234'
)
;
account.
deposit
(
1000
)
;
account.
withdraw
(
300
)
;
account.
withdraw
(
800
)
;
// Insufficient balance
// Private members cannot be accessed from outside
// print(account._balance); // Error: _balance is private
}
存入 ¥1000,当前余额: ¥1000
取出 ¥300,当前余额: ¥700
余额不足,取款失败
Getter and Setter
Getter and Setter are special methods for reading and writing member variables.
They let you run extra logic when accessing a property while keeping the concise property-access syntax.
Example
class
Circle
{
double
_radius
;
// Private variable storing the radius
Circle
(
this
._radius
)
;
// Getter: get the diameter (computed property)
double
get
diameter
=>
_radius
2
;
// Getter: get the area
double
get
area
=>
3.14159
_radius
_radius
;
// Getter and Setter together: expose the radius property to the outside
double
get
radius
=>
_radius
;
set
radius
(
double
value
)
{
// Validation logic can be added in the Setter
if
(
value
<=
0
)
{
throw
ArgumentError
(
'Radius must be greater than 0'
)
;
}
_radius
=
value
;
}
// Read-only Getter: no corresponding Setter
String
get
info
=>
'Circle(radius: $_radius)'
;
}
void
main
(
)
{
var
circle
=
Circle
(
5
)
;
// Use the Getter (just like accessing a normal property)
(
'RUNOOB circle: ${circle.info}'
)
;
(
'Diameter: ${circle.diameter}'
)
;
(
'Area: ${circle.area.toStringAsFixed(2)}'
)
;
// Use the Setter
circle.
radius
=
10
;
(
'Diameter after change: ${circle.diameter}'
)
;
// Trying to set an invalid value throws an exception
// circle.radius = -1; // Throws ArgumentError
}
RUNOOB 圆形: 圆(半径: 5.0)
直径: 10.0
面积: 78.54
修改后直径: 20.0
The advantage of Getter and Setter is that the caller does not need to know whether radius is a simple field or a computed property. If you later need to add validation logic to radius, you only need to change the field into a getter/setter, and the calling code needs no modification. This is the benefit of "encapsulation".
Static Members
Static members belong to the class itself, not to a particular instance of the class.
All instances share the same static variable, and static methods can be called without creating an object.
Example
class
Counter
{
// Static variable: shared by all instances
static
int
totalCount
=
0
;
// Instance variable: each instance is independent
String label
;
Counter
(
this
.
label
)
{
// Each time an instance is created, the static counter increases by 1
totalCount
++
;
}
// Static method: called via the class name
static
void
printTotal
(
)
{
(
'RUNOOB total instances: $totalCount'
)
;
}
// Static methods are often used for utility functions
static
bool
isValidLabel
(
String label
)
{
return
label.
isNotEmpty
&&
label.
length
<=
20
;
}
}
void
main
(
)
{
// Static method: called directly via the class name, no instance needed
(
'Is label valid: ${Counter.isValidLabel('
test
')}'
)
;
var
c1
=
Counter
(
'Counter A'
)
;
Counter.
printTotal
(
)
;
// 1
var
c2
=
Counter
(
'Counter B'
)
;
var
c3
=
Counter
(
'Counter C'
)
;
Counter.
printTotal
(
)
;
// 3
// Static variable: accessed via the class name
(
'Final count: ${Counter.totalCount}'
)
;
}
标签是否有效: true
RUNOOB 总实例数: 1
RUNOOB 总实例数: 3
最终计数: 3
Static methods cannot access instance members (because there is no this). Static methods are suitable for utility functions and factory logic, but do not overuse them - static methods cannot be overridden by subclasses, and overuse reduces code testability and flexibility.