Flutter實戰視頻-移動電商-31.列表頁_列表切換交互制做

31.列表頁_列表切換交互制做

博客地址:https://jspang.com/post/FlutterShop.html#toc-c42html

 點擊左側的大類右邊的小類也跟着變化json

新建provide

要改變哪裏就建哪裏的provide,咱們如今要改變的是右邊的商品列表的數組。數組

category_goods_list.dartapp

 

 

這樣咱們的provide類就作好了less

作好的provide類放到main.dart中註冊

這一步叫作 把狀態放入頂層jsp

category_page.dart修改

_getGoodsList方法總體移動到左側的大類async

 

咱們把他移動到了這裏ide

方法移動過來之後,咱們要接受一個參數類別id,這個類別是可選的,可選的參數用{}括起來佈局

再判斷傳入的參數是否有值,若是有值就用這個值,若是沒有值就用默認的白酒的分類是4post

引入provide更改右側的列表數據

 

import '../provide/category_goods_list.dart';

 

這個時候咱們會發現咱們傳入list的值有錯。

實際上咱們的CategoryGoodsListModel類裏面的data纔是咱們要傳入的列表值 List<CategoryListData>

因此這裏咱們要用.data的形式

修改咱們的右側列表類

list沒有用,已經換成了provide的狀態管理。這裏刪除掉就能夠了。

咱們要在container的外層包括一層provide才能夠去使用狀態管理。

 

外層包括Provide,builder裏面三個參數,1:上下文對象 2:child 3:就是咱們的數據了

 

 

全部list的地方都要換成newList

 

使用咱們改編自狀態的方法:_getGoodsList

在咱們左側大類的onTap事件裏面去調用這個小類數據的方法

 

展現效果

點擊後右側出現了數據

剛進入頁面的時候調用一次加載右側列表的數據

默認記載白酒的子類數據

 

最終代碼

lib/provide/category_goods_list.dart

import 'package:flutter/material.dart';
import '../model/categoryGoodsList.dart';

class CategoryGoodsListProvide with ChangeNotifier{
 List<CategoryListData> goodsList=[];
 //點擊大類時候更換商品列表
 getGoodsList(List<CategoryListData> list){
   goodsList=list;
   notifyListeners();
 }
}

 

 

main.dart

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';


void main(){
 var counter=Counter();
 var childCategory=ChildCategory();
 var categoryGoodsListProvide=CategoryGoodsListProvide();
 var providers=Providers();
 //註冊 依賴
 providers
 ..provide(Provider<Counter>.value(counter))
 ..provide(Provider<CategoryGoodsListProvide>.value(categoryGoodsListProvide))
 ..provide(Provider<ChildCategory>.value(childCategory)); 
  runApp(ProviderNode(child: MyApp(),providers: providers,));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child:MaterialApp(
        title:'百姓生活+',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primaryColor: Colors.pink
        ),
        home: IndexPage(),
      )
    );
  }
}

 

 

import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'dart:convert';
import '../model/category.dart';
import '../model/categoryGoodsList.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';
import '../provide/child_category.dart';
import '../provide/category_goods_list.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    //_getCategory();
    return Scaffold(
      appBar: AppBar(title: Text('商品分類'),),
      body: Container(
        child: Row(
          children: <Widget>[
            LeftCategoryNav(),
            Column(
              children: <Widget>[
                RightCategoryNav(),
                CategoryGoodsList()
              ],
            )
          ],
        ),
      ),
    );
  }

 
}

//左側大類導航
class LeftCategoryNav extends StatefulWidget {
  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list=[];
  var listIndex=0;
  @override
  void initState() { 
    super.initState();
    _getCategory();//請求接口的數據
    _getGoodsList();//參數是可選的默認是4 因此這裏能夠不用傳值
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
        border: Border(
          right: BorderSide(width:1.0,color: Colors.black12),//有邊框
        )
      ),
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (contex,index){
          return _leftInkWell(index);
        },
      ),
    );
  }

  Widget _leftInkWell(int index){
    bool isClick=false;
    isClick=(index==listIndex)?true:false;
    return InkWell(
      onTap: (){
        setState(() {
         listIndex=index; 
        });
        var childList=list[index].bxMallSubDto;//當前大類的子類的列表
        var categoryId=list[index].mallCategoryId;//大類的id
        Provide.value<ChildCategory>(context).getChildCategory(childList);
        _getGoodsList(categoryId:categoryId);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: EdgeInsets.only(left:10.0,top:10.0),
        decoration: BoxDecoration(
          color: isClick?Color.fromRGBO(236, 236, 236, 1.0): Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.0,color: Colors.black12)
          )
        ),
        child: Text(
          list[index].mallCategoryName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),//設置字體大小,爲了兼容使用setSp
        ),
      ),
    );
  }
   void _getCategory() async{
    await request('getCategory').then((val){
      var data=json.decode(val.toString());
      //print(data);
      CategoryModel category= CategoryModel.fromJson(data);
      setState(() {
       list=category.data; 
      });
      Provide.value<ChildCategory>(context).getChildCategory(list[0].bxMallSubDto);
    });
  }

  void _getGoodsList({String categoryId}) async {
    var data={
      'categoryId':categoryId==null?'4':categoryId,//白酒的默認類別
      'CategorySubId':"",
      'page':1
    };
    await request('getMallGoods',formData: data).then((val){
      var data=json.decode(val.toString());
      CategoryGoodsListModel goodsList=CategoryGoodsListModel.fromJson(data);//這樣就從json'轉換成了model類
      //print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:${goodsList.data[0].goodsName}');
      // setState(() {
      //  list=goodsList.data; 
      // });
      Provide.value<CategoryGoodsListProvide>(context).getGoodsList(goodsList.data);
    });
  }
}

class RightCategoryNav extends StatefulWidget {
  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  //List list = ['名酒','寶丰','北京二鍋頭','捨得','五糧液','茅臺','散白'];
  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
      builder: (context,child,childCategory){
        return  Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(570),//總的寬度是750 -180
          decoration: BoxDecoration(
            color: Colors.white,//白色背景
            border: Border(
              bottom: BorderSide(width: 1.0,color: Colors.black12)//邊界線
            )
          ),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childCategory.childCategoryList.length,
            itemBuilder: (context,index){
              return _rightInkWell(childCategory.childCategoryList[index]);
            },
          ),
        );
      }
    );
  }

  Widget _rightInkWell(BxMallSubDto item){
    return InkWell(
      onTap: (){},//事件留空
      child: Container(//什麼都加一個container,這樣好佈局
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),//上下是10 左右是5.0
        child: Text(
          item.mallSubName,
          style:TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }
}

//商品列表 ,能夠上拉加載
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {

  @override
  void initState() {
    //_getGoodsList();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsListProvide>(
      builder: (context,child,data){
        return  Container(
          width: ScreenUtil().setWidth(570),
          height: ScreenUtil().setHeight(974),
          child: ListView.builder(
            itemCount: data.goodsList.length,
            itemBuilder: (contex,index){
              return _listWidget(data.goodsList,index);
            },
          ),
        );
      },
    );
    
   
  }
  

  Widget _goodsImage(List newList,index){
    return Container(
      width: ScreenUtil().setWidth(200),//設置200的寬度 限制
      child: Image.network(newList[index].image),
    );
  }
  Widget _goodsName(List newList,index){
    return Container(
      padding: EdgeInsets.all(5.0),//上下左右都是5.0的內邊距
      width: ScreenUtil().setWidth(370),//370是一個大約的值
      child: Text(
        newList[index].goodsName,
        maxLines: 2,//最多顯示2行內容
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),//字體大小
      ),
    );
  }

  Widget _goodsPrice(List newList,index){
    return Container(
      margin: EdgeInsets.only(top:20.0),//和上面的外間距
      width: ScreenUtil().setWidth(370),//370是一個大約的值
      child: Row(
        children: <Widget>[
          Text(
            '價格¥${newList[index].presentPrice}',
            style: TextStyle(color: Colors.pink,fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '價格¥${newList[index].oriPrice}',
            style: TextStyle(
              color: Colors.black26,
              decoration: TextDecoration.lineThrough
            ),//刪除線的樣式
          )
        ],
      ),
    );
  }

  Widget _listWidget(List newList,int index){
    return InkWell(
      onTap: (){},
      child: Container(
        padding: EdgeInsets.only(top:5.0,bottom:5.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.0,color: Colors.black12)
          )
        ),
        child: Row(
          children: <Widget>[
            _goodsImage(newList,index),
            Column(
              children: <Widget>[
                _goodsName(newList,index),
                _goodsPrice(newList,index)
              ],
            )
          ],
        ),
      ),
    );
  }
}
category_page.dart
相關文章
相關標籤/搜索