Freezed and json_serializable in Flutter: solved exercise
Freezed and json_serializable in Flutter: solved exercise
Freezed automatically generates copyWith, ==, hashCode, toString, and fromJson/toJson for your models. It eliminates the boilerplate you would otherwise write by hand — the most common source of bugs when working with immutable data.
Problem statement
Create an immutable Post model with id, title, body, and isFavorite (with a default value). Demonstrate:
Instance creation.
copyWith to change a single field.
Serialization to/from JSON.
A union type ApiResult to model success and failure.
# Generate .freezed.dart and .g.dart for the first timedart run build_runner build --delete-conflicting-outputs
# Watch mode: regenerates automatically on savedart run build_runner watch --delete-conflicting-outputs
// lib/main.dart
import'package:flutter/material.dart';// Import your generated models
// import 'domain/models/post.dart';
// import 'domain/models/api_result.dart';
voidmain(){// ── Post model ───────────────────────────────────────────────────────────
constpost=Post(id:1,title:'Hello Freezed',body:'Post body');// copyWith: creates a copy with isFavorite changed
finalfavoritePost=post.copyWith(isFavorite:true);// JSON serialization
finaljson=post.toJson();finalfromJson=Post.fromJson({'id':2,'title':'Test','body':'Body'});// == works correctly (generated by Freezed)
assert(post==constPost(id:1,title:'Hello Freezed',body:'Post body'));assert(post!=favoritePost);debugPrint('post: $post');// Post(id: 1, title: Hello Freezed, body: Post body, isFavorite: false)
debugPrint('favoritePost: $favoritePost');// Post(id: 1, title: Hello Freezed, body: Post body, isFavorite: true)
debugPrint('json: $json');// {id: 1, title: Hello Freezed, body: Post body, isFavorite: false}
debugPrint('fromJson: $fromJson');// Post(id: 2, title: Test, body: Body, isFavorite: false)
// ── ApiResult union type ─────────────────────────────────────────────────
constApiResult<Post>result=ApiResult.success(post);finalmessage=switch(result){Success(:finaldata)=>'Loaded: ${data.title}',Failure(:finalmessage)=>'Error: $message',};debugPrint(message);// Loaded: Hello Freezed
runApp(constMaterialApp(home:Scaffold(body:Center(child:Text('Freezed OK')))));}
Files generated by build_runner
After running build_runner build, two files appear that you must not edit manually:
1
2
3
4
lib/domain/models/
├── post.dart ← only edit this one
├── post.freezed.dart ← auto-generated
└── post.g.dart ← auto-generated (fromJson/toJson)
Add these patterns to .gitignore if you prefer not to version the generated files (requires regeneration in CI):
1
2
3
# .gitignore (optional)
*.freezed.dart
*.g.dart
Or commit them to avoid regenerating on every CI build.
Common mistakes
Forgetting part 'post.freezed.dart': the compiler cannot find the generated types and fails with _$Post not found.
Not running build_runner after a change: .freezed.dart files become stale and type errors appear.
Editing a .freezed.dart file by hand: it gets overwritten on the next build; all changes go in the annotated source file.
When Freezed is worth it
Models that travel across multiple layers (API → domain → UI).
Models that are frequently copied with small modifications.
BLoC/Cubit states with multiple variants (union types).
Any project lasting more than a couple of weeks.
Practical use
Freezed is the de facto standard for domain models in Flutter. You will find it in almost every production project with clean architecture, alongside Riverpod or BLoC.