Flutter持久化购物车插件persistent_shopping_cart的使用
Flutter持久化购物车插件persistent_shopping_cart的使用
Persistent Shopping Cart
Persistent Shopping Cart 是一个Flutter包,它为您的移动应用程序提供简单且持久的购物车功能。它使用Hive进行本地存储,使购物车数据在应用会话之间保持持久。
Demo Preview
Features
- Initialization: 使用
init()
方法轻松初始化购物车。 - Add to Cart: 使用
addToCart
方法将产品添加到购物车。 - Remove from Cart: 使用
removeFromCart
方法从购物车中移除产品。 - Increment/Decrement Quantity: 使用
incrementCartItemQuantity
和decrementCartItemQuantity
方法调整购物车中项目的数量。 - Calculate Total Price: 使用
calculateTotalPrice
方法获取购物车中商品的总价。 - Get Cart Item Count: 使用
getCartItemCount
方法检索购物车中的总项目数。 - Clear Cart: 使用
clearCart
方法从购物车中删除所有项目。 - Show Cart Items: 使用
showCartItems
方法显示购物车项目,提供可自定义的小部件用于每个购物车项目和空购物车消息。 - Show Cart Item Count Widget: 使用
showCartItemCountWidget
方法显示显示当前购物车项目数的小部件。 - Show Total Amount Widget: 使用
showTotalAmountWidget
方法显示显示购物车中商品总价的小部件。 - Show and Update Cart Item Widget: 使用
showAndUpdateCartItemWidget
方法显示基于商品是否在购物车中动态更新的小部件。 - Retrieve Cart Data and Total Price: 使用
PersistentShoppingCart
类中的getCartData
方法获取购物车项目列表和总价。
Getting Started
- 在Dart文件中导入包:
import 'package:persistent_shopping_cart/persistent_shopping_cart.dart';
- 通过调用
init
方法初始化购物车:await PersistentShoppingCart().init();
- 开始在您的应用程序中使用购物车功能!
Example Usage
// Add product to the cart
await PersistentShoppingCart().addToCart(PersistentShoppingCartItem());
// Remove product from the cart
await PersistentShoppingCart().removeFromCart(productId);
// Increment product quantity in the cart
await PersistentShoppingCart().incrementCartItemQuantity(productId);
// Decrement product quantity in the cart
await PersistentShoppingCart().decrementCartItemQuantity(productId);
// Get total price of items in the cart
double totalPrice = PersistentShoppingCart().calculateTotalPrice();
// Get total number of items in the cart
int itemCount = PersistentShoppingCart().getCartItemCount();
// Clear the cart
PersistentShoppingCart().clearCart();
// Retrieve cart data and total price
Map<String, dynamic> cartData = PersistentShoppingCart().getCartData();
List<PersistentShoppingCartItem> cartItems = cartData['cartItems'];
double totalPriceFromData = cartData['totalPrice'];
Widgets
Show Cart Items
PersistentShoppingCart().showCartItems(
cartTileWidget: ({required PersistentShoppingCartItem data}) {
// Your custom cart item widget
},
showEmptyCartMsgWidget: YourEmptyCartMessageWidget(),
);
Show Cart Item Count Widget
PersistentShoppingCart().showCartItemCountWidget(
cartItemCountWidgetBuilder: (int itemCount) {
// Your custom widget displaying the cart item count
},
);
Show Total Amount Widget
PersistentShoppingCart().showTotalAmountWidget(
cartTotalAmountWidgetBuilder: (double totalAmount) {
// Your custom widget displaying the total amount
},
);
Show and Update Cart Item Widget
PersistentShoppingCart().showAndUpdateCartItemWidget(
inCartWidget: YourInCartWidget(),
notInCartWidget: YourNotInCartWidget(),
product: yourProduct,
);
示例代码(完整示例demo)
以下是一个完整的示例代码,展示了如何在一个Flutter应用程序中使用persistent_shopping_cart
插件:
// example's main.dart
import 'package:flutter/material.dart';
import 'package:persistent_shopping_cart/model/cart_model.dart';
import 'package:persistent_shopping_cart/persistent_shopping_cart.dart';
import 'package:persistent_shopping_cart_example/model/item_model.dart';
import 'package:persistent_shopping_cart_example/res/components/network_image_widget.dart';
import 'package:persistent_shopping_cart_example/cart_view.dart';
void main() async {
await PersistentShoppingCart().init();
runApp(
MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.dark,
theme: ThemeData(
brightness: Brightness.dark,
useMaterial3: true,
),
home: ProductsScreen(),
),
);
}
class ProductsScreen extends StatelessWidget {
ProductsScreen({super.key});
List<ItemModel> itemsList = const [
ItemModel(productId: '1', productName: 'Fried Fish Burger', productDescription: 'Served with fries & coleslaw', productThumbnail: 'https://taytocafe.com/delivery/assets/products/642da78b9bac1_Double-Tangy-B.png', unitPrice: 30),
ItemModel(productId: '2', productName: 'Loaded Beef Jalapeno', productDescription: '200g Premium beef with jalapeno sauce', productThumbnail: 'https://taytocafe.com/delivery/assets/products/642da91abab43_Loaded-Chicken-Jalapeno-B.png', unitPrice: 30),
ItemModel(productId: '3', productName: 'Crispy Penny Pasta', productDescription: 'Creamy mushroom sauce with three types of bell pepper mushrooms & fried breast fillet', productThumbnail: 'https://taytocafe.com/delivery/assets/products/1671690922.png', unitPrice: 50),
ItemModel(productId: '4', productName: 'Moroccan Fish', productDescription: "Fried filet of fish served with Moroccan sauce sided by veggies & choice of side", productThumbnail: 'https://taytocafe.com/delivery/assets/products/1671691271.png', unitPrice: 20),
ItemModel(productId: '5', productName: 'Creamy Chipotle', productDescription: 'Grilled chicken fillet topped with chipotle sauce', productThumbnail: 'https://taytocafe.com/delivery/assets/products/6569bee77d7c2_12.png', unitPrice: 40),
ItemModel(productId: '6', productName: 'Onion Rings', productDescription: '10 imported crumbed onion rings served with chilli garlic sauce', productThumbnail: 'https://taytocafe.com/delivery/assets/products/1671634436.png', unitPrice: 5),
ItemModel(productId: '7', productName: 'Pizza Fries', productDescription: 'French fries topped with chicken chunks & pizza sauce with Nachos & cheese', productThumbnail: 'https://taytocafe.com/delivery/assets/products/1671634207.png', unitPrice: 10),
];
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: TextButton.icon(
onPressed: () {
PersistentShoppingCart().clearCart();
Navigator.pop(context);
},
icon: const Icon(Icons.logout),
label: const Text('Logout'),
),
),
],
),
),
appBar: AppBar(
title: const Text('Persistent Shopping Cart', style: TextStyle(fontSize: 15)),
centerTitle: true,
actions: [
PersistentShoppingCart().showCartItemCountWidget(
cartItemCountWidgetBuilder: (itemCount) => IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartView()),
);
},
icon: Badge(
label: Text(itemCount.toString()),
child: const Icon(Icons.shopping_bag_outlined),
),
),
),
const SizedBox(width: 20.0)
],
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: ListView.builder(
itemCount: itemsList.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(bottom: 5),
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
NetworkImageWidget(
height: 100,
width: 100,
imageUrl: itemsList[index].productThumbnail.toString(),
),
const SizedBox(width: 10,),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(itemsList[index].productName,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.white),
),
Text(itemsList[index].productDescription,
maxLines: 2,
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
),
const SizedBox(height: 5,),
Text(r"$" + itemsList[index].unitPrice.toString(),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
Align(
alignment: Alignment.centerRight,
child: PersistentShoppingCart().showAndUpdateCartItemWidget(
inCartWidget: Container(
height: 30,
width: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.red),
),
child: Center(
child: Text(
'Remove',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
notInCartWidget: Container(
height: 30,
width: 100,
decoration: BoxDecoration(
border: Border.all(color: Colors.green),
borderRadius: BorderRadius.circular(20),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Center(
child: Text(
'Add to cart',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
),
product: PersistentShoppingCartItem(
productId: index.toString(),
productName: itemsList[index].productName,
productDescription: itemsList[index].productDescription,
unitPrice: double.parse(itemsList[index].unitPrice.toString()),
productThumbnail: itemsList[index].productThumbnail.toString(),
quantity: 2
),
),
)
],
),
)
],
)
],
),
),
),
);
},
),
),
),
);
}
}
以上是关于persistent_shopping_cart
插件的详细介绍和使用方法,希望对您有所帮助!如果您有任何问题或需要进一步的帮助,请随时提问。
更多关于Flutter持久化购物车插件persistent_shopping_cart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复