1

I'm trying to login in users using a third party api. But the problem is whenever an error occurs and the catch error is executed the "then" function that holds the navigation to the HomeScreen also is executed. Please is there a way to login user only when there is no error.

void signIn() {
    setState(() {
      _isLoading = true;
    });

    final isValid = _formKey.currentState!.validate();
    if (isValid == false) {
      setState(() {
        _isLoading = false;
      });
      return;
    } else {
      setState(() {
        _isLoading = true;
      });
      Provider.of<Authorization>(context, listen: false)
          .loginUser(
        _emailController.text.trim(),
        _passwordController.text.trim(),
      )
          .catchError((error) {
        const snackBar = SnackBar(
          backgroundColor: Colors.red,
          content: Text("An error occured please try again."),
        );

        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }).then((_) {
        setState(() {
          _isLoading = false;
        });
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: ((context) => const HomeScreen()),
          ),
        );
      });
    }
  }

Thanks in advance.

Ariyo
  • 49
  • 4

1 Answers1

0

You can use another way to run this function and make it easier to you to understand and also more easy to code

void signIn() async{
setState(() {
  _isLoading = true;
});

final isValid = _formKey.currentState!.validate();
if (isValid == false) {
  setState(() {
    _isLoading = false;
  });
  return;
} else {
  setState(() {
    _isLoading = true;
  });
// here you need to make the login user function back a bool value either true or false true for success false for failed 
  final result = await Provider.of<Authorization>(context, listen: false)
      .loginUser(
    _emailController.text.trim(),
    _passwordController.text.trim(),
  )

// hide the loading
setState(() {
  _isLoading = false;
});

// check if the result back from the function is true we success
if(result == true){
    

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: ((context) => const HomeScreen()),
      ),
    );

}
// else we failed
else{
    
    const snackBar = SnackBar(
      backgroundColor: Colors.red,
      content: Text("An error occured please try again."),
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}

}

this answer i think will work perfectly with you you just need to make the login user function return a Future and if success return true or if it failed return false and every thing will work successfully

thanks and i hope this answer helps you