Flutter實戰視頻-移動電商-58.購物車_刪除商品功能製做

58.購物車_刪除商品功能製做

主要作購物車後面的刪除按鈕json

 

刪除的方法寫在provide裏面app

provide/cart.dart文件

傳入goodsId,循環對比,找到後進行移除less

 

  //刪除單個購物車商品
  deleteOneGoods(String goodsId) async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    List<Map> tempList=(json.decode(cartString.toString()) as List).cast();
    int tempIndex=0;//定義循環的索引
    int deleteIndex=0;//要刪除的索引
    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        deleteIndex=tempIndex;
      }
      tempIndex++;
    });
    tempList.removeAt(deleteIndex);//刪除
    //刪除後轉換成string進行持久化
    cartString=json.encode(tempList.toString());//list轉字符串
    prefs.setString('cartInfo', cartString);
    await getCartInfo();//從新獲取下列表數據,由於getCartInfo方法裏面有通知,這裏就再也不調用了
  }

 

ui內增長刪除的事件

cart_page.dart文件內,咱們須要在ListView的外層套一層Provide組件異步

 

這樣咱們購物車的數據就是動態的了async

刪除的事件-cart_item.dart

先引入cartProvide和provideide

傳入上下文context,和item當前這個商品對象ui

 

 

運行程序查看效果

 

修正一個錯誤的地方,應該是先encode再去toString()this

最終代碼

provide/cart.dartspa

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();//通知
  }

  //刪除單個購物車商品
  deleteOneGoods(String goodsId) async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    List<Map> tempList=(json.decode(cartString.toString()) as List).cast();
    int tempIndex=0;//定義循環的索引
    int deleteIndex=0;//要刪除的索引
    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        deleteIndex=tempIndex;
      }
      tempIndex++;
    });
    tempList.removeAt(deleteIndex);//刪除
    //刪除後轉換成string進行持久化
    cartString=json.encode(tempList).toString();//list轉字符串
    prefs.setString('cartInfo', cartString);
    await getCartInfo();//從新獲取下列表數據,由於getCartInfo方法裏面有通知,這裏就再也不調用了
  }


}
View Code

 

cart_page.dart:列表外層嵌套provide,數據從provide內獲取.net

import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import 'package:flutter_shop/provide/cart.dart';
import 'cart_page/cart_item.dart';
import 'cart_page/cart_bottom.dart';


class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('購物車'),
      ),
      body: FutureBuilder(
        future: _getCartInfo(context),
        builder: (context,snapshot){
          if(snapshot.hasData){
           
            List cartList=Provide.value<CartProvide>(context).cartList;
            //return Text('有數據啊'+cartList.length.toString());
            return Stack(
              children: <Widget>[
                  Provide<CartProvide>(
                    builder: (contex,child,childCategory){
                      cartList=Provide.value<CartProvide>(context).cartList;
                      return  ListView.builder(
                        itemCount: cartList.length,
                        itemBuilder: (context,index){
                          return CartItem(cartList[index]);
                        },
                      );
                    },
                  ),
                
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: CartBottom(),
                  )
              ],
            );

          }else{
            return Text('正在加載');
          }
        },
      ),
    );
  }

  Future<String> _getCartInfo(BuildContext context) async{
    await Provide.value<CartProvide>(context).getCartInfo();
    //print('=========================獲取購物車內數據');
    return 'end';
  }

}
View Code

cart_item.dart:主要增長刪除的事件

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../model/cartInfo.dart';
import './cart_count.dart';
import 'package:provide/provide.dart';
import '../../provide/cart.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(context,item)
        ],
      ),
    );
  }
  //複選框
  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(context,item) {
    return Container(
      width: ScreenUtil().setWidth(150),//只要合起來不超過750 就不會溢出
      alignment: Alignment.centerRight,//居中靠右
      child: Column(
        children: <Widget>[
          Text('¥${item.price}'),
          Container(//用來放icon刪除按鈕
            child: InkWell(
              onTap: (){
                Provide.value<CartProvide>(context).deleteOneGoods(item.goodsId);
              },
              child: Icon(
                Icons.delete_forever,
                color: Colors.black26,//淺灰色
                size: 30,
              ),
            ),
          )
        ],
      ),
    );
  }

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