Flutter實戰視頻-移動電商-34.列表頁_小BUG的修復

34.列表頁_小BUG的修復

當高粱酒的子類沒有數據返回的時候就會報錯。json

解決接口空數據報錯的問題

 

沒有數據的時候,給用戶一個友好的提示,

咱們沒有數據的時候還要告訴用戶,提示一下他沒有數據,在咱們的右側列表的build方法內去判斷app

 

友好提示展現效果:

 

子類的id狀態化

狀態管理裏面,定義小類的變量,並根據傳入的id根性賦值。這樣咱們在點擊小類的時候,須要也傳入小類的idasync

這樣咱們在小類點擊事件裏面,傳入小類的id就能夠了ide

 

測試程序

點擊小類進行測試佈局

 

 

 

最終代碼:

provide/child_category.dart測試

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

class ChildCategory with ChangeNotifier{
 List<BxMallSubDto> childCategoryList=[];
 int childIndex=0;//子類高亮索引
 String categoryId='4';//大類ID 白酒的id 默認爲4
 String subId='';//小類ID
  //大類切換邏輯
  getChildCategory(List<BxMallSubDto> list,String id){
    childIndex=0;//每次點擊大類,小類的索引都要清空掉
    categoryId=id;
    BxMallSubDto all=BxMallSubDto();
    all.mallCategoryId="00";
    all.mallCategoryId="00";
    all.comments="null";
    all.mallSubName='所有';
    childCategoryList=[all];
    //childCategoryList=list;
    childCategoryList.addAll(list);
    notifyListeners();//監聽
  }
  //改變子類索引,indexs是從哪裏來的呢?從咱們具體的類中進行傳遞
  changeChildIndex(index,String id){
    childIndex=index;//把傳遞過來的index賦值給咱們的childIndex
    subId=id;
    notifyListeners();//通知
  }
}

 

 

pages/category_page.dart字體

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,categoryId);
        _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,list[0].mallCategoryId);
    });
  }

  void _getGoodsList({String categoryId}) {
    var data={
      'categoryId':categoryId==null?'4':categoryId,//白酒的默認類別
      'categorySubId':"",
      'page':1
    };
    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(index,childCategory.childCategoryList[index]);
            },
          ),
        );
      }
    );
  }

  Widget _rightInkWell(int index,BxMallSubDto item){
    bool isClick=false;
    isClick=(index==Provide.value<ChildCategory>(context).childIndex)?true:false;

    return InkWell(
      onTap: (){
        Provide.value<ChildCategory>(context).changeChildIndex(index,item.mallSubId);
        _getGoodsList(item.mallSubId);
      },//事件留空
      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),
            color: isClick?Colors.pink:Colors.black
          ),
        ),
      ),
    );
  }
  void _getGoodsList(String categorySubId) {
    var data={
      'categoryId':Provide.value<ChildCategory>(context).categoryId,//大類ID
      'categorySubId':categorySubId,
      'page':1
    };
    request('getMallGoods',formData: data).then((val){
      var data=json.decode(val.toString());
      CategoryGoodsListModel goodsList=CategoryGoodsListModel.fromJson(data);//這樣就從json'轉換成了model類
      if(goodsList.data==null){
        Provide.value<CategoryGoodsListProvide>(context).getGoodsList([]);
      }else{
        Provide.value<CategoryGoodsListProvide>(context).getGoodsList(goodsList.data);
      }
      
    });
  }
}

//商品列表 ,能夠上拉加載
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){
        if(data.goodsList.length>0){
            return  Expanded(
              child: Container(
                width: ScreenUtil().setWidth(570),
                //height: ScreenUtil().setHeight(974),
                child: ListView.builder(
                  itemCount: data.goodsList.length,
                  itemBuilder: (contex,index){
                    return _listWidget(data.goodsList,index);
                  },
                ),
              ),
            );
        }else{
          return Text('暫時沒有數據');
        }
       
      },
    );
    
   
  }
  

  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
相關文章
相關標籤/搜索