skip to Main Content

I am currently working on a reset password page. I am using firebase auth and I am trying to catch errors with "try catch". When I enter e mail in a wrong format or leave it empty I want to display some alert dialog. However when I write wrong e mail or leave it empty, my app crashes and give this error message:

Exception has occurred.

PlatformException (PlatformException(invalid-email, The email address is badly formatted., {code: invalid-email, message: The email address is badly formatted., nativeErrorMessage: The email address is badly formatted., nativeErrorCode: 17008, additionalData: {}}, null))

Also I realized that if I run app on terminal with flutter run, catch method works and the alert dialog comes to screen but after that application stops working in VScode so that I could not hot restart or hot reload –

Full code:

 // ignore_for_file: use_build_context_synchronously
    import 'dart:io';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:petinonedemo/main.dart';
    
    class ForgotPasswordPage extends StatefulWidget {
      const ForgotPasswordPage({super.key});
    
      @override
      State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
    }

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _phoneNumberController = TextEditingController();

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

  void _showIOSAlert(BuildContext context, Text myContent) {
    showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
        content: myContent,
        actions: <CupertinoDialogAction>[
          CupertinoDialogAction(
            isDefaultAction: true,
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('Geri dön'),
          ),
        ],
      ),
    );
  }

  void _showAndroidAlert(BuildContext context, Text myContent) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          content: myContent,
          //buttons?
          actions: <Widget>[
            TextButton(
              child: const Text("Geri dön"),
              onPressed: () {
                Navigator.of(context).pop();
              }, //closes popup
            ),
          ],
        );
      },
    );
  }

  Future passwordReset() async {
    String resetMail = _emailController.text.toString();

    try {
      await FirebaseAuth.instance
          .sendPasswordResetEmail(email: _emailController.text.trim());
      if (Platform.isIOS) {
        _showIOSAlert(
          context,
          Text('$resetMail adresine şifre sıfırlama linki gönderildi'),
        );
      } else {
        _showAndroidAlert(
          context,
          Text('$resetMail adresine şifre sıfırlama linki gönderildi'),
        );
      }
    } on FirebaseAuthException catch (e) {
      if (Platform.isIOS) {
        return _showIOSAlert(
          context,
          Text(
            e.message.toString(),
          ),
        );
      } else {
        return _showAndroidAlert(
          context,
          Text(
            e.message.toString(),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Şifremi Unuttum"),
        elevation: 0,
      ),
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 70,
                padding: const EdgeInsets.symmetric(horizontal: 25),
                child: TextField(
                    controller: _emailController,
                    cursorColor: Colors.white,
                    keyboardType: TextInputType.emailAddress,
                    style: const TextStyle(color: Colors.white),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        hintText: "E-posta",
                        hintStyle: const TextStyle(color: Colors.white),
                        labelStyle: const TextStyle(color: Colors.white),
                        filled: true,
                        fillColor: applicationPurple,
                        border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                            borderRadius: BorderRadius.circular(20)))),
              ),
              Container(
                decoration: BoxDecoration(
                    color: applicationOrange,
                    borderRadius: BorderRadius.circular(20)),
                height: 50,
                padding: const EdgeInsets.symmetric(horizontal: 25.0),
                child: TextButton(
                  onPressed: () {
                    passwordReset();
                  },
                  child: const Text(
                    "Şifremi Sıfırla",
                    style: TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    I changed the Breakpoints inside the Run and Debug area: All Exceptions --> Unchecked Uncaught Exceptions --> Checked

    Now it is working. If anyone is struggling with this issue, I hope it helps.


  2. you are getting this exception because you are catching only firebase exceptions:

    try this:

    
     // ignore_for_file: use_build_context_synchronously
        import 'dart:io';
        import 'package:firebase_auth/firebase_auth.dart';
        import 'package:flutter/cupertino.dart';
        import 'package:flutter/material.dart';
        import 'package:petinonedemo/main.dart';
        
        class ForgotPasswordPage extends StatefulWidget {
          const ForgotPasswordPage({super.key});
        
          @override
          State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
        }
    
    class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
      final TextEditingController _emailController = TextEditingController();
      final TextEditingController _phoneNumberController = TextEditingController();
    
      @override
      void dispose() {
        _emailController.dispose();
        _phoneNumberController.dispose();
        super.dispose();
      }
    
      void _showIOSAlert(BuildContext context, Text myContent) {
        showCupertinoModalPopup<void>(
          context: context,
          builder: (BuildContext context) => CupertinoAlertDialog(
            content: myContent,
            actions: <CupertinoDialogAction>[
              CupertinoDialogAction(
                isDefaultAction: true,
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text('Geri dön'),
              ),
            ],
          ),
        );
      }
    
      void _showAndroidAlert(BuildContext context, Text myContent) {
        showDialog(
          context: context,
          barrierDismissible: true,
          builder: (BuildContext context) {
            return AlertDialog(
              content: myContent,
              //buttons?
              actions: <Widget>[
                TextButton(
                  child: const Text("Geri dön"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  }, //closes popup
                ),
              ],
            );
          },
        );
      }
    
      Future passwordReset() async {
        String resetMail = _emailController.text.toString();
    
        try {
          await FirebaseAuth.instance
              .sendPasswordResetEmail(email: _emailController.text.trim());
          if (Platform.isIOS) {
            _showIOSAlert(
              context,
              Text('$resetMail adresine şifre sıfırlama linki gönderildi'),
            );
          } else {
            _showAndroidAlert(
              context,
              Text('$resetMail adresine şifre sıfırlama linki gönderildi'),
            );
          }
        } on FirebaseAuthException catch (e) {
          if (Platform.isIOS) {
            return _showIOSAlert(
              context,
              Text(
                e.message.toString(),
              ),
            );
          } else {
            return _showAndroidAlert(
              context,
              Text(
                e.message.toString(),
              ),
            );
          }
        } catch (_){
    //-------------------------
          print('Generic Auth Exception')
          
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("Şifremi Unuttum"),
            elevation: 0,
          ),
          body: SafeArea(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    height: 70,
                    padding: const EdgeInsets.symmetric(horizontal: 25),
                    child: TextField(
                        controller: _emailController,
                        cursorColor: Colors.white,
                        keyboardType: TextInputType.emailAddress,
                        style: const TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.never,
                            hintText: "E-posta",
                            hintStyle: const TextStyle(color: Colors.white),
                            labelStyle: const TextStyle(color: Colors.white),
                            filled: true,
                            fillColor: applicationPurple,
                            border: OutlineInputBorder(
                                borderSide: BorderSide.none,
                                borderRadius: BorderRadius.circular(20)))),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: applicationOrange,
                        borderRadius: BorderRadius.circular(20)),
                    height: 50,
                    padding: const EdgeInsets.symmetric(horizontal: 25.0),
                    child: TextButton(
                      onPressed: () {
                        passwordReset();
                      },
                      child: const Text(
                        "Şifremi Sıfırla",
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search