Learn/Capstone Projects/Social Media App Project

Social Media App Project

Build a social media platform with posts, likes, follows, and feeds

14 min~7 min read+85 FX

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

Table of Contents

  1. 1. Feed Quality Strategy
  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.

Social Media App Project

Build a full-featured social media application with user profiles, image/text posts, likes, comments, follow/unfollow functionality, and a personalized feed. This capstone project is the ultimate test of your Flutter skills, combining real-time data streams, complex state management, image processing, pagination, and social graph algorithms. You will implement features found in production apps like Instagram, Twitter, and TikTok.

dart
1// ══════════════════════════════════════
2// SOCIAL MEDIA APP: PROJECT ARCHITECTURE
3// ══════════════════════════════════════
4//
5// lib/
6// main.dart
7// models/
8// user_profile.dart
9// post.dart
10// comment.dart
11// notification.dart
12// services/
13// auth_service.dart
14// post_service.dart
15// user_service.dart
16// notification_service.dart
17// storage_service.dart
18// providers/
19// auth_provider.dart
20// feed_provider.dart
21// profile_provider.dart
22// screens/
23// feed/
24// feed_screen.dart
25// post/
26// create_post_screen.dart
27// post_detail_screen.dart
28// profile/
29// profile_screen.dart
30// edit_profile_screen.dart
31// followers_screen.dart
32// search/
33// search_screen.dart
34// notifications/
35// notifications_screen.dart
36// widgets/
37// post_card.dart
38// comment_tile.dart
39// user_avatar.dart
40// like_button.dart
41
42// ── DATA MODELS ──
43class UserProfile {
44 final String uid;
45 final String username;
46 final String displayName;
47 final String? bio;
48 final String? avatarUrl;
49 final int followersCount;
50 final int followingCount;
51 final int postsCount;
52
53 const UserProfile({
54 required this.uid,
55 required this.username,
56 required this.displayName,
57 this.bio,
58 this.avatarUrl,
59 this.followersCount = 0,
60 this.followingCount = 0,
61 this.postsCount = 0,
62 });
63}
64
65class Post {
66 final String id;
67 final String authorId;
68 final String authorName;
69 final String? authorAvatar;
70 final String? text;
71 final String? imageUrl;
72 final int likesCount;
73 final int commentsCount;
74 final DateTime createdAt;
75 final bool isLikedByCurrentUser;
76
77 const Post({
78 required this.id,
79 required this.authorId,
80 required this.authorName,
81 this.authorAvatar,
82 this.text,
83 this.imageUrl,
84 this.likesCount = 0,
85 this.commentsCount = 0,
86 required this.createdAt,
87 this.isLikedByCurrentUser = false,
88 });
89}
90
91class Comment {
92 final String id;
93 final String authorId;
94 final String authorName;
95 final String? authorAvatar;
96 final String text;
97 final DateTime createdAt;
98
99 const Comment({
100 required this.id,
101 required this.authorId,
102 required this.authorName,
103 this.authorAvatar,
104 required this.text,
105 required this.createdAt,
106 });
107}
dart
1// ── POST SERVICE ──
2class PostService {
3 final _firestore = FirebaseFirestore.instance;
4 final _auth = FirebaseAuth.instance;
5
6 // Create a new post
7 Future<void> createPost({String? text, File? image}) async {
8 final user = _auth.currentUser!;
9 String? imageUrl;
10
11 if (image != null) {
12 final ref = FirebaseStorage.instance
13 .ref('posts/${user.uid}/${DateTime.now().millisecondsSinceEpoch}.jpg');
14 await ref.putFile(image);
15 imageUrl = await ref.getDownloadURL();
16 }
17
18 final postRef = _firestore.collection('posts').doc();
19 await postRef.set({
20 'authorId': user.uid,
21 'authorName': user.displayName ?? 'User',
22 'authorAvatar': user.photoURL,
23 'text': text,
24 'imageUrl': imageUrl,
25 'likesCount': 0,
26 'commentsCount': 0,
27 'createdAt': FieldValue.serverTimestamp(),
28 });
29
30 // Increment user post count
31 await _firestore.collection('users').doc(user.uid).update({
32 'postsCount': FieldValue.increment(1),
33 });
34 }
35
36 // Get feed (posts from users you follow)
37 Future<List<Post>> getFeed({DocumentSnapshot? lastDoc}) async {
38 final userId = _auth.currentUser!.uid;
39
40 // Get list of users you follow
41 final followingSnap = await _firestore
42 .collection('users')
43 .doc(userId)
44 .collection('following')
45 .get();
46
47 final followingIds = followingSnap.docs.map((d) => d.id).toList();
48 followingIds.add(userId); // Include own posts
49
50 // Firestore whereIn supports max 30 values
51 Query query = _firestore
52 .collection('posts')
53 .where('authorId', whereIn: followingIds.take(30).toList())
54 .orderBy('createdAt', descending: true)
55 .limit(10);
56
57 if (lastDoc != null) {
58 query = query.startAfterDocument(lastDoc);
59 }
60
61 final snapshot = await query.get();
62
63 // Check which posts the current user has liked
64 final posts = <Post>[];
65 for (final doc in snapshot.docs) {
66 final likeDoc = await doc.reference
67 .collection('likes')
68 .doc(userId)
69 .get();
70 posts.add(Post.fromFirestore(doc, isLiked: likeDoc.exists));
71 }
72
73 return posts;
74 }
75
76 // Toggle like on a post
77 Future<void> toggleLike(String postId) async {
78 final userId = _auth.currentUser!.uid;
79 final likeRef = _firestore
80 .collection('posts')
81 .doc(postId)
82 .collection('likes')
83 .doc(userId);
84
85 final likeDoc = await likeRef.get();
86
87 if (likeDoc.exists) {
88 await likeRef.delete();
89 await _firestore.collection('posts').doc(postId).update({
90 'likesCount': FieldValue.increment(-1),
91 });
92 } else {
93 await likeRef.set({'timestamp': FieldValue.serverTimestamp()});
94 await _firestore.collection('posts').doc(postId).update({
95 'likesCount': FieldValue.increment(1),
96 });
97 }
98 }
99}
dart
1// ── FOLLOW/UNFOLLOW SYSTEM ──
2class UserService {
3 final _firestore = FirebaseFirestore.instance;
4 final _auth = FirebaseAuth.instance;
5
6 Future<void> toggleFollow(String targetUserId) async {
7 final currentUserId = _auth.currentUser!.uid;
8 final followRef = _firestore
9 .collection('users')
10 .doc(currentUserId)
11 .collection('following')
12 .doc(targetUserId);
13
14 final followDoc = await followRef.get();
15 final batch = _firestore.batch();
16
17 if (followDoc.exists) {
18 // Unfollow
19 batch.delete(followRef);
20 batch.delete(_firestore
21 .collection('users').doc(targetUserId)
22 .collection('followers').doc(currentUserId));
23 batch.update(_firestore.collection('users').doc(currentUserId), {
24 'followingCount': FieldValue.increment(-1),
25 });
26 batch.update(_firestore.collection('users').doc(targetUserId), {
27 'followersCount': FieldValue.increment(-1),
28 });
29 } else {
30 // Follow
31 batch.set(followRef, {'timestamp': FieldValue.serverTimestamp()});
32 batch.set(_firestore
33 .collection('users').doc(targetUserId)
34 .collection('followers').doc(currentUserId),
35 {'timestamp': FieldValue.serverTimestamp()});
36 batch.update(_firestore.collection('users').doc(currentUserId), {
37 'followingCount': FieldValue.increment(1),
38 });
39 batch.update(_firestore.collection('users').doc(targetUserId), {
40 'followersCount': FieldValue.increment(1),
41 });
42 }
43
44 await batch.commit();
45 }
46}
47
48// ── POST CARD WIDGET ──
49class PostCard extends StatelessWidget {
50 final Post post;
51 final VoidCallback onLike;
52 final VoidCallback onComment;
53 final VoidCallback onProfile;
54
55 const PostCard({
56 super.key,
57 required this.post,
58 required this.onLike,
59 required this.onComment,
60 required this.onProfile,
61 });
62
63 @override
64 Widget build(BuildContext context) {
65 return Card(
66 margin: const EdgeInsets.symmetric(vertical: 4),
67 child: Column(
68 crossAxisAlignment: CrossAxisAlignment.start,
69 children: [
70 // Author header
71 ListTile(
72 leading: GestureDetector(
73 onTap: onProfile,
74 child: CircleAvatar(
75 backgroundImage: post.authorAvatar != null
76 ? NetworkImage(post.authorAvatar!)
77 : null,
78 child: post.authorAvatar == null
79 ? Text(post.authorName[0])
80 : null,
81 ),
82 ),
83 title: Text(post.authorName,
84 style: const TextStyle(fontWeight: FontWeight.bold)),
85 subtitle: Text(_timeAgo(post.createdAt)),
86 trailing: const Icon(Icons.more_vert),
87 ),
88 // Image
89 if (post.imageUrl != null)
90 Image.network(post.imageUrl!, fit: BoxFit.cover,
91 width: double.infinity),
92 // Text
93 if (post.text != null)
94 Padding(
95 padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
96 child: Text(post.text!),
97 ),
98 // Actions
99 Padding(
100 padding: const EdgeInsets.symmetric(horizontal: 8),
101 child: Row(
102 children: [
103 IconButton(
104 icon: Icon(
105 post.isLikedByCurrentUser
106 ? Icons.favorite : Icons.favorite_border,
107 color: post.isLikedByCurrentUser ? Colors.red : null,
108 ),
109 onPressed: onLike,
110 ),
111 Text('${post.likesCount}'),
112 const SizedBox(width: 16),
113 IconButton(
114 icon: const Icon(Icons.chat_bubble_outline),
115 onPressed: onComment,
116 ),
117 Text('${post.commentsCount}'),
118 const Spacer(),
119 IconButton(
120 icon: const Icon(Icons.share_outlined),
121 onPressed: () {},
122 ),
123 ],
124 ),
125 ),
126 ],
127 ),
128 );
129 }
130}

Social Media Scaling Considerations

💡 Social Media Scaling Considerations

Use Firestore batch writes for follow/unfollow to update multiple documents atomically. Paginate the feed using startAfterDocument to load posts incrementally. Store like counts as a field on the post document and use FieldValue.increment to avoid read-modify-write conflicts. For large user bases, consider denormalizing data to reduce the number of reads.

Feed Quality Strategy

Social feed systems must balance freshness, relevance, and cost:

  • Define ranking inputs clearly (recency, engagement, relationship strength).
  • Use pagination and incremental loading to protect startup performance.
  • Keep write paths atomic for likes, comments, and follow graph updates.
  • Separate moderation workflow from feed retrieval path.

Clear feed strategy prevents both performance bottlenecks and inconsistent user experience.

Social Platform Checklist

  • Feed pagination is stable and duplicate-safe under rapid updates.
  • Like and comment counters remain consistent under concurrent interactions.
  • Follow and unfollow actions are atomic and reversible.
  • Content moderation and reporting flows are integrated.
  • Notification fan-out paths are measured for latency and cost.

This Lesson In Simple Words

Build a social media platform with posts, likes, follows, and feeds. Forms collect user input, and validation ensures the input is safe and useful.

Your level focus

Operate with production and interview-level clarity.

One practical habit

Show validation messages early and clearly, near the field that needs correction.

Deep Understanding Guide

Why this lesson matters

Most app trust problems start when invalid or incomplete input reaches backend systems.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Treat forms as mini workflows: input, validate, submit, and recover from errors.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Validating only on submit and giving late feedback to users.
  • Using vague error text that does not tell users what to fix.
  • Forgetting to trim whitespace and normalize input values.
  • Not handling keyboard focus flow and accessibility labels.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build a signup form with per-field validators and submit-state handling.
  • Add password strength feedback with friendly, actionable hints.
  • Simulate a server validation error and show a user-safe message.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why use Firestore batch writes for follow/unfollow?".

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.

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

Validated input at UI and domain layers protects business logic from invalid assumptions.

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 design Flutter forms that are user-friendly, accessible, and backend-safe?

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

Lesson Completion Checklist

  • I can explain "Social Media 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: Validating only on submit and giving late feedback to users.
  • 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 use Firestore batch writes for follow/unfollow?

Following a user requires updating 4 documents: your following list, their followers list, your following count, and their followers count. Batch writes ensure all succeed or all fail together. Trap check: batch writes are about atomic consistency, not automatic retries or security-rule bypass behavior.

How do you implement infinite scroll pagination with Firestore?

Firestore cursor-based pagination uses limit() to fetch a page size and startAfterDocument() with the last document to fetch the next page. This is efficient and consistent even with real-time updates. Trap check: offset pagination is inefficient in Firestore and unstable under inserts; cursor pagination is the production-safe approach.

Why use FieldValue.increment() instead of reading the count, adding 1, and writing back?

If two users like a post at the same time, read-modify-write could lose one like. FieldValue.increment(1) is an atomic server-side operation that correctly handles concurrent updates. Trap check: shorter code is irrelevant here; atomic increments protect counters under concurrent likes and unlikes.

Users rapidly tap follow and unfollow, and counters drift from relation docs. Which write strategy best prevents divergence?

Atomic writes ensure relationship edges and counter fields succeed or fail together. This prevents half-applied follow operations under rapid concurrent interactions.

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.