Use Cubit for Flutter form

Issue

I’m trying to use Cubit state management for a form (validation and submit). Is there any example I can follow?

I have already tried to implement it and it works, but every time there is an error, it shows me the form again with empty fields because the widget is repainted with initial data. How can I solve it?

Here my Cubit consumer code on the form:

BlocConsumer<LoginCubit, LoginState> buildLoginCard(BuildContext context) {
  return BlocConsumer<LoginCubit, LoginState>(
    listener: (context, state) {
      if (state is LoginError) {
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(state.message),
            backgroundColor: Colors.red,
          ),
        );
      } else if (state is LoginSuccess) {
        BlocProvider.of<AuthCubit>(context).autoLogin();
      }
    },
    builder: (context, state) {
      if (state is LoginInProgress) {
        return LoadingWidget();
      } else {
        return LoginCardWidget();
      }
    },
  );
}

Solution

you might try to add this to your BlocConsumer after listener

buildWhen: (previous, current) {
    if (current is LoginError)
      return false;
    else
      return true;
  },

in this case if the state is error it will not rebuild the widget agin and the fields will have there own values without being changed

Answered By – Baraa Aljabban

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.