What is a model class?
- Flutter course
- Intermediate
- Lesson 56/99
- 4 min
Store data type-safely with a model class.
What is a model class?
A model class is a Dart class that stores data in named, typed fields. Using a model instead of Map<String, dynamic> lets you access fields safely; if you mistype a key, the compiler warns you. Fields are usually final, so the object cannot change after it is created.
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
}
void main() {
final k = Kullanici('Ayşe', 28);
print(k.ad); // Ayşe
}final fields and the constructor
In a model class, fields are declared final and given their initial values by the constructor. final fields cannot be changed later, which keeps the data consistent throughout the program. The shorthand constructor Urun(this.ad, this.fiyat) assigns parameters directly to fields.
class Urun {
final String ad;
final int fiyat;
Urun(this.ad, this.fiyat);
}
final u = Urun('Kalem', 15);
// u.fiyat = 20; // Error: final cannot be assignedPractice Define a Kullanici model
Define a class named Kullanici with final String ad and final int yas fields. Assign values via the constructor. In main, create an instance and print its ad field with print.
Starter code
// Kullanici sınıfını tanımla
// ad ve yas alanları final olsun
// Bir nesne oluşturup ad'ını yazdır
void main() {
}Sample solution
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
}
void main() {
final k = Kullanici('Mert', 30);
print(k.ad);
}Expected output
Mert
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a model class provide?
- Type-safe access to fields Correct answer
- Automatic UI rendering
- Database connection
- Faster compilation
Explanation: A model class explicitly specifies field types, so the compiler warns on wrong access. UI rendering, database, and compilation speed are not the model's responsibility.
2 Declare a final field
class Kullanici {
____;
final int yas;
Kullanici(this.ad, this.yas);
}
class Kullanici {
final String ad;
final int yas;
Kullanici(this.ad, this.yas);
}
Explanation: In a model class, fields are declared final; this way they cannot change after the object is created.
3 Model class parts
| Term | Meaning |
|---|---|
class Kullanici |
Class declaration |
final String ad |
Immutable field |
Kullanici(this.ad) |
Constructor |
k.ad |
Field access |