简体   繁体   English

如何使用 flutter 向 firebase 中的现有文档添加字段?

[英]How to add Field to existing document in firebase with flutter?

I want to add a new field in an existing Document my firestore collection我想在我的 firestore 集合中的现有文档中添加一个新字段

so I want to add Field like this:所以我想像这样添加字段:

"name" : "john",
"uid" : "ddddddddddddddddd",
"email" : "example@example.com",
"imageUrl" : "url"

"cart" : {          >>>>>> this field I want to add 
  "Productone":{
  "product name" : "productname", 
  "price" : "50"
    }
  "Productow":{
  "product name" : "productname",  
  "price" : "50"
    }
}

How can I do this so when the user adds a product to the cart, I can store it in firestore?当用户将产品添加到购物车时,我该怎么做才能将其存储在 Firestore 中?

await FirebaseFirestore.instance.collection('Users').doc(userId)
.update({"cart":
  "Productone":
  {"product name" : "productname", 
  "price" : "50"}
  "Productow":
  {"product name" : "productname",  
  "price" : "50"}
  });

It's explained extremely well here .这里解释得非常好。 I believe that Firebase, specifically Flutter documentation is probably one of the best written documentations online.我相信 Firebase,特别是 Flutter 文档可能是最好的在线书面文档之一。 Props to the team.给球队的道具。

Firestore can accept map so 'cart' should be added as map: Firestore 可以接受 map 因此“购物车”应添加为 map:

Map<String, Map<String, dynamic>> cart = {
'Productone'{
"product name" : "productname", 
  "price" : "50"
}
}

 FirebaseFirestore.instance.collection('orders').add({
         orders: cart,
        );

or或者

FirebaseFirestore.instance.collection('Users').doc(userId)
.update{ 
        orders: cart,
       );

Main Idea is to convert cart to Map specifically Map<String, Map<String, dynamic>>主要思想是将购物车转换为 Map 特别是 Map<String, Map<String, dynamic>>

You can do it using FieldValue .您可以使用FieldValue来做到这一点。

FirebaseFirestore.instance
    .collection('Users')
    .doc('here is your document uid')
    .update({
  'cart': FieldValue.arrayUnion([
    {
      'Productone': {
        'product name': 'productname',
        'price': '50',
      },
    },
    {
      'Productow': {
        'product name': 'productname',
        'price': '50',
      },
    },
  ]),
});

It will work like List.add它将像List.add一样工作


One-time data reading:一次性数据读取:

FutureBuilder<firestore.DocumentSnapshot>(
  future: firestore.FirebaseFirestore.instance
      .collection('Users')
      .doc('your document uid')
      .get(),
  builder: (context, asyncSnapshot) {
    if (asyncSnapshot.hasData) {
      if (asyncSnapshot.data!.exists) {
        return Text(asyncSnapshot.data!.data()!['cart']);
      } else {
        return const Text('Document doesn\'t exist');
      }
    } else {
      return const CircularProgressIndicator();
    }
  });

Realtime changes reading:实时变化读数:

StreamBuilder<firestore.DocumentSnapshot>(
  stream: firestore.FirebaseFirestore.instance
      .collection('Users')
      .doc('your document uid')
      .snapshots(),
  builder: (context, asyncSnapshot) {
    if (asyncSnapshot.hasData) {
      if (asyncSnapshot.data!.exists) {
        return Text(asyncSnapshot.data!.data()!['cart']);
      } else {
        return const Text('Document doesn\'t exist');
      }
    } else {
      return const CircularProgressIndicator();
    }
  });

Some links:一些链接:

Official FieldValue class documentation 官方FieldValue class 文档

FlutterFireFieldValue , one-time read , realtime changes FlutterFireFieldValue , 一次性读取, 实时变化

Stack Overfolw answer堆栈溢出答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM