Methods
- Dart course
- Beginner
- Lesson 80/116
- 5 min
Learn to define methods in a class.
Methods
Methods define the behavior of a class's instances. They are written inside the class body like normal functions. Example: class User { String name; void describe() { print(name); } }.
A method can access the class's fields directly. Writing name inside describe refers to the field. this.name means the same.
Methods are called on an instance through a dot: u.describe(). They can take parameters, just like normal functions. When there is no return value, write void.
Method with parameters
Methods can take parameters. Example: void greet(String title) { print('$title $name'); }. This method takes a title when called and prints it together with name.
Call: u.greet('Mr.'). Here 'Mr.' goes into the title parameter; the body combines it with name via $title $name.
Parameterized methods combine the class data with external values. This makes behavior flexible. For a return value, write a type instead of void: String greeting() { return 'Hello $name'; }.
Practice The describe method
Define a User class with a String name field and a User(this.name) constructor. Add a void describe() method whose body does print(name). Inside main create a User('Ayşe') instance and call u.describe().
Starter code
void main() {
// define the User class and describe method
// create an instance and call describe
}Sample solution
class User {
String name;
User(this.name);
void describe() {
print(name);
}
}
void main() {
var u = User('Ayşe');
u.describe();
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the method parts
| Term | Meaning |
|---|---|
void |
No return |
describe |
Method name |
() |
No parameters |
u.describe() |
Call |
2 What does name do inside a method?
- Throws
- Reaches the name field of the class Correct answer
- Declares a new variable
- Counts as a parameter
Explanation: name inside a method reaches the class field.
3 Method definition
class User {
String name;
void describe() {
print(____);
}
}
class User {
String name;
void describe() {
print(name);
}
}
Explanation: name inside a method reaches the field.