1

Hy Guys I have connected flutter to my firebase project and used AUTH feature in Firebase but what I would do is to show an error message when a wrong password or Email user is wrong. this is my code:

Widget submitButton (){
    return Container(
      child: SizedBox(
        width: 220,
        height: 40,
        child: MaterialButton(
          elevation: 5,
          onPressed: () async {
            setState(() {
              showProgress = true;
            });

            try {
              final newUser = await _auth.signInWithEmailAndPassword(email: email, password: password);
              print(newUser.toString());
              if (newUser != null) {
                Navigator.push(context, PageTransition(
                  type: PageTransitionType.fade,
                  child: WelcomeScreen(),
                ));
                setState(() {
                  showProgress = false;
                });

              }
            } catch (e) {}
          },
          child: Text('Accedi',style: TextStyle(color: Colors.black),),
          color: Colors.white,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
              side: BorderSide(color: Colors.black12,width: 1)),
        ),

      ),
    );
  }
3
  • Try using a Form() with TextFormField() Commented Jul 15, 2020 at 8:08
  • could you be more specific please? Commented Jul 15, 2020 at 8:46
  • Check out the answer I submitted, hope it helps. Commented Jul 15, 2020 at 14:56

3 Answers 3

3

First you need to catch the error, you can do that by using catchError():

final newUser = await _auth.signInWithEmailAndPassword(email: email, password: password)
    .catchError((err) {
          showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Error"),
              content: Text(err.message),
              actions: [
                FlatButton(
                  child: Text("Ok"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          });
    });

Then the showDialog will have err.message which will contain the error received from Firebase Authentication.

Sign up to request clarification or add additional context in comments.

4 Comments

Hello thanks and how to empty the fields once user clicks on OK and return back to the prompt?
You need to use a TextFormField for that and then do myController.text = "";. Check the cookbook its very good flutter.dev/docs/cookbook/forms/retrieve-input
I see that will show the data into the alertDialog. what I want is once I click to try again the go back to the form I want cleaning the login form fields
when u are clicking ok, the alertdialog is poping then all you have to do is empty the fields, check the link i added in the comments
1

You have two options:

1.Use an alert dialog

  void _showAlertDialog(String message) async {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(message),
          actions: <Widget>[
            FlatButton(
              child: Text('Ok'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

full example

  1. Use errorText property in InputDecoration
TextField(
    decoration: InputDecoration(
        errorText: this.errorText,
    ),
)

full example

Comments

0

You can use a Form() with TextFormField()

Something like this:

Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            TextFormField(
              key: ValueKey('email'),
              validator: (value) {
                if (value.isEmpty || !value.contains('@'))
                  return 'Please enter a valid Email address';
                return null;
              },
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(labelText: 'Email address'),
              onSaved: (value) {
                _userEmail = value;
              },
            ),

It's just a dummy, but as you see there's some validation code in the validator attribute.

So what validator does is, if you return null everything is well and good, but if something is wrong, just return the String and it'll be shown below the text form field as an error message.

And to validate you can call a method like this to activate the method while form submission

void _trySubmit() {
final bool isValid = _formKey.currentState.validate();
FocusScope.of(context).unfocus();

if (isValid) {
  _formKey.currentState.save();
  widget.submitFn(
    _userEmail.trim(),
    _userName.trim(),
    _userPassword.trim(),
    _isLogin,
    context,
  );
}}

The method for getting isValid will invoke validation function of all TextFormFields, if all of them are okay, it'll return true else it'll return false.

All the _name are used to store the values in state variables using the onSaved attribute.

Let me know if you have anymore doubts.

Hope this helps✌

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.