skip to Main Content

I am trying for the dialog box to appear with the error message when the user input his email. It is not working, it is not appearing in the app as well as not printing on the console.
Here is the code and the console when i,m running the app.I m using firebase as backend and trying to create forgot password page to send a reset password link when user click on button


import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:ur_mentor/auth_file/main_page.dart';
import 'package:ur_mentor/pages_file/LoginPage.dart';
//import 'package:ur_mentor/pages_file/LoginPage.dart';

class ForgotPassword extends StatefulWidget {
  const ForgotPassword({Key? key}) : super(key: key);

  @override
  State<ForgotPassword> createState() => _ForgotPasswordState();
}

class _ForgotPasswordState extends State<ForgotPassword> {
  final _emailController = TextEditingController();

  @override
  void dispose() {
    _emailController.dispose();
    super.dispose();
  }

  Future passwordReset() async {
    try {
      FirebaseAuth.instance
          .sendPasswordResetEmail(email: _emailController.text.trim());
    } on FirebaseAuthException catch (e) {
      debugPrint(e.toString());
      showDialog(
          context: context,
          builder: (BuildContext context) => AlertDialog(
                content: Text(e.toString()),
              ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      body: Column(
        children: [
          //Back IconButton
          Padding(
            padding: const EdgeInsets.fromLTRB(300, 30, 0, 0),
            child: IconButton(
              onPressed: ()=> Navigator.pop(context,false),
              icon: const Icon(Icons.exit_to_app_outlined),
              iconSize: 33.0,
              splashColor: Colors.blue,
              splashRadius: 30,
            ),
          ),

          //Enter email text
          Padding(
            padding: EdgeInsets.fromLTRB(10, 80, 10, 0),
            child: Text(
              'Enter the email to receive reset password link',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                fontFamily: 'AppleFont',
              ),
              textAlign: TextAlign.center,
            ),
          ),

          //email Textfield
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25),
            child: Container(
              //decoration: BoxDecoration(
              //color: Colors.grey[200],
              // border: Border.all(color: Colors.white),
              //borderRadius: BorderRadius.circular(20),
              //),
              child: TextField(
                controller: _emailController,
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.grey[200],
                  hintText: '[email protected]',
                  labelText: 'Email',
                  prefixIcon: Icon(Icons.mail),
                  suffixIcon: _emailController.text.isEmpty
                      ? Container(
                          width: 0,
                        )
                      : IconButton(
                          icon: Icon(Icons.close),
                          onPressed: () => _emailController.clear(),
                        ),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12.0)),
                ),
                keyboardType: TextInputType.emailAddress,
                textInputAction: TextInputAction.done,
              ),
            ),
          ),

          //Reset Button
          ElevatedButton(
            onPressed: passwordReset,
            child: Text(
              'Reset Password',
              style: TextStyle(
                  fontSize: 16,
                  fontFamily: 'AppleFont',
                  fontWeight: FontWeight.w600),
            ),
            style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                padding: EdgeInsets.fromLTRB(20, 8, 20, 8)),
          ),
        ],
      ),
    );
  }
}

//here is the console display

W/System  (25885): Ignoring header X-Firebase-Locale because its value was null.
E/flutter (25885): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/invalid-email] The email address is badly formatted.
E/flutter (25885): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter (25885): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:296:18)
E/flutter (25885): <asynchronous suspension>
E/flutter (25885): #2      MethodChannelFirebaseAuth.sendPasswordResetEmail (package:firebase_auth_platform_interface/src/method_channel/method_channel_firebase_auth.dart:343:7)
E/flutter (25885): <asynchronous suspension>
E/flutter (25885): 
E/Parcel  (25885): Reading a NULL string not supported here.

2

Answers


  1. You need to pass your BuildContext to the resetPassword function:

     Future passwordReset(BuildContext context) async {
        try {
          FirebaseAuth.instance
              .sendPasswordResetEmail(email: _emailController.text.trim());
        } on FirebaseAuthException catch (e) {
          debugPrint(e.toString());
          showDialog(
              context: context,
              builder: (BuildContext context) => AlertDialog(
                    content: Text(e.toString()),
                  ));
        }
      }
    

    Then change the onPressed method of your ElevatedButton to this:

     ElevatedButton(
                onPressed: () => passwordReset(context), // ADD THIS
                child: Text(
                  'Reset Password',
                  style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'AppleFont',
                      fontWeight: FontWeight.w600),
                ),
                style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    padding: EdgeInsets.fromLTRB(20, 8, 20, 8)),
              ),
    
    Login or Signup to reply.
  2. This is what worked for me.

    Future passwordReset() async {
        try {
          print(_emailController.text.trim());
          await FirebaseAuth.instance
              .sendPasswordResetEmail(email: _emailController.text.trim());
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                content: Text(
                  'An email was sent ton${_emailController.text.trim()}',
                  style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.center,
                ),
              );
            },
          );
        } on FirebaseAuthException catch (e) {
          print(e);
    
          if (e.code.toString() == 'invalid-email') {
          showDialog(
              context: context,
              builder: (context) {
                return AlertDialog(content: Text(e.message.toString()));
              });
          }
          //if (e.code.toString() == 'missing-email') {}
          //if (e.code.toString() == 'user-not-found') {}
        } catch (e) {
          return false;
        }
      }
    

    Modify it according to your needs.

    You might want to try this as well.

    e.code.toUpperCase() == 'INVALID-EMAIL'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search