skip to Main Content

**Hi, I am using a cubit for user sign up and when the register button is clicked once it works fine. If there is error and user is not routed to home page and I click the button again nothing happens.

See code below.

Please help!!!

user_signup_cubit.dart

import 'package:ach_mobile/main.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'user_signup_state.dart';

class UserSignupCubit extends Cubit<UserSignupState> {
  UserSignupCubit()
      : super(
          UserSignupInitial(),
        );

  Future<void> signupUser({required String email, required String password}) async {
    try {
      final response = await supabaseInitialization.auth.signUp(email: email, password: password);
      if (response.user == null) {
        throw Exception('Pressure... no user.');
      }
      emit(UserSignupSuccess());
    } catch (e) {
      emit(
        const UserSignupFailed(error: 'Failed to register user...'),
      );
    }
  }
}

user_signup_state.dart**

part of 'user_signup_cubit.dart';

sealed class UserSignupState extends Equatable {
  const UserSignupState();

  @override
  List<Object> get props => [];
}

final class UserSignupInitial extends UserSignupState {}

final class UserSignupLoading extends UserSignupState {}

final class UserSignupSuccess extends UserSignupState {}

final class UserSignupFailed extends UserSignupState {
  final String error;

  const UserSignupFailed({required this.error});

  @override
  List<Object> get props => [error];
}

user_signup.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:ach_mobile/data_layer/cubits/user_signup/user_signup_cubit.dart';

class UserSignUp extends StatelessWidget {
  const UserSignUp({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => UserSignupCubit(),
      child: RegistrationForm(),
    );
  }
}

class RegistrationForm extends StatelessWidget {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  RegistrationForm({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('User Registration'),
      ),
      body: BlocConsumer<UserSignupCubit, UserSignupState>(
        listener: (context, state) {
          if (state is UserSignupSuccess) {
            // Navigate to the next screen or perform necessary actions
          } else if (state is UserSignupFailed) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('Registration failed: ${state.error}'),
              ),
            );
          }
        },
        builder: (context, state) {
          if (state is UserSignupLoading) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextField(
                    controller: emailController,
                    decoration: const InputDecoration(labelText: 'Email'),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: passwordController,
                    decoration: const InputDecoration(labelText: 'Password'),
                    obscureText: true,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () {
                      final email = emailController.text;
                      final password = passwordController.text;
                      context.read<UserSignupCubit>().signupUser(
                            email: email,
                            password: password,
                          );
                    },
                    child: const Text('Register'),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }
}

I am using a cubit and I tried using chat GPT for help but no help there.

2

Answers


  1. Maybe the problem is here:

    Future<void> signupUser({required String email, required String password}) async {
        try {
          final response = await supabaseInitialization.auth.signUp(email: email, password: password);
          if (response.user == null) {
            throw Exception('Pressure... no user.'); // <----- HERE
          }
          emit(UserSignupSuccess());
        } catch (e) {
          emit(
            const UserSignupFailed(error: 'Failed to register user...'),
          );
        }
      }
    

    Because when response.user == null, you just throw the error but do not handle it.

    You can try:

      Future<void> signupUser(
          {required String email, required String password}) async {
        try {
          final response = await supabaseInitialization.auth
              .signUp(email: email, password: password);
          if (response.user == null) {
            emit(
              const UserSignupFailed(error: 'Your custom message...'),
            );
          } else {
            emit(UserSignupSuccess());
          }
        } catch (e) {
          emit(
            const UserSignupFailed(error: 'Failed to register user...'),
          );
        }
      }
    
    Login or Signup to reply.
  2. If you emit the same state in a BLoC, the listeners might not be notified by default. When using BLoC with BlocBuilder or BlocListener, these widgets rely on changes in the state instance to trigger a rebuild or respond to changes.
    Since you are emitting const UserSignupFailed(error: ‘Failed to register user…’)
    try

    import 'package:ach_mobile/main.dart';
    import 'package:bloc/bloc.dart';
    import 'package:equatable/equatable.dart';
    
    part 'user_signup_state.dart';
    
    class UserSignupCubit extends Cubit<UserSignupState> {
      UserSignupCubit()
          : super(
              UserSignupInitial(),
            );
    
      Future<void> signupUser({required String email, required String password}) async {
        try {
          final response = await supabaseInitialization.auth.signUp(email: email, password: password);
          if (response.user == null) {
            throw Exception('Pressure... no user.');
          }
          emit(UserSignupSuccess());
        } catch (e) {
    //changed hereeee ---------------------------------------------------
          emit(
            const UserSignupFailed(error: 'Failed to register user... $email $password'),
          );
        }
      }
    }
    

    try using different email or password.Cause that will change the content of state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search