0
votes

enter image description here Trying already for a couple of days to get document id of a document in Firestore from my Flutter app. what I want is to update or delete document, but have to identify it first by his id. I have that ID with other values like name, address, etc.., when I open Firestore.

Now I am trying to understand how to get document id into a variable, which I then use in my function to delete or update the document.

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

I understand that widget in a function is not usable. Maybe something with snapshot.data.... but its also marked as red.

This is my function which then should work:

deleteDocument(){

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

}

enter image description here enter image description here

5
check out this link.. link to your Answer - Gbenga B Ayannuga
Check this link... this will help you link - Gbenga B Ayannuga
You actually know the ID while requesting the document. What's the problem ? - Dharmaraj
The problem is, that I need that ID when I am using an app. I don't want to open Firestore to get that id. When I open a Firestores document which is a request from a user, I want to delete it from my app. And to delete it, I can do it by using an ID of a document. So I need a variable which gets an ID from opened document - Michael Karp
@MichaelKarp please share a screenshot of your Firestore structure as well as the Flutter code so we can test stuff. Also what is marked in red? - Dharmaraj

5 Answers

0
votes

If you know the values inside the document, you can use a where query to find all documents that have those parameters.

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

However, if you already have access to the document's data locally, you can pull the reference path from the document snapshot if you have stored it locally. It is only an issue of recovering that data from within your app at that point.

0
votes

Thank you all! I've got it!

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());

Below I get in keyID the Document ID from field in a document. After that I can use the delete function with ID reference.

Firestore.instance.collection('Requests').document(keyID).delete();
-1
votes
getDocIndex() {
  var document = Firestore.instance
      .collection('Requests')
      .document(widget.data['Document ID'].toString())
      .get();
  print(document.id);
}
-1
votes
getDocIndex() async {
  var document = await Firestore.instance
      .collection('Requests')
      .document(widget.data['Document ID'].toString())
      .get();
  print(document.id);
}
-1
votes
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')),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}