In professional apps, managing data using raw Maps (like {"name": "Alice", "age": 25}) is risky because keys are just strings, making typos easy and debugging hard. Models allow you to define a blueprint (Class) for your data, ensuring type safety, autocomplete support, and consistency across your application.
1. What is a Data Model?
A Model is simply a Dart class that represents a specific type of entity, such as a User, Product, or Post. It holds properties (fields) and typically includes a constructor to initialize them.
Defining a Class
1// Define the blueprint2class User {3 String name;4 int age;5 String email;6 7 // Constructor with named parameters8 User({9 required this.name, 10 required this.age, 11 required this.email12 });13}14 15void main() {16 // Creating an instance (Object) of User17 User currentUser = User(18 name: 'Houssam', 19 age: 25, 20 email: 'houssam@example.com'21 );22 23 print(currentUser.name); // ✅ Type-safe and auto-completed!24 // print(currentUser['name']); // ❌ Error: This isn't a Map anymore25}HintBy using a class, you prevent spelling mistakes. If you try to access currentUser.nmae, the compiler will stop you immediately.
2. Converting Maps to Models (fromJson)
Data usually comes from the internet (APIs) in JSON format, which Dart treats as a Map<String, dynamic>. A robust model includes a "factory constructor" to convert this raw map into a strongly typed object.
The .fromJson Method
1class Product {2 String id;3 String title;4 double price;5 6 Product({required this.id, required this.title, required this.price});7 8 // Factory constructor to create a Product from a Map (JSON)9 factory Product.fromJson(Map<String, dynamic> json) {10 return Product(11 id: json['id'],12 title: json['title'],13 // specific logic to ensure safety (e.g. converting int to double)14 price: json['price'].toDouble(), 15 );16 }17}18 19void main() {20 // Simulating data from an API21 var rawJson = {'id': 'p1', 'title': 'Laptop', 'price': 999.99};22 23 // Convert raw map to safe Product object24 Product myProduct = Product.fromJson(rawJson);25 26 print('Title: ${myProduct.title}'); // Safe access27}HintThe factory constructor is the standard pattern in Flutter for parsing JSON. It encapsulates the "messy" map lookups inside the class so the rest of your app stays clean.
3. Converting Models back to Maps (toJson)
Sometimes you need to send data back to a server. For this, you create a method (usually called toJson) that converts your object back into a Map.
The .toJson Method
1class User {2 String name;3 int age;4 5 User({required this.name, required this.age});6 7 // Convert Object -> Map8 Map<String, dynamic> toJson() {9 return {10 'name': name,11 'age': age,12 };13 }14}15 16void main() {17 User user = User(name: 'Alice', age: 30);18 19 // Ready to send to API20 print(user.toJson()); // Output: {name: Alice, age: 30}21}HintThis creates a complete data cycle: Raw JSON -> Model (for use in the app) -> Raw JSON (for sending back to the server).
Loot collected
Key takeaways- Models are Classes that define the structure of your data.
- Using Models instead of Maps prevents typos, runtime crashes, and logic errors.
- Use a
factory ClassName.fromJsonconstructor to parse incoming API data. - Use a
toJson()method to prepare data for sending to a database or API. - Models are the industry standard for handling data in Flutter apps.
Side quests
Practice exercises
Exercise 1: Basic Class
Create a class Car with properties brand (String) and year (int). Create an instance of it.
Reveal solutionHide solution
1class Car { String brand; int year; Car({required this.brand, required this.year}); } 2var myCar = Car(brand: 'Toyota', year: 2022);Exercise 2: JSON Parsing
Add a fromJson factory to your Car class that accepts a Map.
Reveal solutionHide solution
1factory Car.fromJson(Map<String, dynamic> json) { return Car(brand: json['brand'], year: json['year']); }