rxDart BehaviorSubject的值在sink.addError上不为null

时间:2019-03-15 11:03:48

标签: flutter

我是使用rxDart和bloc的新手。我实现了一个转换来验证输入。当我在接收器上侦听数据时,它可以正确输出(如果错误,则为null,如果没有错误,则为value),但是当我打印BehaviorSubject的值时,它将不会在错误时表示null,并应打印应该为错误的值。这是我的代码:

  final _phoneNumberController = BehaviorSubject<String>();

  Function(String) get setPhoneNumber => _phoneNumberController.sink.add;

  Observable<String> get phoneNumberValue =>
      _phoneNumberController.stream.transform(_validatePhoneNumber);

  final _validatePhoneNumber = StreamTransformer<String, String>.fromHandlers(
      handleData: (phoneNumber, sink) {
    if (phoneNumber.length > 5 && isNumeric(phoneNumber)) {
      sink.add(phoneNumber);
    } else {
      sink.addError(StringConstant.phoneNumberValidationErrorMessage);
    }
  });
  void signUserIn() {
    print(_phoneNumberController.stream.value); // Prints value that should be an error
  }

  SignInBloc() {
    phoneNumberValue.listen((data) => print(data)); // Just Fine
  }

1 个答案:

答案 0 :(得分:0)

您正在监听数据,但没有监听接收器错误。将您的代码更改为:

 SignInBloc() {
    phoneNumberValue.listen((data) {
      print(data);
      }, 
    onError: (_){
  print(_.toString());
   });
  }