Home > database >  What is the meaning of the <FormState> syntax in the GlobalKey<FormState>?
What is the meaning of the <FormState> syntax in the GlobalKey<FormState>?

Time:08-25

I saw a code like below. I understood formKey is defined as GlobalKey type, and basically what <FormState> is? is this type as well?

I can declare field like final formKey GlobalKey; without any errors, but when I use if (_formKey.currentState.validate()) later, flutter says validate() are not defined as methods and finally I'm confusing gramatically what <FormState> is, especially way of using <>?

Or Is this Generics? but I'm still confusing that i just learned that we can use Generics like as type placeholder. But this code shown below seems not like that. I'm sorry that I'm really new about class or objective programing’, and do appreciate your kindness!

class TEST extends ConsumerWidget {
final formKey GlobalKey<FormState>;
//omit

CodePudding user response:

The GlobalKey represents a key that is unique across your entire Flutter app. This is used to uniquely identify elements and provide access to objects that are associated to those elements. If the widget that has the global key associated, is stateful, the key also provide access to it's state.

If you check the GlobalKey class, you'll notice that it is declared as

abstract class GlobalKey<T extends State<StatefulWidget>> extends Key {}

In your case, the FormState should be a sub-class of State, which it is. The FormState represents the state associated to your form. The FormState can be used to save, reset, and validate every FormField in your Form.

TLDR: T is a generic, specifically a class that should extend State<StatefulWidget> . In your case it is used as the return type of T? get currentState {} method and it represents the state of the associated form.

For your issue with the validate() method, you must actually write the validate() method and pass it to the validator: in the TextFormField(validate: HERE) widget. The method needs to return null if everything is ok, and the string with the validation error otherwise.

ex:

String? passwordValidator(String? value){
  if(value == null || value.isEmpty){
    return "Please fill this field";
  }else {
    return null;
   }
} //This is a very dummy validator, do not use it in production.
  • Related