Classes
## Learning Objectives
- Define classes and create objects
- Work with constructors
- Understand factory constructors
- Master static members
- Learn enums and extensions
## Defining Classes
### Basic Class
```dart
class Person {
String name = '';
int age = 0;
void greet() {
print('Hello, I am $name');
}
}
void main() {
var person = Person();
person.name = 'Alice';
person.age = 30;
person.greet();
}
```
### Class with Constructor
```dart
class Person {
String name;
int age;
Person(this.name, this.age);
void greet() {
print('Hello, I am $name');
}
}
void main() {
var person = Person('Alice', 30);
person.greet();
}
```
## Constructors
### Default Constructor
```dart
class Point {
double x = 0;
double y = 0;
}
void main() {
var p = Point();
print('${p.x}, ${p.y}'); // 0, 0
}
```
### Parameterized Constructor
```dart
class Point {
double x;
double y;
Point(this.x, this.y);
}
void main() {
var p = Point(3, 4);
print('${p.x}, ${p.y}'); // 3, 4
}
```
### Named Constructor
```dart
class Point {
double x;
double y;
Point(this.x, this.y);
// Named constructor
Point.origin()
: x = 0,
y = 0;
Point.fromJson(Map json)
: x = json['x'] as double,
y = json['y'] as double;
}
void main() {
var p1 = Point.origin();
var p2 = Point.fromJson({'x': 5.0, 'y': 10.0});
print('${p1.x}, ${p1.y}'); // 0, 0
print('${p2.x}, ${p2.y}'); // 5, 10
}
```
### Constructor with Initializers
```dart
class Person {
String name;
final int birthYear;
Person(this.name, this.birthYear);
// Initializer list
Person.withAge(String name, int age)
: name = name,
birthYear = DateTime.now().year - age;
}
void main() {
var p1 = Person('Alice', 1990);
var p2 = Person.withAge('Bob', 25);
print('${p1.name} born ${p1.birthYear}'); // Alice born 1990
print('${p2.name} born ${p2.birthYear}'); // Bob born 1999
}
```
### Redirecting Constructors
```dart
class Person {
String name;
int age;
// Primary constructor
Person(this.name, this.age);
// Redirects to primary
Person.guest() : this('Guest', 0);
}
void main() {
var guest = Person.guest();
print('${guest.name}, ${guest.age}'); // Guest, 0
}
```
### Constant Constructor
```dart
class ImmutablePoint {
final double x;
final double y;
const ImmutablePoint(this.x, this.y);
}
void main() {
var p1 = const ImmutablePoint(0, 0);
var p2 = const ImmutablePoint(0, 0);
print(identical(p1, p2)); // true (same instance)
}
```
## Factory Constructors
### Singleton Pattern
```dart
class Database {
static final Database _instance = Database._internal();
factory Database() => _instance;
Database._internal();
void query(String sql) {
print('Executing: $sql');
}
}
void main() {
var db1 = Database();
var db2 = Database();
print(identical(db1, db2)); // true (same instance)
}
```
### From Cache
```dart
class Cache {
static final Map _cache = {};
final String key;
factory Cache(String key) {
return _cache.putIfAbsent(key, () => Cache._internal(key));
}
Cache._internal(this.key);
}
void main() {
var c1 = Cache('user');
var c2 = Cache('user');
print(identical(c1, c2)); // true
}
```
## Static Members
### Static Fields
```dart
class Counter {
static int count = 0;
Counter() {
count++;
}
static void reset() {
count = 0;
}
}
void main() {
Counter();
Counter();
Counter();
print(Counter.count); // 3
Counter.reset();
print(Counter.count); // 0
}
```
### Static Methods
```dart
class MathUtils {
static int square(int x) => x * x;
static double circleArea(double radius) =>
3.14159 * radius * radius;
// Can call without instance
}
void main() {
print(MathUtils.square(5)); // 25
print(MathUtils.circleArea(2)); // 12.56636
}
```
## Getters and Setters
### Implicit Getters/Setters
```dart
class Person {
String _name = ''; // Private field
// Implicit getter
String get name => _name;
// Implicit setter
set name(String value) => _name = value;
}
void main() {
var p = Person();
p.name = 'Alice'; // Calls setter
print(p.name); // Calls getter
}
```
### Computed Properties
```dart
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
// Computed property
double get area => width * height;
double get perimeter => 2 * (width + height);
}
void main() {
var rect = Rectangle(5, 10);
print(rect.area); // 50
print(rect.perimeter); // 30
}
```
## Enums
### Basic Enum
```dart
enum Color { red, green, blue }
void main() {
var color = Color.red;
print(color); // Color.red
print(color.index); // 0
// Iterate
for (var c in Color.values) {
print(c);
}
}
```
### Enum with Values
```dart
enum Status {
pending('P'),
active('A'),
completed('C');
final String code;
const Status(this.code);
}
void main() {
print(Status.active.code); // A
}
```
### Enum with Methods
```dart
enum Operation {
add,
subtract,
multiply;
int apply(int a, int b) {
switch (this) {
case Operation.add:
return a + b;
case Operation.subtract:
return a - b;
case Operation.multiply:
return a * b;
}
}
}
void main() {
print(Operation.add.apply(5, 3)); // 8
print(Operation.multiply.apply(5, 3)); // 15
}
```
## Extensions
### Adding Methods to Existing Classes
```dart
extension StringExtension on String {
String capitalize() {
if (isEmpty) return this;
return '${this[0].toUpperCase()}${substring(1)}';
}
bool get isEmail => contains('@');
}
void main() {
print('hello'.capitalize()); // Hello
print('test@email.com'.isEmail); // true
}
```
## Class Modifiers (Dart 3)
### Final Class
```dart
final class FinalClass {
// Cannot be extended
}
// class Extended extends FinalClass {} // Error
```
### Base Class
```dart
base class BaseClass {
void baseMethod() {}
}
// Must implement base class properly
base class Derived implements BaseClass {
void baseMethod() {}
}
```
### Interface Class
```dart
interface class InterfaceClass {
void interfaceMethod() {}
}
// Can implement but not extend
class ImplementsInterface implements InterfaceClass {
void interfaceMethod() {}
}
```
### Sealed Class
```dart
sealed class Result {}
// Subclasses defined in same file
class Success extends Result {}
class Failure extends Result {}
```
## Summary
- Classes: `class Name { fields, constructors, methods }`
- Constructors: default, parameterized, named, factory
- `this.fieldName` for parameter initialization
- `static` for class-level members
- Getters/setters for controlled access
- `enum` for fixed set of values
- `extension` adds methods to existing types
- Dart 3 class modifiers: final, base, interface, sealed
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →