[英]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個選擇
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);
}
}
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.