skip to Main Content

Following is my code. I’m trying to return the value of document ID from the Firebase database so I can delete that specific document.

Future<String> getID() async {
    List<String> id = [];

    //Map<String, dynamic> user = jsonDecode(jsonString);
    await FirebaseFirestore.instance.collection("Babies").get().then((event) {
      for (final doc in event.docs) {
        id.add(doc.data()['ID']);
      }
    });

    return id.length > 0 ? id[0] : 'No Id';
  }
}

Here is another code calling the getID().

ElevatedButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(
                    Color.fromARGB(255, 239, 106, 62))),
            child: const Text("Remove Baby"),
            onPressed: () {
              setState(()  {
                DocumentReference _documentReference = FirebaseFirestore
                    .instance
                    .collection('Babies')
                    .doc(getID().toString());

                _documentReference.delete();
                print(getID().toString());
              });
            },
          ),

When running the program, the

print(getID().toString());

returns Instance of ‘_Future<String>’ instead the actual document ID.

2

Answers


  1. since the getId is asynchronous, you will need to await for it until it

    returns String, otherwise it will return the type of the method, try this :
         
       onPressed: () async { // add async
                  setState(()  {
                    DocumentReference _documentReference = FirebaseFirestore
                        .instance
                        .collection('Babies')
                        .doc(getID().toString());
    
                    _documentReference.delete();
                    print(await getID()); // add await
                  });
                },
    
    Login or Signup to reply.
  2. Because Future<:String:> returns a Future<:String:>, not a string. You can get this with await;

    print(await getID());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search