Flutter如何使用rxdart检查提交时文本字段是否为空

我有 2 个文本字段检查值更改时是否为空,但问题是如果我按下提交功能并且文本字段为空,它不会显示错误。如何在提交时检查值并在文本字段中显示错误?

用户界面

 Widget buildColumn() => Form(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: buildTitle(),
          ),
          SizedBox(
            height: 10,
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: buildDesription(),
          ),
          buildSubmit()
        ],
      ));

  Widget buildTitle() => StreamBuilder<String>(
      stream: manager.title,
      builder: (context, snapshot) {
        debugPrint(snapshot.toString());
        return TextField(
          onChanged: manager.inTitle.add,
          decoration: InputDecoration(
              labelText: 'Title',
              labelStyle: TextStyle(fontWeight: FontWeight.bold),
              errorText:
                  snapshot.error == null ? null : snapshot.error.toString()),
        );
      });

  Widget buildDesription() => StreamBuilder<String>(
      stream: manager.description,
      builder: (context, snapshot) {
        return TextField(
          onChanged: manager.inDescription.add,
          decoration: InputDecoration(
              labelText: 'Description',
              labelStyle: TextStyle(fontWeight: FontWeight.bold),
              errorText:
                  snapshot.error == null ? null : snapshot.error.toString()),
        );
      });

  Widget buildSubmit() => StreamBuilder<Object>(
      stream: manager.isFormValid,
      builder: (context, snapshot) {
        return ElevatedButton(
            onPressed: () {
              if (snapshot.hasData) {
                manager.submit();
                debugPrint("YEs");
              }
            },
            child: Text("SEND"));
      });
}

经理 在提交时不检查标题和描述是否为空

class CreatePostManager with Validation {
  final _repository = PostRepository();
  final _postsFetcher = PublishSubject<Post>();

  Stream<Post> get addPost => _postsFetcher.stream;

  final _title = BehaviorSubject<String>();

  Stream<String> get title => _title.stream.transform(validateTitle);

  Sink<String> get inTitle => _title.sink;

  final _description = BehaviorSubject<String>();

  Stream<String> get description =>
      _description.stream.transform(validateDescription);

  Sink<String> get inDescription => _description.sink;

  final _loading = BehaviorSubject<bool>();

  Stream<bool> get loading => _loading.stream.transform(checkLoading);

  Sink<bool> get inLoading => _loading.sink;

  Stream<bool> get isFormValid =>
      Rx.combineLatest2(title, description, (a, b) => true);

  Future submit() async {
    inLoading.add(true);
    String title = _title.value;
    String description = _description.value;
    Post itemModel = await _repository.addPost(title, description);
    _postsFetcher.sink.add(itemModel);
    inLoading.add(false);
    return itemModel;
  }

  dispose() {
    _postsFetcher.close();
  }
}

验证器

mixin Validation {

  final validateTitle =
      StreamTransformer<String, String>.fromHandlers(handleData: (value, sink) {
        if (value.isEmpty) {
          sink.addError("Title cannot be empty");
        }else {
          sink.add(value);
        }
  });

  final validateDescription =
  StreamTransformer<String, String>.fromHandlers(handleData: (value, sink) {
    if (value.isEmpty) {
      sink.addError("Description cannot be empty");
    }else {
      sink.add(value);
    }
  });

  final checkLoading =
  StreamTransformer<bool, bool>.fromHandlers(handleData: (value, sink) {
      sink.add(value);
  });
}

在提交时,我想检查文本字段是否为空并显示错误消息。目前它只在用户输入时显示。

stack overflow Flutter how to check if textfield is not empty on submit using rxdart
原文答案

答案:

作者头像

On submission, the TextField can be validated using its Controllers.

_textFieldController = TextEditingController();

...

TextField(
  controller: _textFieldController,
)

The TextField value can then be fetched using TextEditingController().value.text. Add a checker against this value on submission.

Another way of validating TextFields is with the use of the validator in TextFormField

TextFormField(
  // When a String is returned, it's displayed as an error on the TextFormField
  validator: (String? value) {
    return (value == null || value == '') ? 'Field should not be empty.' : null;
  },
)