验证成功时,TextField显示错误

时间:2019-07-06 16:37:08

标签: flutter dart textfield rxdart

我有一个用于PhoneNumber enter image description here的文本字段

当电话号码是10位数字时,我不想显示任何错误,但如果不是10位数字,我想显示错误,但是当电话号码为10位数字时,我会收到错误消息,而当电话号码是10位数字时,则不会出现错误。不是10位数字

以下是我的代码

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;
}

我的TextField如下

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,


                  ),
                ),
              ));
        });

1 个答案:

答案 0 :(得分:1)

您应该将错误而不是数据传递给InputDecoration

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,
),