We noticed you're using an ad blocker

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Duplicate GlobalKey detected - [Solved]

club-football-league

FootballDesk

Get update standing EPL, UEFA, LaLiga and more

Get Now

A common error that occurs to every beginner flutter developer is Duplicate GlobalKey detected in widget tree. It's a panic situation. If you are looking for a solution for the error duplicate global key problem both raw flutter project or GetX library, then this post will help you get rid of this problem.

With GetX Library

Scenario: This problem occurs when you create a global key inside the controller and use it on your screen page. To solve this, make your screen page a stateful widget and create the form state global key and pass it to the controller when needed. Follow the example below.

GetX controller

class ProductCreateCtrl extends GetxController {
  
  void saveData({@required formKey}) async {
    //do your code
  }

}

Page Screen

class ProductCreate extends StatefulWidget {
  @override
  _ProductCreateState createState() => _ProductCreateState();
}

class _ProductCreateState extends State<ProductCreate> {

  final ctrl = Get.put(ProductCreateCtrl());
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();


  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[


          ElevatedButton(
            child: const Text('Submit'),
            onPressed: () => _ctrl.saveData(formKey: _formKey),
          )
          
        ],
      ),
    );
  }

}

 

With Raw/Other projects

Remove the static, final keyword from your global key and make it private inside your page widget.

class _ProductCreateState extends State<ProductCreate> {
   //don't
   static final GlobalKey<FormState> formKey = GlobalKey<FormState>();

   //do this
   GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    @override
    Widget build(BuildContext context) {
      
    }
}

 

Hope this post will get you to get rid of this kind of problem during flutter application development. If you find this post is helpful, please share this post with others.


Share on


Related Post


Flutter method channel tutorial

Flutter native splash screen without plugin!

Flutter plugin development - Step by step

Flutter async validation tutorial

Flutter JSON to model converter online

Flutter ListView search tutorial