CodeBlanks Logo Icon CodeBlanks

What is a model class?

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 assigned

Practice 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

main.dart
// 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

main.dart
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

Question
class Kullanici {
  ____;
  final int yas;

  Kullanici(this.ad, this.yas);
}
Answer
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

All lessons in Intermediate