当在其他位置更改时,StreamBuilder TextField不会更新其值

时间:2019-04-10 21:36:51

标签: dart flutter bloc rxdart

我有一个遵循BLOC模式的反应式登录表单。我正在尝试以编程方式清除其中的所有值。在我的Bloc中,我的Submit函数将空字符串传递到流接收器:

class Bloc with Validators {
  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();

  Stream<String> get email => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);
  Stream<bool> get submitValid => Observable.combineLatest2(email, password, (String e, String p) {
    var valid = (e != null && e.isNotEmpty)
                && (p != null && p.isNotEmpty);
    print('$e && $p = $valid');
    return valid;
  });

  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;

  submit() {
    final validEmail = _email.value;
    final validPassword = _email.value;
    print('final values: $validEmail && $validPassword');
    changeEmail('');
    changePassword('');
  }

  dispose() {
    _email.close();
    _password.close();
  }
}

当我按下调用此submit()函数的提交按钮时,我得到了两个文本字段的错误消息,因为电子邮件和密码的值在后台已更改,但未进行视觉更新在TextFields中。这是我的TextFields和Submit按钮的StreamBuilder:

Widget emailField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.email,
      builder: (context, snapshot) { // re-runs build function every time the stream emits a new value
        return TextField(
          onChanged: bloc.changeEmail,
          autocorrect: false,
          keyboardType: TextInputType.emailAddress,
          decoration: InputDecoration(
            icon: Icon(Icons.email),
            hintText: 'email address (you@example.com)',
            labelText: 'Email',
            errorText: snapshot.error
          )
        );
      }
    );
  }

  Widget passwordField(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.password,
      builder: (context, AsyncSnapshot<String> snapshot) {
        return TextField(
          onChanged: bloc.changePassword,
          autocorrect: false,
          obscureText: true,
          decoration: InputDecoration(
            icon: Icon(Icons.security),
            hintText: 'must be greater than 6 characters',
            labelText: 'Password',
            errorText: snapshot.error
          )
        );
      }
    );
  }

  Widget submitButton(Bloc bloc) {
    return StreamBuilder(
      stream: bloc.submitValid,
      builder: (context, snapshot) {
        return RaisedButton(
          child: Text('Logins'),
          color: Colors.blue,
          onPressed: !snapshot.hasData || snapshot.hasError || snapshot.data == false
            ? null
            : bloc.submit
        );
      }
    );
  }'

这是我在Bloc中用于验证器的代码:

class Validators {
  final validateEmail = StreamTransformer<String, String>.fromHandlers(
    handleData: (email, sink) {
      RegExp exp = new RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
      var valid = exp.hasMatch(email);
      if (valid) {
        sink.add(email);
      } else {
        sink.add('');
        sink.addError('Invalid email address!');
      }
    }
  );

  final validatePassword = StreamTransformer<String, String>.fromHandlers(
    handleData: (password, sink) {
      var valid = password.length >= 6;
      if (valid) {
        sink.add(password);
      } else {
        sink.add('');
        sink.addError('Password must be at least 6 characters long!');
      }
    }
  );
}

在我的验证器中,每当出现错误时,我都会发出一个空字符串。这样一来,当用户使过去有效的内容无效时,submitValid getter就会起作用。

2 个答案:

答案 0 :(得分:1)

我知道已经很久了,但这是我解决问题的方式。

首先,我为TextEditingController创建了一个TextField。然后,我在BLoC上创建了两个方法:updateTextOnChangedupdateTextElsewhere。在第一个中,我刚刚检索了该值(因为以后需要使用它)。在第二个上,我添加了一个接收器以更新TextField上的控制器。

小部件:

  return StreamBuilder<String>(
      stream: bloc.streamText,
      builder: (context, snapshot) {
        _controller.text = snapshot.data;
        return Expanded(
            child: TextField(
            controller: _controller,
            onChanged: (value) => {bloc.updateTextOnChanged(value)},
          ),
        );
      }
   );

集团:

  Stream<String> get streamText => _controllerTxt.stream;
  String _myText;

  void updateTextElsewhere(String value) {
    _controllerTxt.sink.add(value);
  }

  void updateTextOnChanged(String value) {
    _myText = value;
  }

然后,只要需要在onChanged之外进行更新,就只需调用updateTextElsewhere()

在这种情况下,只需添加一个空字符串,例如:updateTextElsewhere("");

答案 1 :(得分:0)

在Submit()中,您似乎想重设用户名和密码

changeEmail('');
changePassword('');

正如您所评论的,“每当流发出新值时,重新运行构建函数”。由于值更新为空,因此它将重新构建UI。也许是引起问题的原因?