Flutter持久化购物车插件persistent_shopping_cart的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter持久化购物车插件persistent_shopping_cart的使用

Persistent Shopping Cart

Persistent Shopping Cart 是一个Flutter包,它为您的移动应用程序提供简单且持久的购物车功能。它使用Hive进行本地存储,使购物车数据在应用会话之间保持持久。

Demo Preview

Demo Preview

Features

  • Initialization: 使用init()方法轻松初始化购物车。
  • Add to Cart: 使用addToCart方法将产品添加到购物车。
  • Remove from Cart: 使用removeFromCart方法从购物车中移除产品。
  • Increment/Decrement Quantity: 使用incrementCartItemQuantitydecrementCartItemQuantity方法调整购物车中项目的数量。
  • 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

  1. 在Dart文件中导入包:
    import 'package:persistent_shopping_cart/persistent_shopping_cart.dart';
    
  2. 通过调用init方法初始化购物车:
    await PersistentShoppingCart().init();
    
  3. 开始在您的应用程序中使用购物车功能!

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 回复

更多关于Flutter持久化购物车插件persistent_shopping_cart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter持久化购物车插件persistent_shopping_cart的代码案例。这个插件可以帮助你实现购物车的持久化存储,即使应用重启,购物车数据也不会丢失。

步骤 1: 添加依赖

首先,你需要在你的pubspec.yaml文件中添加persistent_shopping_cart依赖:

dependencies:
  flutter:
    sdk: flutter
  persistent_shopping_cart: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

步骤 2: 初始化购物车

在你的应用入口文件(通常是main.dart)中初始化购物车服务:

import 'package:flutter/material.dart';
import 'package:persistent_shopping_cart/persistent_shopping_cart.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化购物车服务
  final cart = new PersistentCart();
  
  runApp(MyApp(cart: cart));
}

class MyApp extends StatelessWidget {
  final PersistentCart cart;

  MyApp({required this.cart});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(cart: cart),
    );
  }
}

步骤 3: 使用购物车功能

接下来,在你的主屏幕(HomeScreen)中使用购物车功能,例如添加商品到购物车、查看购物车内容等。

import 'package:flutter/material.dart';
import 'package:persistent_shopping_cart/persistent_shopping_cart.dart';

class HomeScreen extends StatefulWidget {
  final PersistentCart cart;

  HomeScreen({required this.cart});

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('购物车示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: '商品名称',
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // 添加商品到购物车
                widget.cart.addItem(_controller.text, quantity: 1);
                setState(() {});  // 更新UI
              },
              child: Text('添加到购物车'),
            ),
            SizedBox(height: 16),
            Divider(),
            SizedBox(height: 16),
            Text('购物车内容:'),
            SizedBox(height: 8),
            Expanded(
              child: ListView.builder(
                itemCount: widget.cart.itemCount,
                itemBuilder: (context, index) {
                  final item = widget.cart.getItemAtIndex(index);
                  return ListTile(
                    title: Text('${item.name} x ${item.quantity}'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 清空购物车
          widget.cart.clear();
          setState(() {});  // 更新UI
        },
        tooltip: '清空购物车',
        child: Icon(Icons.delete),
      ),
    );
  }
}

注意事项

  1. 持久化存储persistent_shopping_cart插件默认使用key-value存储(如NSUserDefaults在iOS或SharedPreferences在Android)来持久化购物车数据。
  2. 复杂数据:如果你的商品数据更复杂(例如包含价格、颜色、大小等),你可能需要自定义一个类来实现CartItem接口。
  3. 异步操作:虽然persistent_shopping_cart的API设计得尽量同步,但在某些平台上(如Web),存储操作可能是异步的。在这种情况下,你可能需要处理异步操作。

这个示例展示了如何使用persistent_shopping_cart插件来实现一个简单的购物车功能,包括添加商品到购物车和查看购物车内容。希望这个示例对你有所帮助!

回到顶部