簡體   English   中英

如何獲取文檔 ID Firestore

[英]how to get document id Firestore

我是 Firestore 的新手。 我一直無法從 Firestore 獲取文檔 ID。 在這里,我使用名稱和年齡參數創建用戶。 當我單擊提交時,它會提交到 Cloud Firestore。 到目前為止一切正常。


class _MyHomePageState extends State<MyHomePage> {
  late final TextEditingController name = TextEditingController();
  late final TextEditingController age = TextEditingController();
  final DBHelper _helper = DBHelper();
  late final User _user=User();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
             TextField(
              controller: name,
              decoration: const InputDecoration(hintText: "Name"),
            ),
             TextField(
              controller: age,
              decoration: const InputDecoration(hintText: "Age"),
            ),
            ElevatedButton(onPressed:(){
              _user.setAge(age.text);
              _user.setName(name.text);
              print("Name: ${_user.name}");
                _helper.addUser(_user);
                Navigator.push(context, MaterialPageRoute(builder: (builder)=>MainPage( ,))); //here i need to push the document id
            }, child: const Text("Submit"))
          ],
        ),
      ),
    );
  }

這是我的自定義用戶 model

class User{
  late final String userId; 
  final  String name;
  final  String age;
  User({required this.name, required this.age});


}

這是我為 Firestore 方法提供的服務 class

class DBHelper{
 // final User user = User();
  final CollectionReference _reference= FirebaseFirestore.instance.collection("users"); // database path

  //Adding user to Firestore
  Future<void> addUser(User user){
  return _reference.add({
    'name':user.name,
    'age':user.age,
  }).then((value) => print("User added"))

      .catchError((onError)=> print("Failed to add the user: $onError"));
}
} 

這就是我想要的:當我單擊上一頁中的提交按鈕時。 它將導航到以下頁面。 在此頁面中,我想顯示“姓名”和“年齡”信息。 唯一缺少的是documentId


    return FutureBuilder<DocumentSnapshot>(
        future: _ref.doc(documentId).get(), //which document doesn't know
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.hasError) {
            return const Center(
                child: Text(
              "Bir hata oluştu.",
              textScaleFactor: 3,
            ));
          } else if (snapshot.hasData && !snapshot.data!.exists) {
            return const Center(
                child: Text(
              "Döküman yok",
              textScaleFactor: 3,
            ));
          }
          if (snapshot.connectionState == ConnectionState.done) {
            Map<String, dynamic> data =
                snapshot.data!.data() as Map<String, dynamic>;
            return Scaffold(
              body: Center(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "Name: ${data['name']}",
                    textScaleFactor: 3,
                  ),
                  Text(
                    "Age:${data['age']}",
                    textScaleFactor: 3,
                  ),
                ],
              )),
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        });

您可以在用於提交信息的方法上獲取 id

而不是 return void ,而是返回一個 String(the id) 然后 go 到下一個屏幕,如下所示:

  Future<String> addUser(User user)async {
  return await _reference.add({
    'name':user.name,
    'age':user.age,
  }).then((value) => var documentId=value.id)

按鈕 function 應該是:

 ElevatedButton(onPressed:(){
              _user.setAge(age.text);
              _user.setName(name.text);
              print("Name: ${_user.name}");
                var id=await _helper.addUser(_user);
               Navigator.push(Get.context!, MaterialPageRoute(builder:(builder)=>MainPage(documentI: id))); 
            }, child: const Text("Submit"))
          ],
        ),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM