'How to delete current user document in firestore collection?
I am adding a button in my flutter app which allows users to delete their account. I also want to delete the user document present in firestore simultaneously. I am trying to achieve this using below code but facing an error.
In below code, I am getting the user uid which is same as the user's doc name :
CollectionReference users = FirebaseFirestore.instance.collection('users');
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
final uid = user?.uid;
final authService = Provider.of<AuthService>(context);
Now I am deleting the current user's document in the users collection:
ElevatedButton(
onPressed: ()async{
await users.doc(uid).delete(); //delete doc
user!.delete().then((value) async { //delete user
await authService.signOut();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(),
),
(Route<dynamic> route) => false);
});
},
But this throws an error when pressed:
type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
The relevant error-causing widget was
StreamBuilder<DocumentSnapshot<Object?>>
lib\screens\quiz_screen.dart:616
When the exception was thrown, this was the stack
#0 CoinsContainer.build.<anonymous closure>
lib\screens\quiz_screen.dart:630
This error repeats everywhere I have a Streambuilder. Why does this error occur and how else do I need to delete the current user document from firestore?
Solution 1:[1]
Do you dispose the streams when the page in which they are used is popped? It seems to me that the deletion of your user works just fine, but that your stream then tries to fetch a deleted user's data from Firestore.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Jacobs |
