Search code examples
fluttervalidationwidget

How to use Pinput widget in flutter?


I am trying to make a otp field which I can fill manually and validate later. I am using the Pinput package in flutter as it is quite popular. I am facing following problems-

  1. The pin does not start typing unless I enter a . / , in the first field
  2. The Pinput() fields are cleared as soon as I enter the last digit.
  3. How to use this pin and validate it later?

My code is-

               Pinput(
                      length: 6,
                      keyboardType: TextInputType.number,
                      controller: pinController,
                      defaultPinTheme: defaultPinTheme,
                      focusedPinTheme: focusedPinTheme,
                      submittedPinTheme: submittedPinTheme,
                      pinputAutovalidateMode: null,
                      textInputAction: TextInputAction.next,
                      showCursor: true,
                      validator: (s) {
                        print('validating code: $s');
                      },
                      onCompleted: null,
                    ),

Please help!!


Solution

    1. Use onCompleted like this not null
    onCompleted: (pin) => print(pin),
    

    This onCompleted method do like if entering input got finish do something like navigation or check thing

    1. When you entered last digit this will print You need to use regex to validate just search and get what you need
    // In validator you can check 
    Int validDigit = 1234; // this is test digit
    Validator: (input){
        return s == validDigit ? null : 'Pin is incorrect';
    }
    

    Validator works like if your input digit was not like the pattern you need, in this case if the input digit was not equal to the code that you send to user, you need to return error otherwise return null it means code is correct.

    in above e.g the validDigit comes from api or somewhere else

    1. And finally set auto validate like here not null:
    pinputAutovalidateMode: PinputAutovalidateMode.onSubmit,
    

    I hope it works, sorry they are not in order of your question.