import 'package:ecommerce_muse/pages/checkout_page.dart';
import 'package:ecommerce_muse/pages/home_page.dart';
import 'package:flutter/material.dart';
import '../models/cart_item.dart';
import '../models/product.dart';
import '../services/api_service.dart';
import 'Order_page.dart';

class CartPage extends StatefulWidget {
  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {
  List<CartItem> cartItems = [];
  List<Product> products = [];
  double totalPrice = 0.0;

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  _fetchData() async {
    try {
      List<dynamic> data = await ApiService.getShoppingCart();
      setState(() {
        cartItems =
            data[0].map<CartItem>((json) => CartItem.fromJson(json)).toList();
        products =
            data[1].map<Product>((json) => Product.fromJson(json)).toList();
        totalPrice = data[2];
      });
    } catch (e) {
      print(e);
    }
  }

  _updateCart(int productId, int quantity) async {
    try {
      List<dynamic> data = await ApiService.updateCart(productId, quantity);
      setState(() {
        totalPrice = data[0];
        int cartIndex =
            cartItems.indexWhere((item) => item.productId == productId);
        cartItems[cartIndex] = CartItem.fromJson(data[1]);
      });
    } catch (e) {
      print(e);
    }
  }

  _deleteCart(int productId) async {
    try {
      double newTotalPrice = await ApiService.deleteCart(productId);
      setState(() {
        cartItems.removeWhere((item) => item.productId == productId);
        totalPrice = newTotalPrice;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: cartItems.length,
        itemBuilder: (context, index) {
          CartItem cartItem = cartItems[index];
          Product product =
              products.firstWhere((p) => p.id == cartItem.productId);
          return ListTile(
            leading: Image.network(product.imageUrl),
            title: Text(product.name),
            subtitle: Text('价格: ${cartItem.price} 数量: ${cartItem.quantity}'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: Icon(Icons.remove),
                  onPressed: () {
                    _updateCart(cartItem.productId, -1);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    _updateCart(cartItem.productId, 1);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.delete),
                  onPressed: () {
                    _deleteCart(cartItem.productId);
                  },
                ),
              ],
            ),
          );
        },
      ),
      bottomNavigationBar: _buildBottomBar(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //跳转到结算页面
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => CheckoutPage()),
          );
        },
        child: Text('结算'),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget _buildBottomBar() {
    return BottomAppBar(
      child: Container(
        height: 50,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text('总价: $totalPrice'),
            ElevatedButton(
              onPressed: () {
                //跳转到结算页面
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => CheckoutPage()),
                );
              },
              child: Text('结算'),
            ),
          ],
        ),
      ),
    );
  }
}
Flutter 购物车页面 - 悬浮结算按钮和底部栏总价显示

原文地址: https://www.cveoy.top/t/topic/oi9s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录