Flutter firebase delete user

Delete a User Using Flutter and Firebase

To delete a user in Flutter using Firebase, you need to follow these steps:

  1. Import the necessary packages:
  2. import 'package:firebase_auth/firebase_auth.dart';
        
  3. Get an instance of the FirebaseAuth:
  4. final FirebaseAuth _auth = FirebaseAuth.instance;
        
  5. Get the current user using the currentUser property of the FirebaseAuth:
  6. final user = _auth.currentUser;
        
  7. Call the delete method on the user to delete it:
  8. user.delete().then((value) {
      // User successfully deleted.
    }).catchError((error) {
      // An error occurred while deleting the user.
    });
        

Here’s an example of how you can delete a user using Flutter and Firebase:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  void deleteUser() async {
    final user = _auth.currentUser;
    
    if (user != null) {
      try {
        await user.delete();
        print('User successfully deleted.');
      } catch (error) {
        print('An error occurred while deleting the user: $error');
      }
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Delete User'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Delete User'),
            onPressed: () {
              deleteUser();
            },
          ),
        ),
      ),
    );
  }
}
  

In this example, when the “Delete User” button is pressed, it calls the deleteUser function which retrieves the current user and deletes it using the delete method. If the deletion is successful, it prints a success message. If an error occurs, it prints the error message.

Leave a comment