CodeBlanks Logo Icon CodeBlanks

Summary - Model classes

Combine fromJson and toJson to write a typed class.

Bidirectional conversion in a model class

If a model class contains both fromJson and toJson, you can carry data in both directions: create an object from an API response, and convert user changes back to JSON to send to the server. Together these two methods cover both the read and write sides of the model.

class Urun {
  final String ad;
  final int fiyat;
  Urun(this.ad, this.fiyat);

  factory Urun.fromJson(Map<String, dynamic> json) {
    return Urun(json['ad'] as String, json['fiyat'] as int);
  }

  Map<String, dynamic> toJson() => {'ad': ad, 'fiyat': fiyat};
}

Practice Complete the Urun model

Add a fromJson factory constructor and a toJson method to the Urun class. In main, create a Urun instance from the given Map and print its toJson output with jsonEncode.

Starter code

main.dart
import 'dart:convert';

class Urun {
  final String ad;
  final int fiyat;

  Urun(this.ad, this.fiyat);

  // fromJson fabrika kurucusunu ekle
  // toJson metodunu ekle
}

void main() {
  // {'ad': 'Kitap', 'fiyat': 50} Map'inden Urun oluştur
  // toJson çıktısını jsonEncode ile yazdır
}

Sample solution

main.dart
import 'dart:convert';

class Urun {
  final String ad;
  final int fiyat;

  Urun(this.ad, this.fiyat);

  factory Urun.fromJson(Map<String, dynamic> json) {
    return Urun(json['ad'] as String, json['fiyat'] as int);
  }

  Map<String, dynamic> toJson() {
    return {'ad': ad, 'fiyat': fiyat};
  }
}

void main() {
  final u = Urun.fromJson({'ad': 'Kitap', 'fiyat': 50});
  print(jsonEncode(u.toJson()));
}

Expected output

{"ad":"Kitap","fiyat":50}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does having both fromJson and toJson in a model enable?

  • Automatic UI rendering
  • Bidirectional JSON conversion Correct answer
  • Database connection
  • Faster compilation

Explanation: fromJson creates an object from JSON, toJson produces a Map from the object; together they enable bidirectional conversion. UI, database, and compilation speed are not the model's job.

2 Cast a JSON value

Question
factory Urun.fromJson(Map<String, dynamic> json) {
  return Urun(
    json['ad'] ____,
    json['fiyat'] as int,
  );
}
Answer
factory Urun.fromJson(Map<String, dynamic> json) {
  return Urun(
    json['ad'] as String,
    json['fiyat'] as int,
  );
}

Explanation: To cast a value from JSON to String, use `as String`; a wrong cast throws at runtime.

3 Model summary

Term Meaning
fromJson Creates a model from JSON
toJson Converts the model to a Map
final Marks immutable fields
factory Factory constructor

All lessons in Intermediate