Flutter 商城商品详情页添加购物车和结算功能
import 'package:cached_network_image/cached_network_image.dart'; import 'package:ecommerce_muse/models/product.dart'; import 'package:ecommerce_muse/services/api_service.dart'; import 'package:flutter/material.dart';
class ProductDetailPage extends StatefulWidget { final int productId;
ProductDetailPage({required this.productId});
@override _ProductDetailPageState createState() => _ProductDetailPageState(productId: productId); }
class _ProductDetailPageState extends State
_ProductDetailPageState({required this.productId});
@override void initState() { super.initState(); _productFuture = ApiService.getProductDetail(productId); }
void _addToCart(BuildContext context) async { try { String result = await ApiService.addToCart(productId: productId, quantity: _quantity); if (result == 'success') { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('添加到购物车成功')), ); } } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('添加到购物车失败')), ); } }
void _showCart(BuildContext context) { showModalBottomSheet( context: context, builder: (BuildContext context) { return Container( height: 300, child: Center( child: Text('购物车内容'), ), ); }, ); }
void _navigateToCheckout(BuildContext context) { Navigator.pushNamed(context, '/checkout'); }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('商品详情'),
),
body: FutureBuilder
Widget _buildProductDetail(Product product) { return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CachedNetworkImage( imageUrl: product.imageUrl, fit: BoxFit.cover, errorWidget: (context, url, error) => Icon(Icons.error), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( product.name, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), SizedBox(height: 8), Text( '价格: ¥${product.price.toStringAsFixed(2)}', style: TextStyle(fontSize: 18), ), SizedBox(height: 8), Text( '品牌: ${product.brand}', style: TextStyle(fontSize: 18), ), SizedBox(height: 8), Text( '描述: ${product.description}', style: TextStyle(fontSize: 18), ), SizedBox(height: 8), Row( children: [ Text( '数量:', style: TextStyle(fontSize: 18), ), SizedBox(width: 8), IconButton( onPressed: () { setState(() { if (_quantity > 1) { _quantity--; } }); }, icon: Icon(Icons.remove), ), Text( '$_quantity', style: TextStyle(fontSize: 18), ), IconButton( onPressed: () { setState(() { _quantity++; }); }, icon: Icon(Icons.add), ), ], ), SizedBox(height: 8), ElevatedButton( onPressed: () => _navigateToCheckout(context), child: Text('结算'), ), ], ), ), ], ), ); } }
原文地址: https://www.cveoy.top/t/topic/oieY 著作权归作者所有。请勿转载和采集!