Bỏ qua để đến nội dung

Class và Object

🎯 Mục tiêu: OOP cơ bản với class trong Dart.


class Person {
String name;
int age;
Person(this.name, this.age);
void greet() {
print("Hello, I'm $name");
}
}
void main() {
var person = Person("Alice", 25);
person.greet();
}

class User {
final String id;
String name;
int _age = 0; // Private (underscore)
User(this.id, this.name);
int get age => _age;
set age(int value) {
if (value >= 0) _age = value;
}
}

class Point {
final double x;
final double y;
final double distance;
Point(double x, double y)
: x = x,
y = y,
distance = sqrt(x * x + y * y);
}

class UserModel {
final String id;
final String name;
final String? avatar;
const UserModel({
required this.id,
required this.name,
this.avatar,
});
}

  • Dùng this. trong constructor
  • _ prefix cho private
  • Getters và setters