Reputation: 2966
is it possible to delete firebase account in authentication on flutter? if yes, how to do that? I have been search but not found the way.
Firestore.instance.collection("users").document(uid).delete().then((_){
// delete account on authentication after user data on database is deleted
});
Upvotes: 18
Views: 33811
Reputation: 81
Here is a sample code from mine:
class FirebaseConnect{
static final CollectionReference _teacherCollectionRef =
FirebaseFirestore.instance.collection('Teacher');
Future<TeacherModel> getTeacher(String id) async {
TeacherModel teacherModel = TeacherModel();
if (id == '') return teacherModel;
await _teacherCollectionRef.doc(id).get().then((value) {
teacherModel =
TeacherModel.fromJson(value.data() as Map<dynamic, dynamic>);
});
return teacherModel;
}
}
And when I wanted to delete that teacher from Teacher collection and from Authentication I used this method:
static Future<void> deleteTeacher(String id) async {
await FirebaseConnect().getTeacher(id).then((value) async{
await FirebaseConnect().deleteUser(value.email!);
await _teacherCollectionRef.doc(id).delete();
});
}
Future<void> deleteUser(String email) async {
await FirebaseAuth.instance.userChanges().listen((event) async {
if (event!.email == email) {
await event.delete();
}
});
}
Upvotes: 1
Reputation: 466
Using flutter, if you want to delete firebase accounts together with the associated firestore user collection document, the following method works fine. (documents in user collection named by the firebase uid).
Database Class
class DatabaseService {
final String uid;
DatabaseService({this.uid});
final CollectionReference userCollection =
Firestore.instance.collection('users');
Future deleteuser() {
return userCollection.document(uid).delete();
}
}
Use Firebase version 0.15.0 or above otherwise, Firebase reauthenticateWithCredential() method throw an error like { noSuchMethod: was called on null }.
Authentication Class
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future deleteUser(String email, String password) async {
try {
FirebaseUser user = await _auth.currentUser();
AuthCredential credentials =
EmailAuthProvider.getCredential(email: email, password: password);
print(user);
AuthResult result = await user.reauthenticateWithCredential(credentials);
await DatabaseService(uid: result.user.uid).deleteuser(); // called from database class
await result.user.delete();
return true;
} catch (e) {
print(e.toString());
return null;
}
}
}
Then use the following code inside the clickable event of a flutter widget tree to achieve the goal;
onTap: () async {
await AuthService().deleteUser(email, password);
}
Upvotes: 21
Reputation: 1179
Code for deleting user:
FirebaseUser user = await FirebaseAuth.instance.currentUser();
user.delete();
Upvotes: 20
Reputation: 598728
To delete a user account, call delete()
on the user object.
For more on this, see the reference documentation for FirebaseUser.delete()
.
Upvotes: 9