38 Flutter仿京东商城项目 渲染结算页面商品数据

加群452892873 下载对应38课文件,运行方法,建好项目,直接替换lib目录

CartServices.dart

import 'dart:convert';

import 'Storage.dart';
import '../config/Config.dart';

class CartServices {
  static addCart(item) async {
    //把对象转换成Map类型的数据
    item = CartServices.formatCartData(item);
    try {
      List cartListData = json.decode(await Storage.getString('cartList'));
      bool hasData = cartListData.any((value) {
        return value["_id"] == item['_id'] &&
            value['selectedAttr'] == item['selectedAttr'];
      });
      if (hasData) {
        for (var i = 0; i < cartListData.length; i++) {
          if (cartListData[i]["_id"] == item['_id'] &&
              cartListData[i]['selectedAttr'] == item['selectedAttr']) {
            cartListData[i]['count'] = cartListData[i]['count'] + 1;
          }
        }
        await Storage.setString('cartList', json.encode(cartListData));
      } else {
        cartListData.add(item);
        await Storage.setString('cartList', json.encode(cartListData));
      }
    } catch (e) {
      List tempList = [];
      tempList.add(item);
      await Storage.setString("cartList", json.encode(tempList));
    }
  }

  //过滤数据
  static formatCartData(item) {
    //处理图片:
    String pic = item.pic;
    pic = Config.domain + pic.replaceAll('\', '/');

    final Map data = new Map<String, dynamic>();
    data['_id'] = item.sId;
    data['title'] = item.title;
    //处理string和Int类型的购物车数据:
    if (item.price is int || item.price is double) {
      data['price'] = item.price;
    } else {
      data['price'] = double.parse(item.price);
    }

    data['selectedAttr'] = item.selectedAttr;
    data['count'] = item.count;
    data['pic'] = pic;
    //是否选中
    data['checked'] = true;
    return data;
  }

  //获取购物车选中的数据:
  static getCheckOutData() async{
    List cartListData=[];
    List tempCheckOutData=[];
    try{
      cartListData=json.decode(await Storage.getString('cartList'));
    }catch(e){
      cartListData=[];
    }
    print(cartListData);
    for(var i=0;i<cartListData.length;i++){
      if(cartListData[i]['checked']==true){
        tempCheckOutData.add(cartListData[i]);
      }
    }
    return tempCheckOutData;

  }
}

provider/CheckOut.dart

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

import '../services/Storage.dart';

class CheckOut with ChangeNotifier {
  List _checkOutListData = []; //购物车数据

  List get checkOutListData => this._checkOutListData;
  changeCheckOutListData(data){
    this._checkOutListData=data;
    notifyListeners();
  }
}

原文地址:https://www.cnblogs.com/yiweiyihang/p/11553050.html