Member-only story
Class in Dart
A class in Dart is like a blueprint for creating objects. It groups related data and functions together, making code more organized and reusable.
Read Medium Story for free 👇
Why Use Classes?
- Organised Code: Classes help group related data and behaviour together.
- Reusability: You can create multiple objects from a single class.
- Encapsulation: keeps data safe and prevents unintended changes.
- Inheritance: One class can inherit properties and methods from another.
Defining a Class
A class has properties (variables) and methods (functions). Let’s start with a simple example:
class Person {
String name;
int age;
// Constructor to initialize values
Person(this.name, this.age);
// Method to introduce the person
void introduce() {
print('Hello, my name is $name and I am $age years old.');
}
}
void main() {
Person p1 = Person('Alice', 30);
p1.introduce(); // Output: Hello, my name is Alice and I am 30 years old.
}









