以 cloud_firestore 作为数据库,在现有 Flutter 应用程序的数据模型中添加新字段

问题描述 投票:0回答:1

在我的带有 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'
    );
  }
flutter dart
1个回答
0
投票
size: json.containsKey('size') ? json["size"] : 'not known'

上面的代码用于检查从 firestore 读取的文档是否包含该字段。

© www.soinside.com 2019 - 2024. All rights reserved.