51.购物车_Provide中添加商品

 

新加provide的cart.dart页面

引入三个文件。开始写provide类。provide需要用with 进行混入

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_ico

从prefs里面获取到数据,判断有没有数据,如果有数据就返转正List<Map>

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_ico_02

判断是否有重复的记录,如果有重复记录就数量+1,如果数据不存在就加入到tempList数组中,最后把tempList数据转成字符串,进行持久化

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_数据_03

清空购物车的方法

清空的方法比较简单,注意这里是异步的

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_04

给两个方法最后都加上通知

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_数据_05

provide的全局依赖

在main.dart中

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_持久化_06

details_bottom.dart中

引入,

因为要获取商品的信息,所以要引入:details_info.dart

 

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_ico_07

import 'package:provide/provide.dart';
import '../../provide/cart.dart';
import '../../provide/details_info.dart';

 

从provide中获取到当前商品的详情,就可以获取到商品的编号 名称 价格和图片的地址了。

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_08

加入购物车和清空购物车的点击事件内,调用provide内的save和remove的方法

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_09

 

纠正错误:

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_ico_10

效果展示:

添加重复的数量在增加

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_数据_11

立即购买是清空的效果

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_12

  最终代码

provide/cart.dart

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

class CartProvide with ChangeNotifier{
  String cartString="[]";//声明一个变量 做持久化的存储

  //声明一个异步的方法,购物车操作放在前台不在请求后台的数据
  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;
        isHave=true;
      }
      ival++;
    });
    //没有不存在这个商品,就把商品的json数据加入的tempList中
    if(!isHave){
      tempList.add({
        'goodsId':goodsId,//传入进来的值
        'goodsNmae':goodsName,
        'count':count,
        'price':price,
        'images':images
      });
    }
    cartString=json.encode(tempList).toString();//json数据转字符串
    print(cartString);
    prefs.setString('cartInfo', cartString);
    notifyListeners();
  }
  remove() async{
    SharedPreferences prefs=await SharedPreferences.getInstance();
    prefs.remove('cartInfo');
    print('清空完成----------------------');
    notifyListeners();
  }
}

 

 

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_13Flutter实战视频-移动电商-51.购物车_Provide中添加商品_数据_14
import 'package:flutter/material.dart';
import './pages/index_page.dart';
import 'package:provide/provide.dart';
import './provide/counter.dart';
import './provide/child_category.dart';
import './provide/category_goods_list.dart';
import './provide/details_info.dart';
import './provide/cart.dart';
import 'package:fluro/fluro.dart';
import './routers/routers.dart';
import './routers/application.dart';


void main(){
 var counter=Counter();
 var childCategory=ChildCategory();
 var categoryGoodsListProvide=CategoryGoodsListProvide();
 var detailsInfoProvide=DetailsInfoProvide();
 var cartProvide=CartProvide();
 var providers=Providers();
 //final router=Router();//Router就是我们的Fluro
 //注册 依赖
 providers
 ..provide(Provider<Counter>.value(counter))
 ..provide(Provider<CategoryGoodsListProvide>.value(categoryGoodsListProvide))
 ..provide(Provider<DetailsInfoProvide>.value(detailsInfoProvide))
 ..provide(Provider<CartProvide>.value(cartProvide))
 ..provide(Provider<ChildCategory>.value(childCategory)); 
  runApp(ProviderNode(child: MyApp(),providers: providers,));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    final router=Router();//Router就是我们的Fluro
    Routes.configurreRoutes(router);//注册router
    Application.router=router;//静态化

    return Container(
      child:MaterialApp(
        title:'百姓生活+',
        onGenerateRoute: Application.router.generator,
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primaryColor: Colors.pink
        ),
        home: IndexPage(),
      )
    );
  }
}
main.dart

 

 

Flutter实战视频-移动电商-51.购物车_Provide中添加商品_flutter_13Flutter实战视频-移动电商-51.购物车_Provide中添加商品_数据_14
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';
import '../../provide/cart.dart';
import '../../provide/details_info.dart';

class DetailsBottom extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var goodsInfo=Provide.value<DetailsInfoProvide>(context).goodsInfo.data.goodInfo;//当前商品的详情
    var goodsId=goodsInfo.goodsId;
    var goodsName=goodsInfo.goodsName;
    var count=1;//默认为1
    var price=goodsInfo.presentPrice;
    var images=goodsInfo.image1;


    return Container(
      width: ScreenUtil().setWidth(750),
      color: Colors.white,
      height: ScreenUtil().setHeight(80),
      child: Row(
        children: <Widget>[
          InkWell(
            onTap: (){},
            child: Container(
              width: ScreenUtil().setWidth(110),
              alignment: Alignment.center,
              child: Icon(
                Icons.shopping_cart,
                size:35,//图标没有自适应 要是设置size的大小
                color: Colors.red,
              ),
            ),            
          ),
          InkWell(
            onTap: () async{
              await Provide.value<CartProvide>(context).save(goodsId, goodsName, count, price, images);
            },
            child: Container(
              alignment: Alignment.center,
              width: ScreenUtil().setWidth(320),//750 - 110 再除以2 评分
              height: ScreenUtil().setHeight(80),
              color: Colors.green,
              child: Text(
                '加入购物车',
                style:TextStyle(color:Colors.white,fontSize: ScreenUtil().setSp(28)),
              ),
            ),
          ),
          InkWell(
            onTap: () async{
              await Provide.value<CartProvide>(context).remove();
            },
            child: Container(
              alignment: Alignment.center,
              width: ScreenUtil().setWidth(320),//750 - 110 再除以2 评分
              height: ScreenUtil().setHeight(80),
              color: Colors.red,
              child: Text(
                '立即购买',
                style:TextStyle(color:Colors.white,fontSize: ScreenUtil().setSp(28)),
              ),
            ),
          )
        ],
      ),
    );
  }
}
details_bottom.dart