Model in Flutter
Why Use It
1.Structure and organize data:- Models define a consistent structure for data (fields + types), making code readable, predictable, and type-safe.
Examples:-
=> In a user login system, a UserModel has uid, name, email, and profileImage. This helps you show and update user profiles easily.
=> In a weather app, a WeatherModel includes temperature, humidity, and condition, helping organize weather data cleanly.
=> In an e-learning app, a CourseModel has fields like title, description, duration, and instructorId.
2.Convert JSON ↔ Dart (Serialization/Deserialization):- Models help convert data received from backend (usually JSON) into Dart objects (fromJson()), and send it back using toJson().
Examples:-
=> In a chat app, messages are received in JSON. You convert them into MessageModel using fromJson() to display on the UI.
=> In a travel booking app, flight data comes from an API. You convert it into FlightModel using fromJson() and display departure, arrival, price.
=>In a food ordering app, user reviews are submitted by converting ReviewModel into JSON using toJson() before sending to Firebase.
3.Clean and Maintainable Architecture:- Models help in separating data from UI and business logic, which keeps your code clean, modular, and easier to test and scale.
Examples:-
=> In a movie app, the UI shows data from MovieModel, which lives in a different file. This keeps UI clean and focused only on presentation.
=>In an inventory management system, models like ProductModel, CategoryModel, and StockModel keep data logic separate from the screens.
=>In a banking app, TransactionModel handles transaction info like amount, type, timestamp — keeping UI separate from core logic.
4.Easy Data Sharing Between Screens:- You can pass model objects (like UserModel) between widgets or screens without dealing with raw data structures like Map<String, dynamic>.
Examples:-
=> In a shopping app, when a user taps on a product, the whole ProductModel is passed to the ProductDetailScreen.
=> In a fitness app, tapping on a workout card passes the entire WorkoutModel to the workout detail page.
=> In a news app, selecting a news item passes the ArticleModel to a full-screen reader.
5. State Management Integration:- Whether you’re using Provider, GetX, Riverpod, or BLoC, models are crucial in holding and managing structured state data.
Examples:-
=> In a food delivery app, a CartController uses a list of CartItemModel to manage cart items reactively.
Get Ajay kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
=> In a note-taking app, Provider holds a list of NoteModel, and whenever a new note is added, UI automatically rebuilds.
=> In a video streaming app, a VideoController (using GetX) holds VideoModel to manage playback, metadata, and suggestions.
About Model:- a Model is a Dart class that represents data for a real-world entity (like User, Post, or Product).
This class defines the structure of the data used in the application and typically includes fromJson() and toJson() methods.
The main purpose of a model is to:
a. Convert incoming JSON data (from an API or Firebase) into a Dart object using fromJson()Convert Dart objects back to JSON using
b. toJson() so they can be sent to a backend or saved in a database.
Step-by-Step Process to Create a Model in Dart
1. Identify Your Data Fields
From API, Firebase, or your app’s data needs.
Json
{
"uid": "12345678",
"name": "Raman",
"email": "raman@gmail.com",
"profilePhoto": "https://example.com/raman.jpg"
}2. Create a Dart Class
class UserModel {
final String uid;
final String name;
final String email;
final String profilePhoto;
UserModel({
required this.uid,
required this.name,
required this.email,
required this.profilePhoto,
});
}3. Add fromJson() Factory Constructor
Converts JSON (Map<String, dynamic>) into a Dart object.
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
uid: json['uid'],
name: json['name'],
email: json['email'],
profilePhoto: json['profilePhoto'],
);
}4. Add toJson() Method
Converts Dart object to JSON (Map) for uploading/saving.
Map<String, dynamic> toJson() {
return {
'uid': uid,
'name': name,
'email': email,
'profilePhoto': profilePhoto,
};
}5. Full Example
class UserModel {
final String uid;
final String name;
final String email;
final String profilePhoto;
UserModel({
required this.uid,
required this.name,
required this.email,
required this.profilePhoto,
});
// Convert JSON → Dart
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
uid: json['uid'],
name: json['name'],
email: json['email'],
profilePhoto: json['profilePhoto'],
);
}
// Convert Dart → JSON
Map<String, dynamic> toJson() {
return {
'uid': uid,
'name': name,
'email': email,
'profilePhoto': profilePhoto,
};
}
}About Factory:- A factory is a special type of constructor that allows you to customize the object creation process.
We use a factory constructor when we need to apply certain logic while creating an object — such as:
=>performing caching
=>returning an existing object
=>applying null checks
=>converting JSON data into a Dart object
Real Example:- Suppose in an app, I want to create a UserModel object, but if the data is null, I want to return null.
This is not possible with a normal constructor, but it can be done using a factory constructor.
More Examples on Models:-
1. Users
class UserModel {
final String uid;
final String username;
final String email;
final String profilePhoto;
UserModel({{
required this.uid,
required this.username,
required this.email,
required this.profilePhoto,
});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
uid: json['uid'],
username: json['username'],
email: json['email'],
profilePhoto: json['profilePhoto'],
);
}
Map<String, dynamic> toJson() {
return {
'uid': uid,
'username': username,
'email': email,
'profilePhoto': profilePhoto,
};
}
}
2. Posts
class PostModel {
final String postId;
final String caption;
final String imageUrl;
final DateTime createdAt;
PostModel({{
required this.postId,
required this.caption,
required this.imageUrl,
required this.createdAt,
});
factory PostModel.fromJson(Map<String, dynamic> json) {
return PostModel(
postId: json['postId'],
caption: json['caption'],
imageUrl: json['imageUrl'],
createdAt: DateTime.parse(json['createdAt']),
);
}
Map<String, dynamic> toJson() {
return {
'postId': postId,
'caption': caption,
'imageUrl': imageUrl,
'createdAt': createdAt.toIso8601String(),
};
}
}
3. Comments
class CommentModel {
final String commentId;
final String text;
final String userId;
final String postId;
CommentModel({{
required this.commentId,
required this.text,
required this.userId,
required this.postId,
});
factory CommentModel.fromJson(Map<String, dynamic> json) {
return CommentModel(
commentId: json['commentId'],
text: json['text'],
userId: json['userId'],
postId: json['postId'],
);
}
Map<String, dynamic> toJson() {
return {
'commentId': commentId,
'text': text,
'userId': userId,
'postId': postId,
};
}
}
4. Like
class LikeModel {
final String likeId;
final String userId;
final String postId;
LikeModel({{
required this.likeId,
required this.userId,
required this.postId,
});
factory LikeModel.fromJson(Map<String, dynamic> json) {
return LikeModel(
likeId: json['likeId'],
userId: json['userId'],
postId: json['postId'],
);
}
Map<String, dynamic> toJson() {
return {
'likeId': likeId,
'userId': userId,
'postId': postId,
};
}
}
5. Products
class ProductModel {
final String id;
final String name;
final double price;
final String imageUrl;
ProductModel({{
required this.id,
required this.name,
required this.price,
required this.imageUrl,
});
factory ProductModel.fromJson(Map<String, dynamic> json) {
return ProductModel(
id: json['id'],
name: json['name'],
price: json['price'].toDouble(),
imageUrl: json['imageUrl'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'price': price,
'imageUrl': imageUrl,
};
}
}
6. CartItems
class CartItemModel {
final String productId;
final int quantity;
CartItemModel({{
required this.productId,
required this.quantity,
});
factory CartItemModel.fromJson(Map<String, dynamic> json) {
return CartItemModel(
productId: json['productId'],
quantity: json['quantity'],
);
}
Map<String, dynamic> toJson() {
return {
'productId': productId,
'quantity': quantity,
};
}
}
7. ProductsOrders
class OrderModel {
final String orderId;
final String userId;
final double totalPrice;
OrderModel({{
required this.orderId,
required this.userId,
required this.totalPrice,
});
factory OrderModel.fromJson(Map<String, dynamic> json) {
return OrderModel(
orderId: json['orderId'],
userId: json['userId'],
totalPrice: json['totalPrice'].toDouble(),
);
}
Map<String, dynamic> toJson() {
return {
'orderId': orderId,
'userId': userId,
'totalPrice': totalPrice,
};
}
}
8. UserAddress
class AddressModel {
final String addressId;
final String street;
final String city;
final String zipCode;
AddressModel({{
required this.addressId,
required this.street,
required this.city,
required this.zipCode,
});
factory AddressModel.fromJson(Map<String, dynamic> json) {
return AddressModel(
addressId: json['addressId'],
street: json['street'],
city: json['city'],
zipCode: json['zipCode'],
);
}
Map<String, dynamic> toJson() {
return {
'addressId': addressId,
'street': street,
'city': city,
'zipCode': zipCode,
};
}
}
9. Notifications
class NotificationModel {
final String notificationId;
final String title;
final String message;
NotificationModel({{
required this.notificationId,
required this.title,
required this.message,
});
factory NotificationModel.fromJson(Map<String, dynamic> json) {
return NotificationModel(
notificationId: json['notificationId'],
title: json['title'],
message: json['message'],
);
}
Map<String, dynamic> toJson() {
return {
'notificationId': notificationId,
'title': title,
'message': message,
};
}
}
10. Chatting
class ChatModel {
final String chatId;
final List<String> userIds;
ChatModel({{
required this.chatId,
required this.userIds,
});
factory ChatModel.fromJson(Map<String, dynamic> json) {
return ChatModel(
chatId: json['chatId'],
userIds: List<String>.from(json['userIds']),
);
}
Map<String, dynamic> toJson() {
return {
'chatId': chatId,
'userIds': userIds,
};
}
}
11. Messages
class MessageModel {
final String messageId;
final String senderId;
final String text;
final DateTime timestamp;
MessageModel({{
required this.messageId,
required this.senderId,
required this.text,
required this.timestamp,
});
factory MessageModel.fromJson(Map<String, dynamic> json) {
return MessageModel(
messageId: json['messageId'],
senderId: json['senderId'],
text: json['text'],
timestamp: DateTime.parse(json['timestamp']),
);
}
Map<String, dynamic> toJson() {
return {
'messageId': messageId,
'senderId': senderId,
'text': text,
'timestamp': timestamp.toIso8601String(),
};
}
}
12. Stories
class StoryModel {
final String storyId;
final String mediaUrl;
final String userId;
final DateTime expiresAt;
StoryModel({{
required this.storyId,
required this.mediaUrl,
required this.userId,
required this.expiresAt,
});
factory StoryModel.fromJson(Map<String, dynamic> json) {
return StoryModel(
storyId: json['storyId'],
mediaUrl: json['mediaUrl'],
userId: json['userId'],
expiresAt: DateTime.parse(json['expiresAt']),
);
}
Map<String, dynamic> toJson() {
return {
'storyId': storyId,
'mediaUrl': mediaUrl,
'userId': userId,
'expiresAt': expiresAt.toIso8601String(),
};
}
}
13. ToDo Tasks
class TaskModel {
final String taskId;
final String title;
final bool isCompleted;
TaskModel({{
required this.taskId,
required this.title,
required this.isCompleted,
});
factory TaskModel.fromJson(Map<String, dynamic> json) {
return TaskModel(
taskId: json['taskId'],
title: json['title'],
isCompleted: json['isCompleted'],
);
}
Map<String, dynamic> toJson() {
return {
'taskId': taskId,
'title': title,
'isCompleted': isCompleted,
};
}
}
14. Tickets Booking
class BookingModel {
final String bookingId;
final String userId;
final DateTime date;
BookingModel({{
required this.bookingId,
required this.userId,
required this.date,
});
factory BookingModel.fromJson(Map<String, dynamic> json) {
return BookingModel(
bookingId: json['bookingId'],
userId: json['userId'],
date: DateTime.parse(json['date']),
);
}
Map<String, dynamic> toJson() {
return {
'bookingId': bookingId,
'userId': userId,
'date': date.toIso8601String(),
};
}
}
15. Transactions
class TransactionModel {
final String transactionId;
final double amount;
final DateTime date;
TransactionModel({{
required this.transactionId,
required this.amount,
required this.date,
});
factory TransactionModel.fromJson(Map<String, dynamic> json) {
return TransactionModel(
transactionId: json['transactionId'],
amount: json['amount'].toDouble(),
date: DateTime.parse(json['date']),
);
}
Map<String, dynamic> toJson() {
return {
'transactionId': transactionId,
'amount': amount,
'date': date.toIso8601String(),
};
}
}
16. Products Categories
class CategoryModel {
final String categoryId;
final String name;
final String icon;
CategoryModel({{
required this.categoryId,
required this.name,
required this.icon,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) {
return CategoryModel(
categoryId: json['categoryId'],
name: json['name'],
icon: json['icon'],
);
}
Map<String, dynamic> toJson() {
return {
'categoryId': categoryId,
'name': name,
'icon': icon,
};
}
}
17. Products Review
class ReviewModel {
final String reviewId;
final double rating;
final String comment;
final String userId;
ReviewModel({{
required this.reviewId,
required this.rating,
required this.comment,
required this.userId,
});
factory ReviewModel.fromJson(Map<String, dynamic> json) {
return ReviewModel(
reviewId: json['reviewId'],
rating: json['rating'].toDouble(),
comment: json['comment'],
userId: json['userId'],
);
}
Map<String, dynamic> toJson() {
return {
'reviewId': reviewId,
'rating': rating,
'comment': comment,
'userId': userId,
};
}
}
18. Courses
class CourseModel {
final String courseId;
final String title;
final String instructorId;
final int duration;
CourseModel({{
required this.courseId,
required this.title,
required this.instructorId,
required this.duration,
});
factory CourseModel.fromJson(Map<String, dynamic> json) {
return CourseModel(
courseId: json['courseId'],
title: json['title'],
instructorId: json['instructorId'],
duration: json['duration'],
);
}
Map<String, dynamic> toJson() {
return {
'courseId': courseId,
'title': title,
'instructorId': instructorId,
'duration': duration,
};
}
}
19. Events
class EventModel {
final String eventId;
final String name;
final String location;
final DateTime date;
EventModel({{
required this.eventId,
required this.name,
required this.location,
required this.date,
});
factory EventModel.fromJson(Map<String, dynamic> json) {
return EventModel(
eventId: json['eventId'],
name: json['name'],
location: json['location'],
date: DateTime.parse(json['date']),
);
}
Map<String, dynamic> toJson() {
return {
'eventId': eventId,
'name': name,
'location': location,
'date': date.toIso8601String(),
};
}
}
20. Videos
class VideoModel {
final String videoId;
final String title;
final String url;
final String thumbnail;
VideoModel({{
required this.videoId,
required this.title,
required this.url,
required this.thumbnail,
});
factory VideoModel.fromJson(Map<String, dynamic> json) {
return VideoModel(
videoId: json['videoId'],
title: json['title'],
url: json['url'],
thumbnail: json['thumbnail'],
);
}
Map<String, dynamic> toJson() {
return {
'videoId': videoId,
'title': title,
'url': url,
'thumbnail': thumbnail,
};
}
}




