簡體   English   中英

顫振模型設計模式

[英]Flutter Model design pattern

我有一個Product模型

class Product {
  int id;
  String title;
  double mrp;

  Product(this.id, this.title, this.mrp);

  factory Product.fromJson(int id, String title, double mrp) {
    return Product(id, title, mrp);
  }
}

當我從服務器獲取json數據作為響應時,API 調用有不同的 json 結構-

第一個例子

{
  "id": 523,
  "title": "test",
  "mrp": 23.25
}

第二個例子:

{
  "id" : 523,
  "title" : "test",
  "mrp" : 23.25
  "discountedPrice" : 23.00
}

第三個例子:

{
  "id" : 523,
  "title" : "test",
  "mrp" : 23.25
  "availableForSale" : true
}

第四個例子:

{
  "id" : 523,
  "title" : "test",
  "mrp" : 23.25
  "firstCharacterTitle" : "T"
}

如您所見,我在不同的 API 獲取調用中有不同的新字段,例如discountedPrice firstCharacterTitle availableForSale API結構。 在其他情況下可以是許多其他人。

在不同情況下我應該如何處理Product模型,因為我只有 3 個永久字段id title mrp但所有其他字段都取決於場景? 我應該繼續增加模型中的字段還是其他任何內容? 什么是最佳實踐?

對不起,更長的答案。

你有2個選擇

  1. 添加那些額外的參數並使它們可以為空。

class Product {
 int id;
 String title;
 double mrp;
 String? firstCharacterTitle;

 Product(this.id, this.title, this.mrp, {this.firstCharacterTitle});

 factory Product.fromJson(
   int id,
   String title,
   double mrp, {
   String? firstCharacterTitle,
 }) {
   return Product(id, title, mrp, firstCharacterTitle: firstCharacterTitle);
 }
}
  1. 或者使用動態的東西
class Product {
  int id;
  String title;
  double mrp;
  Map<String, dynamic> extraParams;

  Product(this.id, this.title, this.mrp, this.prms);

  factory Product.fromJson(int id, String title, double mrp, Map<String, dynamic> prms) {
    return Product(id, title, mrp, prms);
  }
}

我還建議使用json_serializable 因為您的 fromJson 方法並不是真正的 fromJson,但它采用了已經轉換的 Json 參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM