07-08 Flutter仿京东商城项目 商品分类页面布局:Flutter仿京东商城项目 商品分类页面数据渲染

Flutter实战(交流群:452892873)

本项目是一个实战项目,根据目录建文件,并复制从第一节到最新更新的文章,可以构成完整的一个请求后台数据的项目:

CateModel.dart

class CateModel {
  List<CateItemModel> result;

  CateModel({this.result});

  CateModel.fromJson(Map<String, dynamic> json) {
    if (json['result'] != null) {
      result = new List<CateItemModel>();
      json['result'].forEach((v) {
        result.add(new CateItemModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.result != null) {
      data['result'] = this.result.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CateItemModel {
  String sId;
  String title;
  Object status;
  String pic;
  String pid;
  String sort;

  CateItemModel({this.sId, this.title, this.status, this.pic, this.pid, this.sort});

  CateItemModel.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    title = json['title'];
    status = json['status'];
    pic = json['pic'];
    pid = json['pid'];
    sort = json['sort'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['title'] = this.title;
    data['status'] = this.status;
    data['pic'] = this.pic;
    data['pid'] = this.pid;
    data['sort'] = this.sort;
    return data;
  }
}

  Category.dart

import 'package:flutter/material.dart';
import '../../services/ScreenAdaper.dart';
import '../../config/Config.dart';
import 'package:dio/dio.dart';
import '../../model/CateModel.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];
  @override
  void initState() {
    super.initState();
    _getLeftCateData();
  }

  //左侧数据:
  _getLeftCateData() async {
    var api = '${Config.domain}api/pcate';
    var result = await Dio().get(api);
    var leftCateList = CateModel.fromJson(result.data);
    setState(() {
      this._leftCateList = leftCateList.result;
    });
    _getRightCateData(leftCateList.result[0].sId);
  }

  //右侧数据:
  _getRightCateData(pid) async {
    var api = '${Config.domain}api/pcate?pid=${pid}';
    var result = await Dio().get(api);
    var rightCateList = CateModel.fromJson(result.data);
    print(6666);
    setState(() {
      this._rightCateList = rightCateList.result;
    });
  }

  //左侧组件
  Widget _leftCateWidget(leftWidth) {
    if (this._leftCateList.length > 0) {
      return Container(
         leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: this._leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      // setState(() {
                      _selectIndex = index;
                       this._getRightCateData(this._leftCateList[index].sId);
                    });
                    print(_selectIndex);
                  },
                  child: Container(
                     double.infinity,
                    height: ScreenAdaper.height(56),
                    padding: EdgeInsets.only(top: ScreenAdaper.height(24)),
                    child: Text("${this._leftCateList[index].title}",
                        textAlign: TextAlign.center),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
         leftWidth,
        height: double.infinity,
      );
    }
  }

  //右侧组件:
  Widget _rightCateWidget(rightItemWidth, rightItemHeigth) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          // color: Colors.blue,
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: rightItemWidth / rightItemHeigth,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10),
            itemCount: this._rightCateList.length,
            itemBuilder: (context, index) {
              //处理图片:
              String pic=this._rightCateList[index].pic;
              pic=Config.domain+pic.replaceAll('\','/');
              return Container(
                // padding: EdgeInsets.all(ScreenAdaper.width(20)),
                child: Column(
                  children: <Widget>[
                    AspectRatio(
                      aspectRatio: 1 / 1,
                      child: Image.network(
                          "${pic}",
                          fit: BoxFit.cover),
                    ),
                    Container(
                      height: ScreenAdaper.height(32),
                      child: Text("${this._rightCateList[index].title}"),
                    )
                  ],
                ),
              );
            },
          ),
        ),
      );
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text('加载中...'),
          ));
    }
  }

  Widget build(BuildContext context) {
    ScreenAdaper.init(context);

    //计算右侧GridView宽高比:
    var leftWidth = ScreenAdaper.getScreenWidth() / 4;
    //右侧宽高=总宽度-左侧宽度-Gridview外层元素左右的Padding值-GridView中间的间距
    var rightItemWidth =
        (ScreenAdaper.getScreenWidth() - leftWidth - 20 - 20) / 3;
    rightItemWidth = ScreenAdaper.width(rightItemWidth);
    var rightItemHeigth = rightItemWidth + ScreenAdaper.height(32);

    return Row(
      children: <Widget>[
        _leftCateWidget(leftWidth),
        _rightCateWidget(rightItemWidth, rightItemHeigth)
      ],
    );
  }
}

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