Home > Software engineering >  Flutter: Fluttertoast not appearing after catching error
Flutter: Fluttertoast not appearing after catching error

Time:10-12

I am having a problem when calling the resetPassword method from Firebase. I am catching the error and showing a fluttertoast, when there is an error. Somehow the fluttertoast is not showing which should mean, that the try worked. But when I print the result, it returns null (see code below).

At the same time I am actually receiving a password reset mail, which means the method worked fine. What is wrong with my code? And how can I make sure that the flutter alert (see second code snippet) is showing when the reset email is sent, so the user can know that the mail was sent succesfully?

Future resetPassword({required String email}) async {
try {
  await _auth.sendPasswordResetEmail(email: email);
} catch (error) {
  Fluttertoast.showToast(
      msg: error.toString(),
      gravity: ToastGravity.TOP,
      backgroundColor: Colors.black,
      textColor: Colors.white);
  return null;
}

}

Here is the onPressed Method where I also print the result:

onPressed: () async {
                  dynamic result =
                      await _auth.resetPassword(email: mailController.text);
                  print(result);
                  if (result != null) {
                    setState(() {
                      Alert(
                        context: context,
                        type: AlertType.error,
                        title: "E-mail sent",
                        desc:
                            "Please check your inbox and junk folder for the password reset mail.",
                        buttons: [
                          DialogButton(
                            child: Text(
                              "OK",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 20),
                            ),
                            onPressed: () => Navigator.pop(context),
                            width: 120,
                          )
                        ],
                      ).show();

CodePudding user response:

Firebase does not generate exceptions when the request failed instead it returns a response with statusCode other than 200(Some APIs return exception that you can handle inside catch block). You need to add check inside the try block like that.

try {
  final response = await _auth.sendPasswordResetEmail(email: email);
  if (response.statusCode == 200) {
    // email sent
  } else {
   // email not sent
   // show toast here
  }
} catch (error) {
 ....
}

CodePudding user response:

From the package's API docs, you just have to replace Fluttertoast with FlutterToast (change with the capital T) and the showToast method parameters too have been changed.

Refer to the How To Use for more details and snippet: https://pub.dev/packages/fluttertoast/example

  • Related