Home > other >  How can I change the validator state from outside it's function
How can I change the validator state from outside it's function

Time:07-20

I created a view model for sign up and in there are my validators.

String? emailValidator(String? s) {
  if(s == null || s.isEmpty || s.isWhiteSpace()){
    return "Email is required";
  }

  if(!s.isValidEmail()){
    return "Invalid email address";
  }

  return null;
}

When I create an account I call createUserWithEmailAndPassword but when the user already exists this throws an exception.

onPressed: () {                  
  final isValid = formKey.currentState!.validate();

  assert(isValid == viewModel.isValid(),
    "The view model and form must agree on whether the form is valid");

  if(isValid && viewModel.isValid()){
    try{
      FirebaseAuth.instance.createUserWithEmailAndPassword(email: viewModel.email!, password: viewModel.password!);
    }catch{
      // what should I do here?
    }
  }
},

Now I want to catch it and update my validator so that i can display an error like "email address already in use". How can I do this?

CodePudding user response:

Create a bool

bool emailExists = false;
String? emailValidator(String? s) {
  if(s == null || s.isEmpty || s.isWhiteSpace()){
    return "Email is required";
  }

  if(!s.isValidEmail()){
    return "Invalid email address";
  }
  if(emailExists) return "Registered Email Exists";
  return null;
}

and on button press in catch you can update the bool and validate again

onPressed: () {                  
  final isValid = formKey.currentState!.validate();

  assert(isValid == viewModel.isValid(),
    "The view model and form must agree on whether the form is valid");

  if(isValid && viewModel.isValid()){
    try{
      FirebaseAuth.instance.createUserWithEmailAndPassword(email: viewModel.email!, password: viewModel.password!);
    }catch{
      emailExists = true;
     formKey.currentState!.validate();
    }
  }
},

CodePudding user response:

Since you to use try/catch, the syntax for handling exception is:

try {
  await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: "[email protected]",
    password: "CorrectHorseBatteryStaple"
  );
} on FirebaseAuthException catch (e) {
  print("Caught FirebaseAuthException");
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text(e.code '\n\n\n' e.message!))
  );                            
} catch (e) {
  print("Caught other error");
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text(e.toString()))
  );                            
}

You likely only need the first catch block which handles FirebaseAuthExceptions, and in there you can use e.code to determine the actual error code from Firebase. For the actual codes, see what are the error codes for Flutter Firebase Auth Exception?

We did an episode of the Flutter Boring Show on this topic a while ago, so I recommend checking that out: Firebase Authentication in Flutter (The Boring Flutter Development Show, Ep. 55), also see the final code of what we created there.

  • Related