Search code examples
flutterflutter-getx

Multiple GlobalKey in single controller - flutter - getX


I'm using getX, I have a problem with GlobalKey, so I have auth controller in my project, this controller is used for two view, which is login view and register view, but when user is in login page and goes to register page or otherwise in console appear this error 'Duplicate GlobalKey detected in widget tree.'

this is my controller:

class AuthController extends GetxController {

    GlobalKey<FormState> loginFormKey;
    GlobalKey<FormState> registerFormKey;
    
    AuthController() {
        loginFormKey = new GlobalKey<FormState>();
        registerFormKey = new GlobalKey<FormState>();
    }

  //some function
}

login and register view is like this view:

Widget buildBody(BuildContext context) {
    return Form(
      key: controller.loginFormKey,
      child: ListView(
        primary: true,
        children: [
           //textFormField here
        ],
      ),
    );
  }

i'm sorry for my english


Solution

  • You should not put your keys in a controller. Specially GlobalKey. Put them on the corresponding widgets instead. Form keys are UI layer component, which have different lifecycles than that of GetxControllers. Also, you just should not put your UI layer objects into logic layer.