Firebase Map类型在 Flutter 中返回空值

7xzttuei  于 2023-02-13  发布在  Flutter
关注(0)|答案(1)|浏览(168)

在Firebase中,我有一个名为stockBySize的字段,作为Map

stockBySize
   M: "5"
   L: "2"

在flutter应用程序中,这是我的模型:

class Product {
  String? id;
  String? category;
  String? name;
  String? description;
  String? color;
  String? price;
  List<String>? images;
  Map<String, String>? stockBySize;

  factory Product.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data();
    return Product(
      id: data?['id'],
      category: data?['category'],
      name: data?['name'],
      description: data?['description'],
      color: data?['color'],
      price: data?['price'],
      images: data?['images'] is Iterable ? List.from(data?['images']) : null,
      stockBySize: data?['stockBySize'] is Iterable
          ? Map<String, String>.from(data?['stockBySize'])
          : null,

    );
  }

下面是我读取Firebase数据的代码:

Future<List<Product>> findProducts() async {
    final query = db.collection("products").withConverter(
          fromFirestore: Product.fromFirestore,
          toFirestore: (Product product, _) => product.toFirestore(),
        );
    try {
      final docSnap = await query.get();
      List<Product> products = [];
      docSnap.docs.forEach((element) {
        products.add(
          Product(
            id: element.id,
            category: element.data().category,
            name: element.data().name,
            description: element.data().description,
            color: element.data().color,
            price: element.data().price,
            images: element.data().images,
            stockBySize: element.data().stockBySize,
          ),
        );
      });
      log(products.toString());
      return products;
    } on FirebaseException {
      rethrow;
    }
  }

问题是:字段stockBySize始终为空。
出了什么问题????字段写入正确,firebase中有数据

o8x7eapl

o8x7eapl1#

请尝试以下代码:

class Product {
  Product({
    required this.id,
    required this.category,
    required this.name,
    required this.description,
    required this.color,
    required this.price,
    required this.images,
    required this.stockBySize,
  });

  String? id;
  String? category;
  String? name;
  String? description;
  String? color;
  String? price;
  List<String>? images;
  Map<String, dynamic>? stockBySize;

  factory Product.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data();
    return Product(
      id: data?['id'],
      category: data?['category'],
      name: data?['name'],
      description: data?['description'],
      color: data?['color'],
      price: data?['price'],
      images: data?['images'] is Iterable ? List.from(data?['images']) : null,
      stockBySize: data?['stockBySize'] is Map<String, dynamic> ? Map<String, dynamic>.from(data?['stockBySize']) : null,
    );
  }
}

相关问题