【问题标题】:Get Document ID of Firestore Document (Flutter)获取 Firestore 文档的文档 ID (Flutter)
【发布时间】:2021-07-20 17:52:47
【问题描述】:

enter image description here 已经尝试了几天从我的 Flutter 应用程序中获取 Firestore 中文档的文档 ID。 我想要的是更新或删除文档,但必须先通过他的 id 来识别它。 当我打开 Firestore 时,我的 ID 包含其他值,例如名称、地址等。

现在我正在尝试了解如何将文档 ID 放入变量中,然后在我的函数中使用它来删除或更新文档。

getDocIndex() {
  var documentID = Firestore.instance
      .collection('Requests')
      .document(widget.data['Document ID'].toString())
      .get();
  print(documentID);
}

我了解函数中的小部件不可用。可能是带有 snapshot.data 的东西......但它也被标记为红色。

这是我的功能,然后应该可以工作:

deleteDocument(){

Firestore.instance.collection('Requests').document(documentID).delete();

}

enter image description here enter image description here

【问题讨论】:

  • 查看此链接.. link to your Answer
  • 检查这个链接...这将帮助你link
  • 您在请求文档时实际上知道 ID。有什么问题?
  • 问题是,我在使用应用程序时需要该 ID。我不想打开 Firestore 来获取该 ID。当我打开来自用户的请求的 Firestores 文档时,我想将其从我的应用程序中删除。要删除它,我可以使用文档的 ID 来完成。所以我需要一个从打开的文档中获取 ID 的变量
  • @MichaelKarp 请分享您的 Firestore 结构以及 Flutter 代码的屏幕截图,以便我们进行测试。还有什么是红色标记的?

标签: flutter google-cloud-firestore document


【解决方案1】:

如果您知道文档中的值,则可以使用 where 查询来查找具有这些参数的所有文档。

Firestore.instance.collection('requests').where('Document ID', isEqualTo: "ID")
    .snapshots().listen(
          (data) => print('grower ${data.documents[0]['name']}')
    );

但是,如果您已经可以在本地访问文档的数据,则可以从文档快照中提取参考路径(如果您已将其存储在本地)。那时只是从您的应用中恢复该数据的问题。

【讨论】:

  • 谢谢!现在我得到了 ID,但只能从列表中位置为 [0] 的第一个文档中获取。所以我需要找出如何使 0 变得灵活。系统识别文件在 Firestore 中的位置。没有 .where('Document ID') 它对我有用
  • 有了这个,我从地图中获取所有文档 ID....但只需要一个我选择的未来 getDocIndex() async { Firestore.instance.collection('Requests').snapshots(). listen((data) => print('ID: ${data.documents.map((DocumentSnapshot document) => document['Document ID'])}')); }
【解决方案2】:

谢谢大家!我知道了!

return ListTile(
                        title: Text(
                          '${snapshot.data[index].data['Name']}',
                          style: GoogleFonts.lexendDeca(),
                        ),
                        subtitle: Text(
                          '${snapshot.data[index].data['Anfrage vom']}',
                          style: GoogleFonts.lexendDeca(),
                        ),
                        onTap: () {
                          navigateToDetail(snapshot.data[index]);
                          keyID = snapshot.data[index].data['Document ID'];
                          print(keyID.toString());

下面我在 keyID 中获取来自文档字段的文档 ID。之后,我可以使用带有 ID 引用的删除功能。

Firestore.instance.collection('Requests').document(keyID).delete();

【讨论】:

    【解决方案3】:
    getDocIndex() {
      var document = Firestore.instance
          .collection('Requests')
          .document(widget.data['Document ID'].toString())
          .get();
      print(document.id);
    }
    

    【讨论】:

    • 谢谢,但是小部件和 id 被标记为红色。我也认为这很困难,因为我在一个 dart 文件中有用户添加他的请求的功能,而在我试图获取该文档的其他 dart 文件中。所以我的变量 docId 在其他 dart 文件中。当我使用来自文档的密钥“文档 ID”时,我想获取该 ID。
    【解决方案4】:
    getDocIndex() async {
      var document = await Firestore.instance
          .collection('Requests')
          .document(widget.data['Document ID'].toString())
          .get();
      print(document.id);
    }
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
    • @michael-karp 如果您可以提供您的 Firestore 结构来帮助查询结构,那总是很棒的。请记住,您从 Future 获取值始终必须将 async 放在 func 主体之前,并在函数之前放置 int ,否则您可能有一个空值或抛出一个期望。
    • @menotenhanga 谢谢!问题是,当我尝试上传 3 张以上的图片时,这里出现错误。所以我不能发布完整的代码。以下是您的答案,我有两个错误。系统不知道这里的小部件是什么,并且 document.id -> 无法识别单词 id。它没有定义。
    • @menotenhanga 我已经从该文件中给出了答案。所以这是该文件的完整代码
    • 目前我使用更新文档的功能,以及删除文档的equal。但问题在于它总是更新/删除地图中的第一个文档,因为 [0] 索引。如果我能设法找出当前的索引,也许我可以这样解决我的问题。
    【解决方案5】:
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import 'package:google_fonts/google_fonts.dart';
    import 'package:kuechenrechner/card_widget.dart';
    import 'package:kuechenrechner/gmaps.dart';
    import 'package:geocoder/geocoder.dart';
    import 'adminslogin.dart';
    
    //final documentsRef = Firestore.instance.collection('Requests');
    
    class Admins extends StatefulWidget {
      @override
      _AdminsState createState() => _AdminsState();
    }
    
    class _AdminsState extends State<Admins> {
      /*geoConvert() async {
    // Geocoding for Address
    // final query = "1600 Amphiteatre Parkway, Mountain View";
        var addresses = await Geocoder.local.findAddressesFromQuery(query);
        var first = addresses.first;
        print("${first.featureName} : ${first.coordinates}");
      }
    */
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (BuildContext context) {
                    return AdminsLogin();
                  }));
                }),
            title: Text(
              'Anfragen',
              style: GoogleFonts.lexendDeca(),
            ),
            centerTitle: true,
            actions: [
              IconButton(
                  icon: Icon(Icons.refresh),
                  onPressed: () {
                    setState(() {});
                  })
            ],
          ),
          body: AdminsList(),
        );
      }
    }
    
    Future getPosts() async {
      var firestore = Firestore.instance;
      QuerySnapshot qn = await firestore
          .collection("Requests")
          .orderBy('Anfrage vom')
          .getDocuments();
    
      return qn.documents;
    }
    
    //Abfrage DocumentID
    getDocIndex() async {
      /* var documentID = Firestore.instance
          .collection('Requests')
          .document(widget.data['Document ID'].toString())
          .get();
      print(documentID);
      */
    
      var document = await Firestore.instance
          .collection('Requests')
          .document(widget.data['Document ID'].toString())
          .get();
      print(document.id);
    }
    
    class AdminsList extends StatefulWidget {
      @override
      _AdminsListState createState() => _AdminsListState();
    }
    
    class _AdminsListState extends State<AdminsList> {
      navigateToDetail(DocumentSnapshot post) {
        Navigator.push(context,
            MaterialPageRoute(builder: (context) => AdminsDetails(post: post)));
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: FutureBuilder(
              future: getPosts(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: Text('Loading...'),
                  );
                } else {
                  return ListView.separated(
                    reverse: true,
                    shrinkWrap: true,
                    itemCount: snapshot.data.length,
                    itemBuilder: (_, index) {
                      return ListTile(
                        title: Text(
                          '${snapshot.data[index].data['Name']}',
                          style: GoogleFonts.lexendDeca(),
                        ),
                        subtitle: Text(
                          '${snapshot.data[index].data['Anfrage vom']}',
                          style: GoogleFonts.lexendDeca(),
                        ),
                        onTap: () => navigateToDetail(snapshot.data[index]),
                        leading: Icon(
                          Icons.business_center,
                          color: Colors.blue,
                        ),
                        trailing: IconButton(
                            icon: Icon(Icons.sort),
                            onPressed: () {
                              getDocIndex();
                            }),
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider();
                    },
                  );
                }
              }),
        );
      }
    }
    
    class AdminsDetails extends StatefulWidget {
      final DocumentSnapshot post;
      AdminsDetails({this.post});
    
      @override
      _AdminsDetailsState createState() => _AdminsDetailsState();
    }
    
    String keyID;
    
    class _AdminsDetailsState extends State<AdminsDetails> {
      //Anfragen löschen intern
      deleteDocument() async {
        /* CollectionReference collectionReference =
            Firestore.instance.collection("Requests");
        QuerySnapshot querySnapshot = await collectionReference.getDocuments();
    
        querySnapshot.documents[0].reference.delete();
    */
    
        Firestore.instance.collection('Requests').document(keyID).delete();
      }
    
      //Anfragen intern ändern, anpassen! Button in der Appbar!
      TextEditingController adminComment = TextEditingController();
      updateData() async {
        CollectionReference collectionReference =
            Firestore.instance.collection("Requests");
        QuerySnapshot querySnapshot = await collectionReference.getDocuments();
        querySnapshot.documents[0].reference
            .updateData({'Administrator Anmerkung': adminComment.text});
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(
              'Anfrage von ${widget.post.data["Name"]}',
              style: GoogleFonts.lexendDeca(),
            ),
            centerTitle: true,
            actions: [
              IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () {
                    setState(() {
                      updateData();
                    });
                  })
            ],
          ),
          body: SingleChildScrollView(
            child: Container(
              child: Padding(
                padding: const EdgeInsets.all(24.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Kontaktdaten des Kunden: ',
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
                    ),
                    TextButton(
                      onPressed: () => customLaunch(
                          'mailto:${widget.post.data["Email"]}?subject=Feed%20back&body=Write your%20feedback'),
                      child: Text('Email: ${widget.post.data["Email"]}',
                          style: TextStyle(fontSize: 18)),
                    ),
                    SizedBox(
                      child: Container(color: Colors.amber),
                    ),
                    TextButton(
                      onPressed: () =>
                          customLaunch('tel: ${widget.post.data["Telefon"]}'),
                      child: Text('Telefon: ${widget.post.data["Telefon"]}',
                          style: TextStyle(fontSize: 18)),
                    ),
                    Divider(),
                    Text(
                      'Kundenanschrift: ',
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    TextButton(
                      child: Text('${widget.post.data["Anschrift"]}'),
                      onPressed: () => Navigator.push(context,
                          MaterialPageRoute(builder: (BuildContext context) {
                        return MapsDemo();
                      })),
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    Divider(),
                    Text(
                      'Kommentar:',
                      style: TextStyle(fontWeight: FontWeight.w200, fontSize: 18.0),
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text('${widget.post.data["Kommentar"]}',
                        style: GoogleFonts.lexendDeca()),
                    Divider(),
                    Text(
                      'Details der Anfrage: ',
                      style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text('Anfrage vom: ${widget.post.data["Anfrage vom"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text('Küchenlänge: ${widget.post.data["Küchenlaenge"]} Meter',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text('Hängeschränke: ${widget.post.data["Hängeschränke"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                        'Gebrauchte Küche: ${widget.post.data["Gebrauchte Küche"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                        'Arbeitsplatte schneiden: ${widget.post.data["Arbeitsplatte bearbeiten"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                        'Anschluss Waschmaschine: ${widget.post.data["Anschluss WaMa"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                        'Anschluss Spülmaschine: ${widget.post.data["Anschluss Spuel"]}',
                        style: GoogleFonts.lexendDeca()),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                      'Anschluss Herd: ${widget.post.data["Anschluss Herd"]}',
                      style: GoogleFonts.lexendDeca(),
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                      'Wunschdatum Montage: ${widget.post.data["Wunschdatum"]}',
                      style: GoogleFonts.lexendDeca(),
                    ),
                    SizedBox(
                      height: 16.0,
                    ),
                    Text(
                      'Gesamt geschätzt: ${widget.post.data["Gesamt geschätzt"]} Euro',
                      style: GoogleFonts.lexendDeca(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          decoration: TextDecoration.underline),
                    ),
                    TextField(
                        controller: adminComment,
                        decoration: InputDecoration(
                          hintText: 'Anmerkung Administrator:',
                        )),
                    //Kommentare von Administratoren:
                    Container(
                        child: Text(
                      '${widget.post.data['Administrator Anmerkung']}',
                      style: GoogleFonts.lexendDeca(),
                    )),
                    Column(
                      children: [
                        Center(
                          child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: Colors.red,
                              ),
                              onPressed: () {
                                Navigator.push(context, MaterialPageRoute(
                                    builder: (BuildContext context) {
                                  return AlertDialog(
                                    title: Text('Diese Anfrage wirklich löschen?',
                                        style: GoogleFonts.lexendDeca()),
                                    actions: [
                                      TextButton(
                                          onPressed: () {
                                            Navigator.pop(context);
                                          },
                                          child: Text('Abbrechen')),
                                      TextButton(
                                          onPressed: () async {
                                            setState(() {
                                              deleteDocument();
                                              Navigator.push(context,
                                                  MaterialPageRoute(builder:
                                                      (BuildContext context) {
                                                return Admins();
                                              }));
                                            });
                                          },
                                          child: Text('Löschen')),
                                    ],
                                  );
                                }));
                              },
                              child: Text('Anfrage löschen')),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 2020-12-05
      • 2022-07-22
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2021-12-16
      相关资源
      最近更新 更多