Learn/Capstone Projects/Chat App Project

Chat App Project

Build a real-time chat application with Firebase from scratch

12 min~6 min read+80 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Chat Reliability Blueprint
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens
  10. 10. Interview Angle

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Project Submission

Open the project tab to submit your GitHub repository and demo video before continuing through the lesson flow.

Chat App Project

Build a fully functional real-time chat application using Flutter and Firebase. This capstone project combines authentication, Firestore real-time database, Cloud Storage for media, push notifications, and polished UI design into a single production-ready application. You will implement one-on-one messaging, group chats, online status indicators, image sharing, and typing indicators. This project tests your mastery of state management, streams, and Firebase integration.

dart
1// ══════════════════════════════════════
2// CHAT APP: PROJECT ARCHITECTURE
3// ══════════════════════════════════════
4//
5// lib/
6// main.dart
7// models/
8// user_model.dart
9// message_model.dart
10// chat_room_model.dart
11// services/
12// auth_service.dart
13// chat_service.dart
14// notification_service.dart
15// storage_service.dart
16// providers/
17// auth_provider.dart
18// chat_provider.dart
19// screens/
20// auth/
21// login_screen.dart
22// signup_screen.dart
23// chat/
24// chat_list_screen.dart
25// chat_room_screen.dart
26// new_chat_screen.dart
27// profile/
28// profile_screen.dart
29// widgets/
30// message_bubble.dart
31// chat_tile.dart
32// typing_indicator.dart
33
34// ── DATA MODELS ──
35class ChatMessage {
36 final String id;
37 final String senderId;
38 final String senderName;
39 final String text;
40 final String? imageUrl;
41 final DateTime timestamp;
42 final bool isRead;
43
44 ChatMessage({
45 required this.id,
46 required this.senderId,
47 required this.senderName,
48 required this.text,
49 this.imageUrl,
50 required this.timestamp,
51 this.isRead = false,
52 });
53
54 factory ChatMessage.fromFirestore(DocumentSnapshot doc) {
55 final data = doc.data() as Map<String, dynamic>;
56 return ChatMessage(
57 id: doc.id,
58 senderId: data['senderId'],
59 senderName: data['senderName'],
60 text: data['text'] ?? '',
61 imageUrl: data['imageUrl'],
62 timestamp: (data['timestamp'] as Timestamp).toDate(),
63 isRead: data['isRead'] ?? false,
64 );
65 }
66
67 Map<String, dynamic> toMap() => {
68 'senderId': senderId,
69 'senderName': senderName,
70 'text': text,
71 'imageUrl': imageUrl,
72 'timestamp': FieldValue.serverTimestamp(),
73 'isRead': isRead,
74 };
75}
76
77class ChatRoom {
78 final String id;
79 final List<String> members;
80 final String? lastMessage;
81 final DateTime? lastMessageTime;
82 final String? groupName;
83 final bool isGroup;
84
85 ChatRoom({
86 required this.id,
87 required this.members,
88 this.lastMessage,
89 this.lastMessageTime,
90 this.groupName,
91 this.isGroup = false,
92 });
93}
dart
1// ── CHAT SERVICE ──
2class ChatService {
3 final _firestore = FirebaseFirestore.instance;
4 final _auth = FirebaseAuth.instance;
5
6 // Get or create a chat room between two users
7 Future<String> getOrCreateChatRoom(String otherUserId) async {
8 final currentUser = _auth.currentUser!;
9 final members = [currentUser.uid, otherUserId]..sort();
10 final roomId = members.join('_');
11
12 final roomRef = _firestore.collection('chatRooms').doc(roomId);
13 final room = await roomRef.get();
14
15 if (!room.exists) {
16 await roomRef.set({
17 'members': members,
18 'lastMessage': '',
19 'lastMessageTime': FieldValue.serverTimestamp(),
20 'isGroup': false,
21 });
22 }
23
24 return roomId;
25 }
26
27 // Send a text message
28 Future<void> sendMessage(String roomId, String text) async {
29 final user = _auth.currentUser!;
30
31 await _firestore
32 .collection('chatRooms')
33 .doc(roomId)
34 .collection('messages')
35 .add({
36 'senderId': user.uid,
37 'senderName': user.displayName ?? 'User',
38 'text': text,
39 'timestamp': FieldValue.serverTimestamp(),
40 'isRead': false,
41 });
42
43 // Update last message in chat room
44 await _firestore.collection('chatRooms').doc(roomId).update({
45 'lastMessage': text,
46 'lastMessageTime': FieldValue.serverTimestamp(),
47 });
48 }
49
50 // Real-time message stream
51 Stream<List<ChatMessage>> getMessages(String roomId) {
52 return _firestore
53 .collection('chatRooms')
54 .doc(roomId)
55 .collection('messages')
56 .orderBy('timestamp', descending: true)
57 .limit(50)
58 .snapshots()
59 .map((snapshot) => snapshot.docs
60 .map((doc) => ChatMessage.fromFirestore(doc))
61 .toList());
62 }
63
64 // Get chat rooms for current user
65 Stream<List<ChatRoom>> getChatRooms() {
66 final userId = _auth.currentUser!.uid;
67 return _firestore
68 .collection('chatRooms')
69 .where('members', arrayContains: userId)
70 .orderBy('lastMessageTime', descending: true)
71 .snapshots()
72 .map((snapshot) => snapshot.docs.map((doc) {
73 final data = doc.data();
74 return ChatRoom(
75 id: doc.id,
76 members: List<String>.from(data['members']),
77 lastMessage: data['lastMessage'],
78 lastMessageTime: data['lastMessageTime'] != null
79 ? (data['lastMessageTime'] as Timestamp).toDate()
80 : null,
81 isGroup: data['isGroup'] ?? false,
82 );
83 }).toList());
84 }
85
86 // Upload and send image
87 Future<void> sendImage(String roomId, File imageFile) async {
88 final user = _auth.currentUser!;
89 final ref = FirebaseStorage.instance
90 .ref('chat_images/${roomId}/${DateTime.now().millisecondsSinceEpoch}.jpg');
91 await ref.putFile(imageFile);
92 final url = await ref.getDownloadURL();
93
94 await _firestore
95 .collection('chatRooms')
96 .doc(roomId)
97 .collection('messages')
98 .add({
99 'senderId': user.uid,
100 'senderName': user.displayName,
101 'text': '',
102 'imageUrl': url,
103 'timestamp': FieldValue.serverTimestamp(),
104 'isRead': false,
105 });
106 }
107
108 // Update online status
109 Future<void> updateOnlineStatus(bool isOnline) async {
110 final userId = _auth.currentUser?.uid;
111 if (userId != null) {
112 await _firestore.collection('users').doc(userId).update({
113 'isOnline': isOnline,
114 'lastSeen': FieldValue.serverTimestamp(),
115 });
116 }
117 }
118}
dart
1// ── CHAT ROOM SCREEN (UI) ──
2class ChatRoomScreen extends StatefulWidget {
3 final String roomId;
4 final String otherUserName;
5 const ChatRoomScreen({
6 super.key, required this.roomId, required this.otherUserName,
7 });
8
9 @override
10 State<ChatRoomScreen> createState() => _ChatRoomScreenState();
11}
12
13class _ChatRoomScreenState extends State<ChatRoomScreen> {
14 final _messageController = TextEditingController();
15 final _chatService = ChatService();
16 final _scrollController = ScrollController();
17
18 @override
19 Widget build(BuildContext context) {
20 return Scaffold(
21 appBar: AppBar(
22 title: Column(
23 crossAxisAlignment: CrossAxisAlignment.start,
24 children: [
25 Text(widget.otherUserName),
26 const Text('Online', style: TextStyle(fontSize: 12, color: Colors.green)),
27 ],
28 ),
29 ),
30 body: Column(
31 children: [
32 // Messages list
33 Expanded(
34 child: StreamBuilder<List<ChatMessage>>(
35 stream: _chatService.getMessages(widget.roomId),
36 builder: (context, snapshot) {
37 if (!snapshot.hasData) {
38 return const Center(child: CircularProgressIndicator());
39 }
40 final messages = snapshot.data!;
41 return ListView.builder(
42 controller: _scrollController,
43 reverse: true,
44 itemCount: messages.length,
45 itemBuilder: (context, index) {
46 final msg = messages[index];
47 final isMe = msg.senderId == FirebaseAuth.instance.currentUser?.uid;
48 return MessageBubble(
49 message: msg,
50 isMe: isMe,
51 );
52 },
53 );
54 },
55 ),
56 ),
57
58 // Input bar
59 Container(
60 padding: const EdgeInsets.all(8),
61 decoration: BoxDecoration(
62 color: Colors.white,
63 boxShadow: [BoxShadow(color: Colors.grey[300]!, blurRadius: 4)],
64 ),
65 child: Row(
66 children: [
67 IconButton(
68 icon: const Icon(Icons.image),
69 onPressed: _pickAndSendImage,
70 ),
71 Expanded(
72 child: TextField(
73 controller: _messageController,
74 decoration: const InputDecoration(
75 hintText: 'Type a message...',
76 border: InputBorder.none,
77 ),
78 textCapitalization: TextCapitalization.sentences,
79 ),
80 ),
81 IconButton(
82 icon: const Icon(Icons.send, color: Colors.blue),
83 onPressed: _sendMessage,
84 ),
85 ],
86 ),
87 ),
88 ],
89 ),
90 );
91 }
92
93 void _sendMessage() {
94 final text = _messageController.text.trim();
95 if (text.isEmpty) return;
96 _chatService.sendMessage(widget.roomId, text);
97 _messageController.clear();
98 }
99
100 Future<void> _pickAndSendImage() async {
101 final picker = ImagePicker();
102 final image = await picker.pickImage(source: ImageSource.gallery);
103 if (image != null) {
104 await _chatService.sendImage(widget.roomId, File(image.path));
105 }
106 }
107
108 @override
109 void dispose() {
110 _messageController.dispose();
111 _scrollController.dispose();
112 super.dispose();
113 }
114}

Chat App Best Practices

💡 Chat App Best Practices

Always paginate messages using limit() and startAfter() to avoid loading the entire chat history at once. Use Firestore server timestamps instead of client timestamps to prevent ordering issues. Index your Firestore queries on members and lastMessageTime to keep chat list queries fast.

Chat Reliability Blueprint

Realtime chat quality depends on delivery guarantees and conflict handling:

  • Define message status transitions (sending, sent, delivered, read).
  • Handle duplicate sends during reconnect scenarios.
  • Keep idempotent message IDs for retry safety.
  • Separate transport errors from content validation errors.

This blueprint keeps chat behavior trustworthy under weak network conditions.

Chat App Launch Checklist

  • Realtime streams handle reconnect and offline queue recovery.
  • Message ordering remains correct across multi-device conversations.
  • Media upload failures provide retry and cancellation controls.
  • Typing and online indicators degrade gracefully when presence is unavailable.
  • Security rules restrict room access strictly to chat participants.

This Lesson In Simple Words

Build a real time chat application with Firebase from scratch. Backend integration connects app actions to real user data and secure business workflows.

Your level focus

Operate with production and interview-level clarity.

One practical habit

Define data model and access rules before writing convenience helper methods.

Deep Understanding Guide

Why this lesson matters

Security and data integrity issues can damage user trust faster than UI bugs.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Think from both sides: client UX and backend authorization constraints.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Trusting client-side checks without enforcing server-side rules.
  • Using broad read/write permissions in Firestore rules.
  • Storing secrets in plain text or unsafe local storage.
  • Not versioning schemas when documents evolve over time.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write one secure Firestore rule and test allow/deny cases.
  • Map one backend document model to a typed client model.
  • Implement auth-state based screen routing with guarded actions.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why should you use server timestamps instead of client timestamps in a chat app?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • stream: A sequence of asynchronous values over time.
  • firestore: A cloud NoSQL database used by Firebase apps.
  • validation: Checks that confirm input is correct before processing.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Security rules are part of architecture, not optional deployment polish.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Interview Angle

Practice this prompt: How do you protect Firestore data while keeping Flutter UX smooth and responsive?

Strong answer structure: context, decision, trade-off, and measurable outcome.

Lesson Completion Checklist

  • I can explain "Chat App Project" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Trusting client-side checks without enforcing server-side rules.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Why should you use server timestamps instead of client timestamps in a chat app?

Different devices may have slightly different clock times. FieldValue.serverTimestamp() ensures all messages are timestamped by the server, guaranteeing correct chronological order. Trap check: raw speed is not the objective; consistent ordering across unsynced device clocks is the core requirement.

How do you listen for new messages in real-time with Firestore?

Firestore snapshots() returns a Stream that emits a new event whenever the query results change. This provides real-time updates without manual polling. Trap check: polling with get() increases reads and latency while snapshots() provides push-based updates from Firestore listeners.

Why is reverse: true used on the messages ListView?

Setting reverse to true makes the ListView start from the bottom, which is the natural chat behavior. Combined with descending order from Firestore, newest messages appear at the bottom. Trap check: reverse only changes viewport behavior; it does not replace correct timestamp ordering in your backend query.

A user sends messages while offline, then reconnects and sees duplicate local times. Which approach most reliably preserves global message order?

Server-assigned timestamps provide a single trusted clock for all clients. Ordering by createdAt from Firestore prevents device-clock drift from corrupting timeline order after reconnect.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.