adar2378 / pin_code_fields

A flutter package which will help you to generate pin code fields with beautiful design and animations. Can be useful for OTP or pin code inputs 🤓🤓
https://pub.dev/packages/pin_code_fields
MIT License
677 stars 330 forks source link

_key.currentState is null #379

Open hsynksahin opened 2 months ago

hsynksahin commented 2 months ago

Im trying to validate the pin user entered. On a normal FromField you can put a validator parameter (just like in this package) and then you can reach to it's state trough key then command validate to field's value. The problem is _keyPin.currentState is always be null while we are using this package. Is there any other way to command it to validate ? (Except for the AutoValidate parameter of the package's widget.)

I know that just using autovalidateMode: AutovalidateMode.onUserInteraction will do the same but here is an example code that not working :

// In a statful widget
final _keyPin = GlobalKey<FormFieldState>();

// Somewhere in the build
PinCodeTextField(
    length: 6,
    key: _keyPin
    autoFocus: true,
    focusNode: _focusPin,
    appContext: context,
    controller: _controllerPin,
    obscureText: !_showPin,
    autoDisposeControllers: false,
    keyboardType: TextInputType.number,
    textInputAction: TextInputAction.done,
    animationType: AnimationType.scale,
    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
    beforeTextPaste: (text) => false,
    backgroundColor: Colors.transparent,
    validator: (value) {
    if (value == null || value.isEmpty) {
        return Localization.of(context).fieldShouldNotEmpty;
      } else if (RegExp(r'\d{6}').stringMatch(value) != value) {
        return Localization.of(context).fieldPinRule;
      }
      return null;
    },
    onChanged: (value) {
      _isValid = _keyPin.currentState?.validate() ?? false;
      // always false because currentState is null
      if (mounted) setState(() {});
    },
    pinTheme: ...,
  )

The idea here to make a validation system just a little different. Or: Open/Close a button when the field is validated.

Right now my code has an other method that returns String? and both validator and validation check executes that function like _isValid = Validators.pin(context, value)?.isEmpty ?? true; (Does the same I guess).

But in order to use the widget system better I wish we could reach the validation trough GlobalKey. I think it not very possible because of multiple fields (?) has multiple keys.