42 Flutter仿京东商城项目 修改默认收货地址 显示默认收货地址
CheckOut.dart
import 'package:flutter/material.dart'; import '../services/ScreenAdapter.dart'; import 'package:provider/provider.dart'; import '../provider/CheckOut.dart'; import '../services/UserServices.dart'; import '../services/SignServices.dart'; import '../config/Config.dart'; import 'package:dio/dio.dart'; import '../services/EventBus.dart'; class CheckOutPage extends StatefulWidget { CheckOutPage({Key key}) : super(key: key); _CheckOutPageState createState() => _CheckOutPageState(); } class _CheckOutPageState extends State<CheckOutPage> { List _addressList=[]; @override void initState() { super.initState(); this._getDefaultAddress(); //监听广播 eventBus.on<CheckOutEvent>().listen((event) { print(event.str); this._getDefaultAddress(); }); } _getDefaultAddress() async { List userinfo = await UserServices.getUserInfo(); // print('1234'); var tempJson = { "uid": userinfo[0]["_id"], "salt": userinfo[0]["salt"] }; var sign = SignServices.getSign(tempJson); var api = '${Config.domain}api/oneAddressList?uid=${userinfo[0]["_id"]}&sign=${sign}'; var response = await Dio().get(api); print(response); setState(() { this._addressList=response.data['result']; }); } Widget _checkOutItem(item) { return Row( children: <Widget>[ Container( width: ScreenAdapter.width(160), child: Image.network("${item["pic"]}", fit: BoxFit.cover), ), Expanded( flex: 1, child: Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("${item["title"]}", maxLines: 2), Text("${item["selectedAttr"]}", maxLines: 2), Stack( children: <Widget>[ Align( alignment: Alignment.centerLeft, child: Text("¥${item["price"]}", style: TextStyle(color: Colors.red)), ), Align( alignment: Alignment.centerRight, child: Text("x${item["count"]}"), ) ], ) ], ), )) ], ); } @override Widget build(BuildContext context) { var checkOutProvider = Provider.of<CheckOut>(context); return Scaffold( appBar: AppBar( title: Text("结算"), ), body: Stack( children: <Widget>[ ListView( children: <Widget>[ Container( color: Colors.white, child: Column( children: <Widget>[ SizedBox(height: 10), this._addressList.length>0?ListTile( title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("${this._addressList[0]["name"]} ${this._addressList[0]["phone"]}"), SizedBox(height: 10), Text("${this._addressList[0]["address"]}"), ], ), trailing: Icon(Icons.navigate_next), onTap: () { Navigator.pushNamed(context, '/addressList'); }, ):ListTile( leading: Icon(Icons.add_location), title: Center( child: Text("请添加收货地址"), ), trailing: Icon(Icons.navigate_next), onTap: () { Navigator.pushNamed(context, '/addressAdd'); }, ), SizedBox(height: 10), ], ), ), SizedBox(height: 20), Container( color: Colors.white, padding: EdgeInsets.all(ScreenAdapter.width(20)), child: Column( children: checkOutProvider.checkOutListData.map((value) { return Column( children: <Widget>[_checkOutItem(value), Divider()], ); }).toList()), ), SizedBox(height: 20), Container( color: Colors.white, padding: EdgeInsets.all(ScreenAdapter.width(20)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("商品总金额:¥100"), Divider(), Text("立减:¥5"), Divider(), Text("运费:¥0"), ], ), ) ], ), Positioned( bottom: 0, width: ScreenAdapter.width(750), height: ScreenAdapter.height(100), child: Container( padding: EdgeInsets.all(5), width: ScreenAdapter.width(750), height: ScreenAdapter.height(100), decoration: BoxDecoration( color: Colors.white, border: Border(top: BorderSide(width: 1, color: Colors.black26))), child: Stack( children: <Widget>[ Align( alignment: Alignment.centerLeft, child: Text("总价:¥140", style: TextStyle(color: Colors.red)), ), Align( alignment: Alignment.centerRight, child: RaisedButton( child: Text('立即下单', style: TextStyle(color: Colors.white)), color: Colors.red, onPressed: () {}, ), ) ], ), ), ) ], ), ); } }
AddressList.dart
import 'package:flutter/material.dart'; import '../../services/ScreenAdapter.dart'; import '../../services/UserServices.dart'; import '../../services/SignServices.dart'; import '../../config/Config.dart'; import 'package:dio/dio.dart'; import '../../services/EventBus.dart'; class AddressListPage extends StatefulWidget { AddressListPage({Key key}) : super(key: key); _AddressListPageState createState() => _AddressListPageState(); } class _AddressListPageState extends State<AddressListPage> { List addressList = []; @override void initState() { super.initState(); this._getAddressList(); //监听增加收货地址的广播 eventBus.on<AddressEvent>().listen((event) { // print(event.str); this._getAddressList(); }); } //监听页面销毁的事件 dispose(){ super.dispose(); eventBus.fire(new CheckOutEvent('改收货地址成功...')); } //获取收货地址列表 _getAddressList() async { //请求接口 List userinfo = await UserServices.getUserInfo(); var tempJson = {"uid": userinfo[0]['_id'], "salt": userinfo[0]["salt"]}; var sign = SignServices.getSign(tempJson); var api = '${Config.domain}api/addressList?uid=${userinfo[0]['_id']}&sign=${sign}'; var response = await Dio().get(api); // print(response.data["result"]); setState(() { this.addressList = response.data["result"]; }); } //修改默认收货地址 _changeDefaultAddress(id) async{ List userinfo = await UserServices.getUserInfo(); var tempJson = {"uid": userinfo[0]['_id'], "id":id,"salt": userinfo[0]["salt"]}; var sign = SignServices.getSign(tempJson); var api = '${Config.domain}api/changeDefaultAddress'; var response = await Dio().post(api,data:{ "uid": userinfo[0]['_id'], "id":id, "sign":sign }); Navigator.pop(context); } //删除收货地址 _delAddress(id) async{ List userinfo=await UserServices.getUserInfo(); var tempJson={ "uid":userinfo[0]["_id"], "id":id, "salt":userinfo[0]["salt"] }; var sign=SignServices.getSign(tempJson); var api = '${Config.domain}api/deleteAddress'; var response = await Dio().post(api,data:{ "uid":userinfo[0]["_id"], "id":id, "sign":sign }); this._getAddressList(); //删除收货地址完成后重新获取列表 } //弹出框 _showDelAlertDialog(id) async{ var result= await showDialog( barrierDismissible:false, //表示点击灰色背景的时候是否消失弹出框 context:context, builder: (context){ return AlertDialog( title: Text("提示信息!"), content:Text("您确定要删除吗?") , actions: <Widget>[ FlatButton( child: Text("取消"), onPressed: (){ Navigator.pop(context); }, ), FlatButton( child: Text("确定"), onPressed: () async{ //执行删除操作 this._delAddress(id); Navigator.pop(context); }, ) ], ); } ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("收货地址列表"), ), body: Container( child: Stack( children: <Widget>[ ListView.builder( itemCount: this.addressList.length, itemBuilder: (context, index) { if (this.addressList[index]["default_address"] == 1) { return Column( children: <Widget>[ SizedBox(height: 20), ListTile( leading: Icon(Icons.check, color: Colors.red), title: InkWell( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "${this.addressList[index]["name"]} ${this.addressList[index]["phone"]}"), SizedBox(height: 10), Text("${this.addressList[index]["address"]}"), ]), onTap: (){ this._changeDefaultAddress(this.addressList[index]["_id"]); }, onLongPress: (){ this._showDelAlertDialog(this.addressList[index]["_id"]); }, ), trailing: IconButton( icon:Icon(Icons.edit, color: Colors.blue), onPressed: (){ Navigator.pushNamed(context, '/addressEdit',arguments: { "id":this.addressList[index]["_id"], "name":this.addressList[index]["name"], "phone":this.addressList[index]["phone"], "address":this.addressList[index]["address"], }); }, ), ), Divider(height: 20), ], ); } else { return Column( children: <Widget>[ SizedBox(height: 20), ListTile( title:InkWell( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "${this.addressList[index]["name"]} ${this.addressList[index]["phone"]}"), SizedBox(height: 10), Text("${this.addressList[index]["address"]}"), ]), onTap: (){ this._changeDefaultAddress(this.addressList[index]["_id"]); }, onLongPress: (){ this._showDelAlertDialog(this.addressList[index]["_id"]); }, ), trailing: IconButton( icon:Icon(Icons.edit, color: Colors.blue), onPressed: (){ Navigator.pushNamed(context, '/addressEdit',arguments: { "id":this.addressList[index]["_id"], "name":this.addressList[index]["name"], "phone":this.addressList[index]["phone"], "address":this.addressList[index]["address"], }); }, ), ), Divider(height: 20), ], ); } }, ), Positioned( bottom: 0, width: ScreenAdapter.width(750), height: ScreenAdapter.height(88), child: Container( padding: EdgeInsets.all(5), width: ScreenAdapter.width(750), height: ScreenAdapter.height(88), decoration: BoxDecoration( color: Colors.red, border: Border( top: BorderSide(width: 1, color: Colors.black26))), child: InkWell( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(Icons.add, color: Colors.white), Text("增加收货地址", style: TextStyle(color: Colors.white)) ], ), onTap: () { Navigator.pushNamed(context, '/addressAdd'); }, ), ), ) ], ), )); } }
EventBus.dart
import 'package:event_bus/event_bus.dart'; //Bus 初始化 EventBus eventBus = EventBus(); //商品详情广播数据 class ProductContentEvent{ String str; ProductContentEvent(String str){ this.str=str; } } //用户中心广播 class UserEvent{ String str; UserEvent(String str){ this.str=str; } } //收货地址广播 class AddressEvent{ String str; AddressEvent(String str){ this.str=str; } } //结算页面 class CheckOutEvent{ String str; CheckOutEvent(String str){ this.str=str; } }
AddressAdd.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../services/ScreenAdapter.dart'; import '../../widget/JdText.dart'; import '../../widget/JdButton.dart'; import 'package:city_pickers/city_pickers.dart'; import '../../services/UserServices.dart'; import '../../services/SignServices.dart'; import '../../config/Config.dart'; import 'package:dio/dio.dart'; import '../../services/EventBus.dart'; class AddressAddPage extends StatefulWidget { AddressAddPage({Key key}) : super(key: key); _AddressAddPageState createState() => _AddressAddPageState(); } class _AddressAddPageState extends State<AddressAddPage> { String area=''; String name=''; String phone=''; String address=''; //监听页面销毁的事件 dispose(){ super.dispose(); eventBus.fire(new AddressEvent('增加成功...')); eventBus.fire(new CheckOutEvent('改收货地址成功...')); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("增加收货地址"), ), body: Container( padding: EdgeInsets.all(10), child: ListView( children: <Widget>[ SizedBox(height: 20), JdText( text: "收货人姓名", onChanged: (value){ this.name=value; }, ), SizedBox(height: 10), JdText( text: "收货人电话", onChanged: (value){ this.phone=value; }, ), SizedBox(height: 10), Container( padding: EdgeInsets.only(left: 5), height: ScreenAdapter.height(68), decoration: BoxDecoration( border: Border( bottom: BorderSide(width: 1, color: Colors.black12))), child: InkWell( child: Row( children: <Widget>[ Icon(Icons.add_location), this.area.length>0?Text('${this.area}', style: TextStyle(color: Colors.black54)):Text('省/市/区', style: TextStyle(color: Colors.black54)) ], ), onTap: () async{ Result result = await CityPickers.showCityPicker( context: context, cancelWidget: Text("取消", style: TextStyle(color: Colors.blue)), confirmWidget: Text("确定", style: TextStyle(color: Colors.blue)) ); print(result); setState(() { this.area= "${result.provinceName}/${result.cityName}/${result.areaName}"; }); }, ), ), SizedBox(height: 10), JdText( text: "详细地址", maxLines: 4, height: 200, onChanged: (value){ this.address="${this.area} ${value}"; }, ), SizedBox(height: 10), SizedBox(height: 40), JdButton(text: "增加", color: Colors.red,cb: () async{ List userinfo=await UserServices.getUserInfo(); print(userinfo); // print('1234'); var tempJson={ "uid":userinfo[0]["_id"], "name":this.name, "phone":this.phone, "address":this.address, "salt":userinfo[0]["salt"] }; var sign=SignServices.getSign(tempJson); // print(sign); var api = '${Config.domain}api/addAddress'; var result = await Dio().post(api,data:{ "uid":userinfo[0]["_id"], "name":this.name, "phone":this.phone, "address":this.address, "sign":sign }); // if(result.data["success"]){ // } Navigator.pop(context); }) ], ), )); } }