flutter 購物車功能

嬌嫩的黃瓜發表於2019-01-25

flutter 購物車功能
flutter 購物車功能
flutter 購物車功能
flutter 購物車功能

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/http/Api.dart';
import 'package:flutter_app/http/ApiService.dart';
import 'package:flutter_app/ui/main/bean/ShopCartBean.dart';

import 'package:flutter_slidable/flutter_slidable.dart';//側滑刪除


class ShopPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new ShopPageState();
}

class ShopPageState extends State<ShopPage> {
  List<ShopCartResult> _list = new List();
  var money = 0.00;
  var selectCount = 0;
  var listItemCount = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _categoryChild();
  }

  bool isSelect = false;

  void _categoryChild() {
    ApiService.getLogin("toBuy/list", "POST", null, (callBack) {
      if (callBack != null) {
        var categoryChildBean = ShopCartBean.fromJson(callBack);
        if (categoryChildBean.success) {
          _list.clear();
          _list = categoryChildBean.result;
          isSelect = _viewSelect();
          _listMoneyCount();
        }
      }
    }, (errorCallBack) => {});
  }

  _viewSelect() {
    var count = 0;
    for (var i = 0; i < _list.length; i++) {
      if (_list[i].selected) {
        count++;
      }
    }
    return count == _list.length;
  }

  @override
  Widget build(BuildContext context) {
// TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        automaticallyImplyLeading: false, //左邊按鈕
        centerTitle: true,
        title: new Text(
          "購物車($listItemCount)",
          style: new TextStyle(color: Colors.white, fontSize: 20.0),
        ),
        backgroundColor: Colors.red,
      ),
      body: new Column(
        children: <Widget>[
          new Expanded(
              child: Container(
            child: new ListView(
              children: _itemView(),
              padding: new EdgeInsets.only(bottom: 10),
            ),
            width: double.infinity,
            color: Colors.grey,
          )),
          Row(
            children: <Widget>[
              new Checkbox(
                  value: isSelect,
                  activeColor: Color.fromARGB(255, 255, 67, 78),
                  onChanged: (bool) {
                    for (var i = 0; i < _list.length; i++) {
                      _list[i].selected = !isSelect;
                      for (var j = 0; j < _list[i].goodsToBuyDtos.length; j++) {
                        _list[i].goodsToBuyDtos[j].selected = !isSelect;
                      }
                    }
                    isSelect = !isSelect;
                    _listMoneyCount();
                    setState(() {});
                  }),
              Text("全選"),
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "不含運費 ",
                      style: TextStyle(color: Colors.grey, fontSize: 10),
                    ),
                    Text(
                      "合計:",
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                    Text(
                      "¥",
                      style: TextStyle(color: Colors.red, fontSize: 12),
                    ),
                    Text(
                      "$money",
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 16,
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: new Text(
                        "結算($selectCount)",
                        style: TextStyle(color: Colors.white),
                      ),
                      width: 130,
                      height: 50,
                      color: Colors.red,
                    )
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  List<Widget> _itemView() {
    List<Widget> listWidget = List();
    for (var i = 0; i < _list.length; i++) {
      var item = _list[i].selected;
      listWidget.add(new Card(
        color: Colors.white,
        elevation: 0,
        margin: new EdgeInsets.only(left: 10, right: 10, top: 10),
        child: Column(
          children: _itemViewChild(i, item),
        ),
      ));
    }
    return listWidget;
  }

  List<Widget> _itemViewChild(int index, bool item) {
    var row = new Row(
      children: <Widget>[
        new Checkbox(
            value: item,
            activeColor: Color.fromARGB(255, 255, 67, 78),
            onChanged: (bool) {
              _list[index].selected = !item;
              for (var j = 0; j < _list[index].goodsToBuyDtos.length; j++) {
                _list[index].goodsToBuyDtos[j].selected = !item;
              }
              isSelect = _viewSelect();
              _listMoneyCount();
              setState(() {});
            }),
        Text(null != _list[index].storeName ? _list[index].storeName : "")
      ],
    );
    List<Widget> listWidget = List();
    listWidget.clear();
    listWidget.add(row);
    listWidget.add(new Baseline(
      baseline: 1,
      baselineType: TextBaseline.alphabetic,
      child: new Container(
        color: Color(0xFFededed),
        height: 1,
        width: double.infinity,
      ),
    ));

    List<Widget> listWidgetChild = List();
    listWidgetChild.clear();
    for (var b = 0; b < _list[index].goodsToBuyDtos.length; b++) {
      var selected = _list[index].goodsToBuyDtos[b].selected;
      listWidgetChild.add(new Padding(
        padding: EdgeInsets.only(top: 10, bottom: 10),
        child: new Slidable(
            child: new Container(
              child: new Row(
                children: <Widget>[
                  new Checkbox(
                      value: selected,
                      activeColor: Color.fromARGB(255, 255, 67, 78),
                      onChanged: (bool) {
                        _list[index].goodsToBuyDtos[b].selected = !selected;
                        var count = 0;
                        _list[index].goodsToBuyDtos.forEach((fe) {
                          if (fe.selected) {
                            count++;
                          }
                        });
                        _list[index].selected =
                            count == _list[index].goodsToBuyDtos.length;
                        isSelect = _viewSelect();
                        _listMoneyCount();
                        setState(() {});
                      }),
                  new Image.network(
                    Api.getInstance().photo +
                        _list[index].goodsToBuyDtos[b].path,
                    fit: BoxFit.fill,
                    width: 80,
                    height: 80,
                  ),
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.only(left: 5, right: 5),
                      child: new Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            _list[index].goodsToBuyDtos[b].name,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          new Expanded(
                              child: new Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Text(
                                _list[index].goodsToBuyDtos[b].skuCfg,
                                softWrap: false,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Text(
                                "¥${_list[index].goodsToBuyDtos[b].price}",
                                style: TextStyle(color: Colors.red),
                                softWrap: false,
                                overflow: TextOverflow.ellipsis,
                              )
                            ],
                          ))
                        ],
                      ),
                    ),
                  )
                ],
              ),
              height: 85,
            ),
            delegate: new SlidableDrawerDelegate(),
            secondaryActions: <Widget>[
              new IconSlideAction(
                caption: '刪除',
                color: Colors.red,
                icon: Icons.delete,
                onTap: () => {},
              ),
            ]),
      ));
    }
    listWidget.add(new Column(
      children: listWidgetChild,
    ));
    return listWidget;
  }

  //計算金額
  _listMoneyCount() {
    money = 0.00;
    selectCount = 0;
    listItemCount = 0;
    _list.forEach((f) {
      f.goodsToBuyDtos.forEach((item) {
        if (item.selected) {
          var itemMoney = double.parse(item.price) * double.parse(item.count);
          money = money + itemMoney;
          selectCount++;
        }
        listItemCount++;
      });
    });
  }
}


複製程式碼

ShopCartBean

import 'package:json_annotation/json_annotation.dart';

part 'ShopCartBean.g.dart';


@JsonSerializable()
class ShopCartBean {

  @JsonKey(name: 'code')
  String code;

  @JsonKey(name: 'msg')
  String msg;

  @JsonKey(name: 'result')
  List<ShopCartResult> result;

  @JsonKey(name: 'success')
  bool success;

  ShopCartBean(this.code,this.msg,this.result,this.success,);

  factory ShopCartBean.fromJson(Map<String, dynamic> srcJson) => _$ShopCartBeanFromJson(srcJson);

}


@JsonSerializable()
class ShopCartResult {

  @JsonKey(name: 'couponShow')
  bool couponShow;

  @JsonKey(name: 'goodsIdStr')
  String goodsIdStr;

  @JsonKey(name: 'goodsToBuyDtos')
  List<GoodsToBuyDtos> goodsToBuyDtos;

  @JsonKey(name: 'selected')
  bool selected;

  @JsonKey(name: 'storeId')
  String storeId;

  @JsonKey(name: 'storeName')
  String storeName;

  ShopCartResult(this.couponShow,this.goodsIdStr,this.goodsToBuyDtos,this.selected,this.storeId,this.storeName,);

  factory ShopCartResult.fromJson(Map<String, dynamic> srcJson) => _$ShopCartResultFromJson(srcJson);

}


@JsonSerializable()
class GoodsToBuyDtos {

  @JsonKey(name: 'count')
  String count;

  @JsonKey(name: 'dValue')
  String dValue;

  @JsonKey(name: 'fee')
  String fee;

  @JsonKey(name: 'goodsId')
  String goodsId;

  @JsonKey(name: 'id')
  String id;

  @JsonKey(name: 'inventory')
  String inventory;

  @JsonKey(name: 'isGoodsNew')
  bool isGoodsNew;

  @JsonKey(name: 'limitDesc')
  String limitDesc;

  @JsonKey(name: 'maxBatch')
  String maxBatch;

  @JsonKey(name: 'memo')
  String memo;

  @JsonKey(name: 'minBatch')
  String minBatch;

  @JsonKey(name: 'name')
  String name;

  @JsonKey(name: 'path')
  String path;

  @JsonKey(name: 'price')
  String price;

  @JsonKey(name: 'selected')
  bool selected;

  @JsonKey(name: 'skuCfg')
  String skuCfg;

  @JsonKey(name: 'standardCfg')
  String standardCfg;

  @JsonKey(name: 'status')
  String status;

  @JsonKey(name: 'storeType')
  String storeType;

  GoodsToBuyDtos(this.count,this.dValue,this.fee,this.goodsId,this.id,this.inventory,this.isGoodsNew,this.limitDesc,this.maxBatch,this.memo,this.minBatch,this.name,this.path,this.price,this.selected,this.skuCfg,this.standardCfg,this.status,this.storeType,);

  factory GoodsToBuyDtos.fromJson(Map<String, dynamic> srcJson) => _$GoodsToBuyDtosFromJson(srcJson);

}



複製程式碼

本人剛剛坑,程式碼沒有進行拆分等優化 只是做了頁面效果以及選中和未選中等邏輯操作(刪除邏輯暫時沒有寫)

資料可以自己新增假資料

相關文章