Flutter实战视频-移动电商-57.购物车_在Model中增加选中字段

57.购物车_在Model中增加选中字段

 

先修改model类

model/cartInfo.dart类增加是否选中的属性

修改provide

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

 

 

测试效果

出现问题的原因,应该是在购物车内持久化的数据,没有isCheck这个新增加的属性,所以就报错了我们需要先点进去一个商品,把持久化的购物车数据清空掉,再重新添加购物车的持久化数据

然后重新添加几个商品到购物车内

 

最终代码

model/cartInfo.dart

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.dart

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

 

posted @ 2019-04-28 22:50  高山-景行  阅读(584)  评论(0编辑  收藏  举报