Flutter實戰視頻-移動電商-57.購物車_在Model中增長選中字段

57.購物車_在Model中增長選中字段

 

先修改model類

model/cartInfo.dart類增長是否選中的屬性json

修改provide

修改UI部分pages/cart_page/cart_item.dart

 

 

測試效果

出現問題的緣由,應該是在購物車內持久化的數據,沒有isCheck這個新增長的屬性,因此就報錯了咱們須要先點進去一個商品,把持久化的購物車數據清空掉,再從新添加購物車的持久化數據less

而後從新添加幾個商品到購物車內異步

 

最終代碼

model/cartInfo.dartasync

class CartInfoModel {
  String goodsId;
  String goodsName;
  int count;
  double price;
  String images;
  bool isCheck;

  CartInfoModel(
      {this.goodsId, this.goodsName, this.count, this.price, this.images, this.isCheck});

  CartInfoModel.fromJson(Map<String, dynamic> json) {
    goodsId = json['goodsId'];
    goodsName = json['goodsName'];
    count = json['count'];
    price = json['price'];
    images = json['images'];
    isCheck = json['isCheck'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['goodsId'] = this.goodsId;
    data['goodsName'] = this.goodsName;
    data['count'] = this.count;
    data['price'] = this.price;
    data['images'] = this.images;
    data['isCheck'] = this.isCheck;
    return data;
  }
}
View Code

 

 

provide/cart.dartide

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../model/cartInfo.dart';

class CartProvide with ChangeNotifier{
  String cartString="[]";//聲明一個變量 作持久化的存儲
  List<CartInfoModel> cartList=[];

  //聲明一個異步的方法,購物車操做放在前臺不在請求後臺的數據
  save(goodsId,goodsName,count,price,images) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString= prefs.getString('cartInfo');//先從持久化中獲取
    var temp = cartString==null?[]:json.decode(cartString.toString());
    //聲明list 強制類型是Map
    List<Map> tempList=(temp as List).cast();//把temp轉成list
    bool isHave=false;//是否已經存在了這條記錄
    int ival=0;//foreach循環的索引
    //循環判斷列表是否存在該goodsId的商品,若是有就數量+1
    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        tempList[ival]['count']=item['count']+1;
        cartList[ival].count++;
        isHave=true;
      }
      ival++;
    });
    //沒有不存在這個商品,就把商品的json數據加入的tempList中
    if(!isHave){
      Map<String,dynamic> newGoods={
        'goodsId':goodsId,//傳入進來的值
        'goodsName':goodsName,
        'count':count,
        'price':price,
        'images':images,
        'isCheck':true
      };
      tempList.add(newGoods);
      cartList.add(CartInfoModel.fromJson(newGoods));
    }
    cartString=json.encode(tempList).toString();//json數據轉字符串
    // print('字符串》》》》》》》》》》》${cartString}');
    // print('字符串》》》》》》》》》》》${cartList}');

    prefs.setString('cartInfo', cartString);
    notifyListeners();
  }
  remove() async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    prefs.remove('cartInfo');
    cartList=[];
    print('清空完成----------------------');
    notifyListeners();
  }

  getCartInfo() async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');//持久化中得到字符串
    print('購物車持久化的數據================>'+cartString);
    cartList=[];//把最終的結果先設置爲空list
    if(cartString==null){
      cartList=[];//若是持久化內沒有數據 那麼就仍是空的list
    }else{
      //聲明臨時的變量
      List<Map> tempList=(json.decode(cartString.toString()) as List).cast();
      tempList.forEach((item){
        cartList.add(CartInfoModel.fromJson(item));//json轉成對象,加入到cartList中
      });
      
    }
    notifyListeners();//通知
  }


}
View Code

 

 

pages/cart_page/cart_item.dart測試

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../model/cartInfo.dart';
import './cart_count.dart';

class CartItem extends StatelessWidget {
  final CartInfoModel item;
  CartItem(this.item);


  @override
  Widget build(BuildContext context) {
   //print(item);
    return Container(
      margin: EdgeInsets.fromLTRB(5.0, 2.0, 5.0, 2.0),
      padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 1,color: Colors.black12)
        )
      ),
      child: Row(
        children: <Widget>[
          _cartCheckBt(context,item),
          _cartImage(),
          _cartGoodsName(),
          _cartPrice()
        ],
      ),
    );
  }
  //複選框
  Widget _cartCheckBt(context,item){
    return Container(
      child: Checkbox(
        value: item.isCheck,//這裏的值變成動態的
        activeColor: Colors.pink,//激活顏色設置爲粉色
        onChanged:(bool val){

        }
      ),
    );
  }
  //商品圖片
  Widget _cartImage(){
    return Container(
      width: ScreenUtil().setWidth(150),
      padding: EdgeInsets.all(3.0),//內邊距
      decoration: BoxDecoration(
        border: Border.all(width:1.0,color: Colors.black12)
      ),
      child: Image.network(item.images),//item聲明好了 因此不用傳遞
    );
  }

  //商品名稱
  Widget _cartGoodsName() {
    return Container(
      width: ScreenUtil().setWidth(300),
      padding: EdgeInsets.all(10),
      alignment: Alignment.topLeft,//頂端左對齊
      child: Column(
        children: <Widget>[
          Text(item.goodsName),
          CartCount()
        ],
      ),
    );
  }

  //商品價格
  Widget _cartPrice() {
    return Container(
      width: ScreenUtil().setWidth(150),//只要合起來不超過750 就不會溢出
      alignment: Alignment.centerRight,//居中靠右
      child: Column(
        children: <Widget>[
          Text('¥${item.price}'),
          Container(//用來放icon刪除按鈕
            child: InkWell(
              onTap: (){},
              child: Icon(
                Icons.delete_forever,
                color: Colors.black26,//淺灰色
                size: 30,
              ),
            ),
          )
        ],
      ),
    );
  }

}
View Code
相關文章
相關標籤/搜索