flutterfirebaselistview

Use Key from ListView of Firebase data in another (onPressed)-function


as you see in my code I want to export the key (docID of ListTile) to the function onPressedNegativ. With that I want to be able to edit the data of my firestore database. The exact idea behind that is, to update the field ergebnis to another value that a different icon is visible as leading of my ListTile.

So the question is, how can I export the right docID of the ListTile where I pressed the button which bring me to the onPressedNegativ function?

Thanks for any kind of help.

void onPressedNegativ() {
    // update something in firebase
    // how can I get the actual docID?
  }



  Widget _buildList(QuerySnapshot snapshot) {
    return ListView.separated(
      padding: EdgeInsets.all(20),
      separatorBuilder: (context, index) => Container(
        height: 10,
      ),
      itemCount: snapshot.docs.length,
      itemBuilder: (context, index) {
        final doc = snapshot.docs[index];
        return ListTile(
          key: Key(doc.id),
          leading: (doc["ergebnis"] == "Ausstehend")
              ? Icon(Icons.schedule)
              : Icon(Icons.check),
          title: Text(
            doc["nachname"] + ", " + doc["vorname"],
          ),
          subtitle: Text(doc["adresse"] +
              " / " +
              doc["Geburtsdatum"] +
              " / " +
              doc["telefon"]),
          trailing: Wrap(
            spacing: 12,
            children: [
              OutlineButton.icon(
                borderSide: BorderSide(color: Colors.red),
                onPressed: onPressedNegativ,
                icon: Icon(
                  Icons.cancel_rounded,
                  color: Colors.red,
                ),
                label: Text(
                  "Test positiv",
                  style: TextStyle(color: Colors.red),
                ),
                shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(30.0)),
              ),
              OutlineButton.icon(
                borderSide: BorderSide(color: Colors.green),
                onPressed: () {},
                icon: Icon(
                  Icons.check_box_rounded,
                  color: Colors.green,
                ),
                label: Text(
                  "Test negativ",
                  style: TextStyle(color: Colors.green),
                ),
                shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(30.0)),
              )
            ],
          ),
        );
      },
    );
  }
}

Solution

  • Void onPressedNegativ(String docID) {
        //Use your docID to do logic you want
        // Or update something in firebase
        print("got this ID from my button: $docID");
      }
    

    And when you want to call it from onpressed:

    onPressed: ()=> onPressedNegativ(doc.id),