Flutter电商应用 #
一、项目概述 #
电商应用是一个完整的Flutter项目,涵盖状态管理、网络请求、本地存储等。
二、项目架构 #
text
lib/
├── main.dart
├── app.dart
├── models/
│ ├── product.dart
│ ├── cart_item.dart
│ └── user.dart
├── providers/
│ ├── products_provider.dart
│ ├── cart_provider.dart
│ └── auth_provider.dart
├── services/
│ ├── api_service.dart
│ └── storage_service.dart
├── screens/
│ ├── home/
│ ├── product/
│ ├── cart/
│ └── profile/
├── widgets/
│ ├── product_card.dart
│ └── cart_item_widget.dart
└── utils/
├── constants.dart
└── validators.dart
三、核心功能 #
3.1 商品列表 #
dart
class ProductsProvider extends ChangeNotifier {
List<Product> _products = [];
bool _isLoading = false;
List<Product> get products => _products;
bool get isLoading => _isLoading;
Future<void> fetchProducts() async {
_isLoading = true;
notifyListeners();
try {
_products = await ApiService().getProducts();
} finally {
_isLoading = false;
notifyListeners();
}
}
}
3.2 购物车 #
dart
class CartProvider extends ChangeNotifier {
final Map<String, CartItem> _items = {};
Map<String, CartItem> get items => _items;
int get itemCount => _items.length;
double get totalAmount =>
_items.values.fold(0, (sum, item) => sum + item.price * item.quantity);
void addItem(Product product) {
if (_items.containsKey(product.id)) {
_items[product.id]!.quantity++;
} else {
_items[product.id] = CartItem(
id: product.id,
title: product.title,
price: product.price,
quantity: 1,
);
}
notifyListeners();
}
void removeItem(String productId) {
_items.remove(productId);
notifyListeners();
}
void clear() {
_items.clear();
notifyListeners();
}
}
四、总结 #
电商应用展示了Flutter完整项目架构。
4.1 恭喜 #
你已经完成了Flutter完全指南的学习!
最后更新:2026-03-28