Blog
Define a Class in Dart
Define a Class in Dart
A class in Dart is a blueprint for creating objects. It defines the
properties and methods that objects of that class can have. Classes help organize code and make it reusable.
Basic Dart Class Syntax
A class is defined using the class keyword. Inside the class, you can define
fields, constructors, and methods.
class Student {
String name;
int age;
String course;
Student(this.name, this.age, this.course);
void study() {
print('$name is studying $course.');
}
void introduction() {
print('Hi, I am $name. I am $age years old.');
}
}
Explanation
- Student is the class name.
- name, age, and course are instance variables.
- The line Student(this.name, this.age, this.course); is a constructor
that initializes the object. - study() and introduction() are methods.
Creating an Object
Once a class is defined, you can create an object from it.
void main() {
Student s1 = Student('Kumar', 20, 'Computer Science');
s1.study();
s1.introduction();
}
Output
Kumar is studying Computer Science.
Hi, I am Kumar. I am 20 years old.
Conclusion
In Dart, a class is a way to model real-world entities. It allows you to group related data and behavior together, making programs more structured, readable, and maintainable.
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/
More information on Dart: