Search code examples
flutterdarttextfieldrxdart

TextField showing error when validation is success


I have a textfield for phoneNumberenter image description here

when the phone number is 10 digit I don't want to show any error but if it is not 10 digit, I want to display error, but I am getting error when phone number is 10 digit and no error when it is not 10 digit

Following is my code

var phoneValidator = StreamTransformer<String, String>.fromHandlers(
      handleData: (phoneNumber, sink) {
    if (phoneNumber.length == 10) {
      sink.add(phoneNumber);
    } else {
      sink.addError(PHONE_NUMBER_ERROR);
    }
  });

class RequestForLoginBloc with RequestForLoginValidators {
final _phoneNumberController = BehaviorSubject<String>();
Function(String) get phoneNumberChanged => _phoneNumberController.sink.add;
Observable<String> get phoneNumber =>
      _phoneNumberController.stream.transform(phoneValidator);
String get phoneNumberValue => _phoneNumberController.stream.value;
}

My TextField is as follows

return StreamBuilder<String>(
        stream: requestForLoginBloc.phoneNumber,
        builder: (context, snapshot) {
          return Theme(
              data: ThemeData(hintColor: Colors.grey),
              child: Container(
                child: TextField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  onChanged: (value) {
                    requestForLoginBloc.phoneNumberChanged(value);
                  },
                  decoration: InputDecoration(
                    hintText: ENTER_YOUR_NUMBER,
                    errorText: snapshot.data,
                    prefix: Padding(
                      padding: const EdgeInsets.only(
                        right: 16,
                      ),
                      child: Text(
                        "+91",

                      ),
                    ),
                    hasFloatingPlaceholder: true,


                  ),
                ),
              ));
        });

Solution

  • You should pass error into InputDecoration instead of data:

    decoration: InputDecoration(
        hintText: ENTER_YOUR_NUMBER,
        errorText: snapshot.error, // <- change to error
        prefix: Padding(
            padding: const EdgeInsets.only(
                right: 16,
            ),
            child: Text(
                "+91",
            ),
        ),
        hasFloatingPlaceholder: true,
    ),