在我的带有 firebase fire-store 数据库的实时扑动应用程序中,我有一个数据模型说
Product.dart
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
class Product{
final String name;
final double price;
Product({required this.name, required this.price});
Map<String, dynamic> toMap() {
return {
"name": name,
"price": price
};
}
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
name: json["name"],
price: double.parse(json["price"].toString())
);
}
factory Product.fromRawJson(String str) => Product.fromMap(json.decode(str));
String toRawJson() => json.encode(toMap());
}
现在,为此数据模型引入一个新的必填字段,即“大小”。我们应该如何重写数据模型类,特别是 fromMap() 函数,因为数据库不会有这个字段,至少在所有文档中都不会,即使在我的应用程序中的适当位置使用下面的代码更新了一些文档。
FirebaseFirestore.instance.collection('product').doc(id)
.update({'size': prodSize})
.then((value) => print("Product Spec Updated"))
.catchError((error) => print("Failed to update product: $error"));
需要类似下面的伪代码:
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
name: json["name"],
price: double.parse(json["price"].toString())
size: json.containsKey('size') ? json["size"] : 'not known'
);
}
size: json.containsKey('size') ? json["size"] : 'not known'
上面的代码用于检查从 firestore 读取的文档是否包含该字段。