ahmdZhran / instagram_clone

0 stars 0 forks source link

Multiple widgets used the same GlobalKey Error in Auth Forms #17

Closed ahmdZhran closed 3 weeks ago

ahmdZhran commented 3 weeks ago

Description:

I encountered a "Multiple widgets used the same GlobalKey" error while implementing authentication forms (Login, SignUp, Forgot Password) in my Flutter app using AuthCubit. The error occurred because multiple widgets were using the same GlobalKey, which led to conflicts during the form validation process.


class AuthCubit extends Cubit<AuthState> {
  AuthCubit(this._authRepository, this._pickerImageService)
      : super(AuthInitial());

  final TextEditingController usernameController = TextEditingController();
  final TextEditingController nameController = TextEditingController();
  final TextEditingController emailAddressController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController bioController = TextEditingController();
  Uint8List? profileImage;
  final ImagePickerService _pickerImageService;
  final AuthRepository _authRepository;

  GlobalKey<FormState> loginFormKey = GlobalKey();
  GlobalKey<FormState> signUpFormKey = GlobalKey();
  GlobalKey<FormState> resetPasswordKey = GlobalKey();
ahmdZhran commented 3 weeks ago

Solution

To resolve the issue, I assigned a unique GlobalKey<FormState> to each form widget to ensure there was no overlap. Each form (Login, SignUp and resetPassword) now has its own independent GlobalKey like this


class CustomFormLogInWidget extends StatefulWidget {
  const CustomFormLogInWidget({super.key});

  @override
  State<CustomFormLogInWidget> createState() => _CustomFormLogInWidgetState();
}

class _CustomFormLogInWidgetState extends State<CustomFormLogInWidget> {
  final loginCubit = AuthCubit.getInstance();
  final GlobalKey<FormState> _logInFormKey = GlobalKey<FormState>();
   @override
           // other widget

            child: Form(
              key: _logInFormKey,     // here is our unique formKey
              child: Column(
                children: [