• 首页
  • 感性生活,理性思考。


flutter2.0电商项目实践学习

项目地址

视频课程

点击这里

项目展示

68747470733a2f2f6766.gif

目录结构

fonts/
images/
lib/

 dao/ models/ page/ routes/ utils/ view/

dao:用来存放对数据库操作的方法,没有逻辑,只有增删改查。
model:就是pojo用来存放实体类对象,一个有Get、Set的方法,把现实中的东西看成一个实体,做成一个类,单独放起来,一个实体类对应数据库里的一个表。

普遍的软件框架示意图

1275932-20190617143844926-1051905530.png

DAO 持久化操作代码层

  • config.dart 主要是定义api接口地址
  • findgoods_dao.dart 主要是定义CURD操作,如对Goods进行增删改查。
const ServerHost = 'http://localhost:8081';
const FindingUrl = '$ServerHost/api/goods';
const HomeUrl = '$ServerHost/api/store';
class FindingsDao{
  static Future<GoodsEntity> fetch() async{
    try {
      Response response = await Dio().get(FindingUrl);
      if(response.statusCode == 200){
        return EntityFactory.generateOBJ<GoodsEntity>(response.data);
      }else{
        throw Exception("StatusCode: ${response.statusCode}");
      }
    } catch (e) {
      print(e);
      return null;
    }
  }
}

Model 持久层、数据模型层

  • 实体工厂:entity_factory.dart 注册有哪些实体
  • 具体实体:goods_entity.dart 实现具体实体的GET SET 以及 JSON 的序列化等数据操作
class EntityFactory {
  static T generateOBJ<T>(json) {
    if (1 == 0) {
      return null;
    } else if (T.toString() == "StoreEntity") {
      return StoreEntity.fromJson(json) as T;
    } else if (T.toString() == "GoodsEntity"){
      return GoodsEntity.fromJson(json) as T;
    }else {
      return null;
    }
  }
}
class GoodsEntity {
    List<GoodsModel> goods;

    GoodsEntity({this.goods});

    GoodsEntity.fromJson(Map<String, dynamic> json) {
        if (json['goods'] != null) {
            goods = new List<GoodsModel>();(json['goods'] as List).forEach((v) { goods.add(new GoodsModel.fromJson(v)); });
        }
    }

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

class GoodsModel {
    String price;
    String name;
    String photo;
    int id;

    GoodsModel({this.price, this.name, this.photo, this.id});

    GoodsModel.fromJson(Map<String, dynamic> json) {
        price = json['price'];
        name = json['name'];
        photo = json['photo'];
        id = json['id'];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['price'] = this.price;
        data['name'] = this.name;
        data['photo'] = this.photo;
        data['id'] = this.id;
        return data;
    }
}

本文链接:

https://chao.asia/tech/143.html

1 + 6 =
快来做第一个评论的人吧~
lamu.png