So I am trying cubit state management and through that I am trying to login a user to second screen. The error occurs in cubit states changing as it's stuck on initial State. Upon pressing the login button the cubit functions are called for authentication and if the input is right it changes state to authstate else it goes to errorstate.
code of text button where cubit func is called.
TextButton(
onPressed: () {
//context.cubit<LoginCubit>().emailAuth(mailController.text!);
context
.cubit<LoginCubit>()
.Auth(mailController.text!, passwordController.text!);
print('object');
if (state is AuthState) {
Navigator.of(context).pushNamed('/Second');
} else if (state is ErrorState) {
AlertDialog(
title: const Text('ERROR'),
content: Text('retry'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/First');
},
child: const Text('retry'))
],
);
} else {
print(state.toString());
}
},
child: Text('Login')),
Cubit class:
class LoginCubit extends Cubit<LoginState> {
LoginCubit() : super(InitialState());
Auth(String email , String password){
print('test');
if((email.isEmpty || !email.contains('@'))||(password.isEmpty || password.length < 8)){
print('test2');
emit(ErrorState());
}
else {
print('test3');
emit (AuthState());
}
print('test4');
}
}
Cubit State:
abstract class LoginState{}
class InitialState extends LoginState{
@override
String get status => 'Loading';
}
class AuthState extends LoginState{
@override
String get status => 'Authenticated';
}
class ErrorState extends LoginState{
@override
String get status => 'Error';
}
CodePudding user response:
Follow this way
TextButton(
onPressed: () {
BlocProvider.of<LoginCubit>(context)
.Auth("", "");
final state = BlocProvider.of<LoginCubit>(context).state;
if (state is AuthState) {
// Navigator.of(context).pushNamed('/Second');
log("Nav to Second");
} else if (state is ErrorState) {
log("Dialog");
// AlertDialog(
// title: const Text('ERROR'),
// content: Text('retry'),
// actions: <Widget>[
// TextButton(
// onPressed: () {
// Navigator.of(context).pushNamed('/First');
// },
// child: const Text('retry'))
// ],
// );
} else {
log(state.toString());
}
},
child: Text('Login')),
CodePudding user response:
So I have found the issue and it wasn't of state change rather than it was of UI issue. Where I was calling alertdialog directly rather than building a context for it.
Solution:
showDialog(
context: context,
builder: (BuildContext context)=>AlertDialog(
title: const Text('ERROR'),
content: Text('retry'),
actions: <Widget>[
TextButton(onPressed: (){
Navigator.pop(context);
}, child: const Text('retry'))
],
)
);