Learn/Capstone Projects/E-Commerce App Project

E-Commerce App Project

Build a complete online store with cart, checkout, and payments

14 min~6 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. Commerce Domain 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.

E-Commerce App Project

Build a complete e-commerce application with product browsing, search, shopping cart, user authentication, order management, and payment integration. This capstone project combines advanced state management, complex UI patterns, local and remote data synchronization, and real-world business logic. You will implement product catalogs with filtering and sorting, a persistent shopping cart, a multi-step checkout flow, and order history tracking.

dart
1// ══════════════════════════════════════
2// E-COMMERCE APP: PROJECT ARCHITECTURE
3// ══════════════════════════════════════
4//
5// lib/
6// main.dart
7// models/
8// product.dart
9// cart_item.dart
10// order.dart
11// user.dart
12// category.dart
13// services/
14// product_service.dart
15// cart_service.dart
16// order_service.dart
17// payment_service.dart
18// auth_service.dart
19// providers/
20// product_provider.dart
21// cart_provider.dart
22// auth_provider.dart
23// screens/
24// home/
25// home_screen.dart
26// product_detail_screen.dart
27// cart/
28// cart_screen.dart
29// checkout_screen.dart
30// orders/
31// order_history_screen.dart
32// order_detail_screen.dart
33// auth/
34// login_screen.dart
35// profile/
36// profile_screen.dart
37// widgets/
38// product_card.dart
39// cart_badge.dart
40// price_tag.dart
41// rating_stars.dart
42
43// ── DATA MODELS ──
44class Product {
45 final String id;
46 final String name;
47 final String description;
48 final double price;
49 final double? salePrice;
50 final List<String> images;
51 final String category;
52 final double rating;
53 final int reviewCount;
54 final bool inStock;
55 final Map<String, dynamic> attributes;
56
57 const Product({
58 required this.id,
59 required this.name,
60 required this.description,
61 required this.price,
62 this.salePrice,
63 required this.images,
64 required this.category,
65 this.rating = 0,
66 this.reviewCount = 0,
67 this.inStock = true,
68 this.attributes = const {},
69 });
70
71 double get effectivePrice => salePrice ?? price;
72 double get discountPercent =>
73 salePrice != null ? ((price - salePrice!) / price * 100) : 0;
74}
75
76class CartItem {
77 final Product product;
78 int quantity;
79 final String? selectedSize;
80 final String? selectedColor;
81
82 CartItem({
83 required this.product,
84 this.quantity = 1,
85 this.selectedSize,
86 this.selectedColor,
87 });
88
89 double get totalPrice => product.effectivePrice * quantity;
90}
91
92class Order {
93 final String id;
94 final List<CartItem> items;
95 final double subtotal;
96 final double shipping;
97 final double tax;
98 final double total;
99 final String status; // pending, confirmed, shipped, delivered
100 final DateTime createdAt;
101 final Map<String, String> shippingAddress;
102
103 const Order({
104 required this.id,
105 required this.items,
106 required this.subtotal,
107 required this.shipping,
108 required this.tax,
109 required this.total,
110 required this.status,
111 required this.createdAt,
112 required this.shippingAddress,
113 });
114}
dart
1// ── CART PROVIDER (State Management) ──
2class CartProvider extends ChangeNotifier {
3 final Map<String, CartItem> _items = {};
4
5 Map<String, CartItem> get items => {..._items};
6 int get itemCount => _items.length;
7
8 double get subtotal => _items.values
9 .fold(0, (sum, item) => sum + item.totalPrice);
10
11 double get shipping => subtotal > 50 ? 0 : 5.99;
12 double get tax => subtotal * 0.08; // 8% tax
13 double get total => subtotal + shipping + tax;
14
15 void addToCart(Product product, {String? size, String? color}) {
16 final key = '${product.id}_${size ?? ""}_${color ?? ""}';
17 if (_items.containsKey(key)) {
18 _items[key]!.quantity++;
19 } else {
20 _items[key] = CartItem(
21 product: product,
22 selectedSize: size,
23 selectedColor: color,
24 );
25 }
26 notifyListeners();
27 }
28
29 void removeFromCart(String key) {
30 _items.remove(key);
31 notifyListeners();
32 }
33
34 void updateQuantity(String key, int quantity) {
35 if (quantity <= 0) {
36 _items.remove(key);
37 } else {
38 _items[key]?.quantity = quantity;
39 }
40 notifyListeners();
41 }
42
43 void clearCart() {
44 _items.clear();
45 notifyListeners();
46 }
47}
48
49// ── PRODUCT SERVICE ──
50class ProductService {
51 final _firestore = FirebaseFirestore.instance;
52
53 Future<List<Product>> getProducts({
54 String? category,
55 String? searchQuery,
56 String sortBy = 'name',
57 bool descending = false,
58 }) async {
59 Query query = _firestore.collection('products');
60
61 if (category != null) {
62 query = query.where('category', isEqualTo: category);
63 }
64
65 query = query.orderBy(sortBy, descending: descending);
66
67 final snapshot = await query.limit(20).get();
68 final products = snapshot.docs
69 .map((doc) => Product.fromFirestore(doc))
70 .toList();
71
72 if (searchQuery != null && searchQuery.isNotEmpty) {
73 final lower = searchQuery.toLowerCase();
74 return products
75 .where((p) => p.name.toLowerCase().contains(lower))
76 .toList();
77 }
78
79 return products;
80 }
81}
dart
1// ── PRODUCT CARD WIDGET ──
2class ProductCard extends StatelessWidget {
3 final Product product;
4 final VoidCallback onTap;
5 const ProductCard({super.key, required this.product, required this.onTap});
6
7 @override
8 Widget build(BuildContext context) {
9 return GestureDetector(
10 onTap: onTap,
11 child: Card(
12 clipBehavior: Clip.antiAlias,
13 child: Column(
14 crossAxisAlignment: CrossAxisAlignment.start,
15 children: [
16 // Product image with sale badge
17 Stack(
18 children: [
19 AspectRatio(
20 aspectRatio: 1,
21 child: Image.network(
22 product.images.first,
23 fit: BoxFit.cover,
24 ),
25 ),
26 if (product.salePrice != null)
27 Positioned(
28 top: 8, left: 8,
29 child: Container(
30 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
31 decoration: BoxDecoration(
32 color: Colors.red,
33 borderRadius: BorderRadius.circular(4),
34 ),
35 child: Text(
36 '-${product.discountPercent.toInt()}%',
37 style: const TextStyle(color: Colors.white, fontSize: 12),
38 ),
39 ),
40 ),
41 ],
42 ),
43
44 Padding(
45 padding: const EdgeInsets.all(8),
46 child: Column(
47 crossAxisAlignment: CrossAxisAlignment.start,
48 children: [
49 Text(product.name,
50 maxLines: 2, overflow: TextOverflow.ellipsis,
51 style: const TextStyle(fontWeight: FontWeight.w600)),
52 const SizedBox(height: 4),
53 // Rating
54 Row(
55 children: [
56 ...List.generate(5, (i) => Icon(
57 i < product.rating.round() ? Icons.star : Icons.star_border,
58 size: 14, color: Colors.amber,
59 )),
60 Text(' (${product.reviewCount})',
61 style: TextStyle(fontSize: 12, color: Colors.grey[600])),
62 ],
63 ),
64 const SizedBox(height: 4),
65 // Price
66 Row(
67 children: [
68 Text('$${product.effectivePrice.toStringAsFixed(2)}',
69 style: const TextStyle(
70 fontSize: 16, fontWeight: FontWeight.bold, color: Colors.green)),
71 if (product.salePrice != null) ...[
72 const SizedBox(width: 4),
73 Text('$${product.price.toStringAsFixed(2)}',
74 style: const TextStyle(
75 fontSize: 12, decoration: TextDecoration.lineThrough,
76 color: Colors.grey)),
77 ],
78 ],
79 ),
80 ],
81 ),
82 ),
83 ],
84 ),
85 ),
86 );
87 }
88}
89
90// ── CHECKOUT FLOW ──
91// Step 1: Review cart items
92// Step 2: Enter shipping address
93// Step 3: Select payment method
94// Step 4: Confirm and place order
95// Step 5: Show order confirmation with tracking ID

E-Commerce Architecture Tips

💡 E-Commerce Architecture Tips

Separate your cart state from your product state. Cart should persist locally (Hive or SharedPreferences) so users do not lose items if they close the app. Validate prices server-side before processing payments to prevent client-side price manipulation. Use optimistic updates in the UI for a snappy feel, but always confirm with the server.

Commerce Domain Strategy

Strong e-commerce apps model business rules explicitly:

  • Pricing rules include discounts, tax, and shipping boundaries.
  • Inventory checks happen close to checkout confirmation.
  • Cart state supports guest mode and authenticated merge behavior.
  • Order lifecycle states remain auditable for support and refunds.

Explicit domain modeling prevents costly edge-case failures at payment time.

E Commerce Release Checklist

  • Server-side price validation is enforced for all checkout requests.
  • Payment success, failure, timeout, and duplicate callbacks are handled safely.
  • Cart persistence and cross-session restoration are tested.
  • Order confirmation and history stay consistent after app restarts.
  • Fraud and abuse monitoring events are logged for payment operations.

This Lesson In Simple Words

Build a complete online store with cart, checkout, and payments. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

Operate with production and interview-level clarity.

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why should you validate prices on the server before processing a payment?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.

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

Connect this lesson to separation of concerns so your codebase stays maintainable as it grows.

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 would you apply this concept in a production Flutter feature with clear trade-offs?

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

Lesson Completion Checklist

  • I can explain "E-Commerce 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: Moving forward without checking whether the current concept is truly clear.
  • 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 validate prices on the server before processing a payment?

Client-side code can be modified. A malicious user could change the price in memory. Server-side validation ensures the charged amount matches the actual product price in your database. Trap check: authentication alone does not guarantee price integrity, because rooted or proxied clients can still tamper payload values.

What is the benefit of persisting the cart locally?

Persisting the cart locally (using Hive or SharedPreferences) ensures that users do not lose their selections when they close the app or lose connectivity. Trap check: local persistence improves continuity, but stock, pricing, and promotions still require authoritative server validation.

What pattern organizes the checkout into multiple screens?

A multi-step wizard breaks the checkout into manageable steps: cart review, shipping address, payment method, and confirmation. Flutter Stepper widget is ideal for this pattern. Trap check: tabs and bottom sheets change presentation style, but they do not provide a true step-by-step checkout state machine.

At checkout, the app submits totals from the client. What should the backend do before creating a payment intent?

Payment amount must come from server-side product and pricing rules. Recomputing totals server-side prevents undercharge attacks caused by tampered client payloads.

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.