Flutter: Phase 2 Practice — ShopApp Core Edition
Scattered parts assembled into an engine — Phase 2 assembles independent knowledge into a complete app architecture.
📋 Prerequisites: You need to master the following first
- Lesson 1: Flutter Intro & Environment Setup
- Lesson 2: Dart Language Crash Course
- Lesson 3: Widget Fundamentals
- Lesson 4: Layout System
- Lesson 5: StatefulWidget and Interaction
- Lesson 6: Material Design & Common Widgets
- Lesson 7: Phase 1 Practice — ShopApp Starter
- Lesson 8: Navigation and Routing
- Lesson 9: Form and Input
- Lesson 10: List and Scrolling
- Lesson 11: Networking and REST API
- Lesson 12: State Management — Riverpod
- Lesson 13: Local Storage
1. What You Will Learn
- Architecture layering: Presentation(Widget) → Application(Notifier) → Infrastructure(Dio+Hive)
- Riverpod global state: cartProvider + authProvider + productProvider coordination
- Dio interceptors: auto-attach Bearer Token + 401 auto-refresh
- Hive offline cache: display cached product data when network fails
- Complete user flow: Browse → Add to Cart → Login → Checkout → Order Confirmation (USD settlement)
2. A True Story of Architecture Chaos
(1) Pain Point: Spaghetti Code
Bob's Phase 1 ShopApp Starter launched, but the code is a mess: network requests scattered inside Widgets, state management half setState half callbacks, caching logic written in build methods. Adding a feature requires modifying 5 files, and every release risks introducing bugs. A 100 thousand DAU app can't sustain spaghetti code.
(2) The Three-Layer Architecture Solution
Clean Architecture divides code into three layers: Presentation (UI), Application (business logic/state), and Infrastructure (data sources), with dependencies flowing from outside to inside.
(3) Benefit: Maintainable, Testable, Extensible
After refactoring to three-layer architecture, Bob adds a payment module by simply adding a Notifier + Repository, without touching the UI layer. Unit tests can mock the Repository to test Notifiers, independent of the network.
3. Three-Layer Architecture Design
graph TD
subgraph Presentation
HP2[HomePage]
DP2[DetailPage]
CP2[CartPage]
CK[CheckoutPage]
end
subgraph Application Layer
PN2[ProductNotifier]
CN2[CartNotifier]
AN[AuthNotifier]
end
subgraph Infrastructure
DR2[DioRepository]
HR[HiveCache]
SS2[SecureStorage]
end
HP2 --> PN2
DP2 --> CN2
CP2 --> CN2
CK --> AN
PN2 --> DR2
AN --> SS2
PN2 --> HR
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
(1) Layer Responsibilities
| Layer | Directory | Responsibility | Depends On |
|---|---|---|---|
| Presentation | screens/, widgets/ |
UI rendering + user interaction | Application |
| Application | notifiers/, providers/ |
State management + business logic | Infrastructure |
| Infrastructure | repositories/, storage/, network/ |
Data fetching + persistence | models |
(2) Project Structure
lib/
├── main.dart
├── app.dart # MaterialApp.router
├── core/
│ ├── router.dart # GoRouter config
│ ├── network/
│ │ ├── dio_client.dart # Dio instance + interceptors
│ │ └── api_exception.dart # Unified error
│ └── storage/
│ ├── secure_storage.dart
│ ├── hive_cache.dart
│ └── shared_prefs.dart
├── models/
│ ├── product.dart
│ ├── cart_item.dart
│ ├── order.dart
│ └── user.dart
├── notifiers/
│ ├── auth_notifier.dart
│ ├── product_notifier.dart
│ └── cart_notifier.dart
├── repositories/
│ ├── product_repository.dart
│ ├── auth_repository.dart
│ └── order_repository.dart
└── screens/
├── home_page.dart
├── detail_page.dart
├── cart_page.dart
├── checkout_page.dart
└── login_page.dart
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
4. Infrastructure Layer Implementation
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Dio client wrapper
import 'package:dio/dio.dart';
// ⚙️ Install dependency: flutter pub add dio
// Custom class definition sources:
// - SecureStorage: see Lesson 13 Flutter Secure Storage
// - AuthInterceptor: see Lesson 11 Dio Auth Interceptor
class DioClient {
late final Dio _dio;
DioClient({required String baseUrl, required SecureStorage storage}) {
_dio = Dio(BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
));
_dio.interceptors.addAll([
AuthInterceptor(storage: storage, dio: _dio),
LogInterceptor(requestBody: true, responseBody: true),
]);
}
Future<Response> get(String path, {Map<String, dynamic>? queryParams}) =>
_dio.get(path, queryParameters: queryParams);
Future<Response> post(String path, {dynamic data}) =>
_dio.post(path, data: data);
Future<Response> put(String path, {dynamic data}) =>
_dio.put(path, data: data);
Future<Response> delete(String path) => _dio.delete(path);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Product Repository
import 'package:dio/dio.dart';
// ⚙️ Install dependency: flutter pub add dio
// Custom class definition sources:
// - DioClient: see Lesson 4 Dio client wrapper in this lesson
// - ProductCache: see Lesson 13 Hive Product Cache
// - Product: see Lesson 11 json_serializable model
class ProductRepository {
final DioClient _client;
final ProductCache _cache;
ProductRepository(this._client, this._cache);
Future<List<Product>> getProducts({int page = 1, String? category}) async {
try {
final response = await _client.get('/products', queryParams: {
'page': page, 'limit': 20, if (category != null) 'category': category,
});
final products = (response.data['items'] as List)
.map((j) => Product.fromJson(j)).toList();
await _cache.saveProducts(products);
return products;
} on DioException {
// Offline fallback
final cached = await _cache.getProducts();
if (cached.isNotEmpty) return cached;
rethrow;
}
}
Future<Product> getProductById(int id) async {
final cached = await _cache.getProductById(id);
if (cached != null) return cached;
final response = await _client.get('/products/$id');
return Product.fromJson(response.data);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
5. Application Layer Implementation
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Auth Notifier
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
// ⚙️ Install dependency: flutter pub add flutter_riverpod riverpod_annotation
// ⚙️ Dev dependency: flutter pub add --dev riverpod_generator build_runner
// Custom class definition sources:
// - User: see Lesson 12 @riverpod Auth example
// - secureStorageProvider/authRepoProvider: see Lesson 13 storage layer
@riverpod
class Auth extends _$Auth {
@override
AsyncValue<User?> build() {
// Check stored token on app start
_checkStoredToken();
return const AsyncData(null);
}
Future<void> _checkStoredToken() async {
final storage = ref.read(secureStorageProvider);
final token = await storage.getAccessToken();
if (token != null) {
state = await AsyncValue.guard(() => ref.read(authRepoProvider).validateToken(token));
}
}
Future<void> login(String email, String password) async {
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
final result = await ref.read(authRepoProvider).login(email, password);
await ref.read(secureStorageProvider).saveTokens(
accessToken: result.accessToken, refreshToken: result.refreshToken, userId: result.user.id,
);
return result.user;
});
}
Future<void> logout() async {
await ref.read(secureStorageProvider).clearAll();
state = const AsyncData(null);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Cart Notifier (persistent version)
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
// ⚙️ Install dependency: flutter pub add flutter_riverpod riverpod_annotation
// ⚙️ Dev dependency: flutter pub add --dev riverpod_generator build_runner
// Custom class definition sources:
// - CartItem: see Lesson 12 CartNotifier example
// - Product: see Lesson 11 json_serializable model
// - cartStorageProvider: see Lesson 13 Hive cart persistence
@riverpod
class Cart extends _$Cart {
@override
List<CartItem> build() {
// Load from local storage on init
_loadFromStorage();
return [];
}
Future<void> _loadFromStorage() async {
final storage = ref.read(cartStorageProvider);
final items = await storage.loadCart();
if (items.isNotEmpty) {
state = items;
}
}
Future<void> _persist() async {
final storage = ref.read(cartStorageProvider);
await storage.saveCart(state);
}
void addItem(Product product) {
final idx = state.indexWhere((i) => i.product.id == product.id);
if (idx >= 0) {
state = [...state]..[idx] = state[idx].copyWith(quantity: state[idx].quantity + 1);
} else {
state = [...state, CartItem(product: product, quantity: 1)];
}
_persist();
}
void updateQuantity(int productId, int qty) {
if (qty <= 0) { removeItem(productId); return; }
state = [for (final i in state) i.product.id == productId ? i.copyWith(quantity: qty) : i];
_persist();
}
void removeItem(int productId) {
state = state.where((i) => i.product.id != productId).toList();
_persist();
}
void clear() { state = []; _persist(); }
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
6. Presentation Layer Implementation
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: GoRouter auth guard
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
// ⚙️ Install dependency: flutter pub add flutter_riverpod go_router
// Custom class definition sources:
// - authProvider: see Lesson 5 Auth Notifier in this lesson
// - MainScaffold: custom Shell route container Widget
final router = GoRouter(
initialLocation: '/',
redirect: (context, state) {
final authState = ProviderScope.containerOf(context).read(authProvider);
final isLoggedIn = authState.valueOrNull != null;
final isLoginRoute = state.matchedLocation == '/login';
if (!isLoggedIn && !isLoginRoute) return '/login';
if (isLoggedIn && isLoginRoute) return '/';
return null;
},
routes: [
ShellRoute(
builder: (_, __, child) => MainScaffold(child: child),
routes: [
GoRoute(path: '/', builder: (_, __) => const HomePage()),
GoRoute(path: '/cart', builder: (_, __) => const CartPage()),
GoRoute(path: '/profile', builder: (_, __) => const ProfilePage()),
],
),
GoRoute(path: '/product/:id', builder: (_, s) => DetailPage(id: int.parse(s.pathParameters['id']!))),
GoRoute(path: '/checkout', builder: (_, __) => const CheckoutPage()),
GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
],
);
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: HomePage consuming Providers
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
// ⚙️ Install dependency: flutter pub add flutter_riverpod go_router
// Custom class definition sources:
// - productProvider/cartItemCountProvider/cartProvider: see Lesson 12
// - ProductCard: custom product card Widget
class HomePage extends ConsumerWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final productsAsync = ref.watch(productProvider);
final cartCount = ref.watch(cartItemCountProvider);
return Scaffold(
appBar: AppBar(title: const Text('ShopApp'), actions: [
Badge(count: cartCount, child: IconButton(icon: const Icon(Icons.shopping_cart),
onPressed: () => context.go('/cart'))),
]),
body: productsAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (err, _) => Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Text('Error: $err'), const SizedBox(height: 16),
FilledButton(onPressed: () => ref.read(productProvider.notifier).refresh(), child: const Text('Retry')),
])),
data: (products) => RefreshIndicator(
onRefresh: () => ref.read(productProvider.notifier).refresh(),
child: GridView.builder(gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.7),
itemCount: products.length,
itemBuilder: (_, i) => ProductCard(product: products[i], onAddToCart: () {
ref.read(cartProvider.notifier).addItem(products[i]);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${products[i].name} added to cart'), duration: const Duration(seconds: 1)));
}),
),
),
),
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
7. Complete Example: main.dart Startup Flow
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ⚙️ Install dependency: flutter pub add flutter_riverpod shared_preferences
// Custom class definition sources:
// - DioClient: see Lesson 4 in this lesson
// - SecureStorage: see Lesson 13
// - initHive(): see Lesson 13 Hive initialization
// - ShopApp: custom MaterialApp Widget
// - sharedPreferencesProvider/dioClientProvider: Riverpod Provider
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize storage
await initHive();
final prefs = await SharedPreferences.getInstance();
final dioClient = DioClient(baseUrl: 'https://api.shopapp.com/v1', storage: SecureStorage());
runApp(ProviderScope(
overrides: [
sharedPreferencesProvider.overrideWithValue(prefs),
dioClientProvider.overrideWithValue(dioClient),
],
child: const ShopApp(),
));
}
class ShopApp extends ConsumerWidget {
const ShopApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp.router(
title: 'ShopApp',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorSchemeSeed: Colors.blue, useMaterial3: true),
routerConfig: router,
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
❓ FAQ
ProviderScope.containerOf(context).read(provider) to read Providers inside redirect.await Hive.deleteBoxFromDisk('products').📖 Summary
- Three-layer architecture: Presentation → Application → Infrastructure, with one-way dependency direction
- Riverpod Notifiers manage business logic and state; Repositories manage data fetching
- Dio interceptors uniformly handle Token attachment and 401 refresh
- Hive caching enables offline fallback, displaying cached data when network fails
- GoRouter redirect implements route auth guards
📝 Exercises
- Basic (⭐): Refactor the Phase 1 project using three-layer architecture, extracting network requests from Widgets into Repositories.
- Intermediate (⭐⭐): Add Auth Notifier + SecureStorage, implementing login state persistence and 401 auto-refresh.
- Challenge (⭐⭐⭐): Implement the complete user flow: browse products (offline cache) → add to cart (persistent) → login (token refresh) → checkout (form validation) → order confirmation, with graceful degradation at every step when network fails.