Answer
Overview
Classes are blueprints for creating objects. Objects are instances of classes. Classes bundle data (fields/properties) and behavior (methods) together.
Class Definition
dartclass Person { // Fields (properties) String name; int age; String? email; // Nullable // Constructor Person(this.name, this.age, {this.email}); // Named constructor Person.anonymous() : name = 'Anonymous', age = 0; // Instance method void greet() => print('Hi, I am $name, age $age'); // Getter (computed property) bool get isAdult => age >= 18; // Method with return String introduce() => 'My name is $name. I am $age years old.'; // Static method (class-level) static Person create(Map<String, dynamic> data) { return Person(data['name'], data['age']); } String toString() => 'Person(name: $name, age: $age)'; }
Creating Objects (Instances)
dartvoid main() { // Create objects (instances of Person) final alice = Person('Alice', 28, email: 'alice@example.com'); final bob = Person('Bob', 17); final anon = Person.anonymous(); // Access fields print(alice.name); // Alice print(bob.isAdult); // false alice.greet(); // Hi, I am Alice, age 28 // Static method — called on class, not instance final carol = Person.create({'name': 'Carol', 'age': 30}); print(carol); // Person(name: Carol, age: 30) }
Class Features in Dart
dartclass Product { // Final fields — set once final int id; // Late — initialized later late String _cachedDescription; String name; double price; static int _totalProducts = 0; // Static field — shared across all instances Product(this.id, this.name, this.price) { _totalProducts++; // Runs on every instantiation } // Static getter static int get totalProducts => _totalProducts; // Computed getter String get priceLabel => '₹${price.toStringAsFixed(2)}'; // Operator overloading bool operator ==(Object other) => other is Product && id == other.id; int get hashCode => id.hashCode; }
Class Relationships
dart// Inheritance (is-a) class AdminUser extends User { ... } // Interface (can-do) class Dog implements Trainable { ... } // Mixin (has-behavior) class FlutterDev with CodeStyle, Debuggable { ... } // Composition (has-a) — preferred class Order { final User user; // Has a User final List<Product> items; // Has Products }
Key Concept: Everything in Flutter is a class —
,textWidget,textText,textColumnare all classes. When you writetextStatelessWidget, you're calling thetextText('Hello')class constructor and creating an object.textText