import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert';

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

class _CartPageState extends State { List _cartList = []; double _totalPrice = 0; bool _isLoading = true;

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

Future _getCartList() async { try { http.Response response = await http.get( 'http://book.musecloud.tech/getshoppingcart', ); List jsonData = jsonDecode(response.body); setState(() { _cartList = jsonData[0]; _totalPrice = jsonData[2]; _isLoading = false; }); } catch (e) { throw e; } }

Future _updateCart(int productId, int quantity) async { try { http.Response response = await http.post( 'http://book.musecloud.tech/updatecart', body: { 'productId': productId.toString(), 'quantity': quantity.toString(), }, ); List jsonData = jsonDecode(response.body); setState(() { _totalPrice = jsonData[0]; _cartList = _cartList.map((cart) { if (cart[1]['id'] == productId) { cart[1]['quantity'] = jsonData[1]['quantity']; cart[1]['price'] = jsonData[1]['price']; } return cart; }).toList(); }); } catch (e) { throw e; } }

Future _deleteCart(int productId) async { try { http.Response response = await http.post( 'http://book.musecloud.tech/deletecart', body: { 'productId': productId.toString(), }, ); setState(() { _totalPrice = double.parse(response.body); _cartList.removeWhere((cart) => cart[1]['id'] == productId); }); } catch (e) { throw e; } }

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('购物车'), ), body: _isLoading ? Center( child: CircularProgressIndicator(), ) : _cartList.isEmpty ? Center( child: Text('购物车为空'), ) : Column( children: [ Expanded( child: ListView.builder( itemCount: _cartList.length, itemBuilder: (BuildContext context, int index) { final cart = _cartList[index]; final product = cart[1]; return ListTile( leading: Image.network( product['imageUrl'], width: 50, height: 50, ), title: Text(product['name']), subtitle: Text( '¥${cart[1]['price']} × ${cart[1]['quantity']}'), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( onPressed: () { _updateCart(cart[1]['id'], cart[1]['quantity'] + 1); }, icon: Icon(Icons.add), ), Text('${cart[1]['quantity']}'), IconButton( onPressed: () { _updateCart(cart[1]['id'], cart[1]['quantity'] - 1); }, icon: Icon(Icons.remove), ), IconButton( onPressed: () { _deleteCart(cart[1]['id']); }, icon: Icon(Icons.delete), ), ], ), ); }, ), ), Container( padding: EdgeInsets.all(16), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('总价:¥${_totalPrice.toStringAsFixed(2)}'), ElevatedButton( onPressed: () { // TODO: 结算 }, child: Text('结算'), ), ], ), SizedBox(height: 16), TextButton( onPressed: () { // TODO: 新增地址 }, child: Text('新增地址'), ), SizedBox(height: 16), Text( '选择地址', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, ), ), SizedBox(height: 16), FutureBuilder<List>( future: _getAddressList(), builder: (context, snapshot) { if (snapshot.hasData) { final addressList = snapshot.data!; return ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: addressList.length, itemBuilder: (BuildContext context, int index) { final address = addressList[index]; return RadioListTile( value: address['id'], groupValue: 0, onChanged: (value) { // TODO: 选择地址 }, title: Text( '${address['name']} ${address['phone']}', style: TextStyle( fontWeight: FontWeight.bold, ), ), subtitle: Text( '${address['provience']}${address['city']}${address['district']}${address['addressLine']}', ), ); }, ); } else if (snapshot.hasError) { return Text('获取地址列表失败'); } else { return Center( child: CircularProgressIndicator(), ); } }, ), SizedBox(height: 16), Text( '选择支付方式', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, ), ), SizedBox(height: 16), Row( children: [ Radio( value: 1, groupValue: 0, onChanged: (value) { // TODO: 选择支付宝 }, ), Text('支付宝'), ], ), Row( children: [ Radio( value: 2, groupValue: 0, onChanged: (value) { // TODO: 选择微信 }, ), Text('微信'), ], ), ], ), ), ], ), ); }

Future<List> _getAddressList() async { try { http.Response response = await http.get( 'http://book.musecloud.tech/getaddresses', ); List jsonData = jsonDecode(response.body); return jsonData; } catch (e) { throw e; } } }

Flutter 购物车页面开发实战:UI设计、数据解析、API 调用

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

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