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.
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),
)
],
),
);
}
}
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.