在 flutter Cloud Firestore 中设置自定义文档 ID

mor*_*cai 1 dart flutter google-cloud-firestore

我想为我的云 Firestore 中的新条目设置自定义文档 ID,但我似乎不知道该怎么做,这是我的代码,它仍然生成一个随机 ID

        FirebaseFirestore.instance.collection("payment_links").add(
  {'id':  user_id.toString(),
  'link':
paymentlink.toString(), 'link_id': linker.toString(),
'amount':
c1.text.toString(),
'title':
c2.text.toString(),
'trxnid':
secureRandom.nextString(
      length: 15, charset: '0123456789').toString(),
      'payments' : 0



  }).then((value){
 
                                      
                                         
    print("================================sucess=============================================================");
    print(value.documentID);
  });
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 5

如果您不想要自动随机 ID,则不要使用add(). 您应该为要创建的文档构建一个DocumentReference ,并使用set()代替。

DocumentReference ref = FirebaseFirestore.instance
    .collection("payment_links")
    .doc("your-document-id");
ref.set({ ... });
Run Code Online (Sandbox Code Playgroud)

我建议仔细阅读文档,其中写道:

如果您想指定自己的 ID,请改为调用 DocumentReference 上的 set 方法