【问题标题】:TextFormField doesn't show errors on validationTextFormField 在验证时不显示错误
【发布时间】:2019-02-28 19:32:55
【问题描述】:

如果在 TextFormField 中通过验证发现错误消息,我该如何显示?

我正在使用 Stepper 类来处理用户的注册,当尝试使用 setState 实现基本验证时,当前正在验证的文本字段中不会显示错误消息

这是我的代码:

...
class _RegisterState extends State<RegisterPage> {
  static TextEditingController _inputController = TextEditingController();
  static bool _validate = false;
  static String _errorMessage;
  static int _currentStep = 0;
  static List<Step> _steps = [
    Step(
      // Title of the Step
      title: Text("Phone Number"),
      subtitle:
          Text('We need your 11 digit phone number to verify your identity!'),
      content: TextFormField(
        controller: _inputController,
        decoration: InputDecoration(
          icon: Icon(Icons.phone),
          labelText: '01XXXXXXXXX',
          errorText: _validate ? _errorMessage : null,
        ),
        maxLength: 11,
        keyboardType: TextInputType.number,
      ),
      state: _validate ? StepState.error : StepState.editing,
      isActive: true,
    ),
// Other steps ...
  ];

  @override
  Widget build(BuildContext context) {
    return CustomScaffold(
      title: 'Signup',
      body: Stepper(
        controlsBuilder: (BuildContext context,
            {VoidCallback onStepContinue, VoidCallback onStepCancel}) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              RaisedButton(
                onPressed: onStepContinue,
                color: Theme.of(context).accentColor,
                child: const Text('Continue'),
              ),
              FlatButton(
                onPressed: onStepCancel,
                child: const Text('Cancel'),
              ),
            ],
          );
        },
        currentStep: _currentStep,
        type: StepperType.vertical,
        steps: _steps,
        // Actions
        onStepTapped: (step) {
          setState(() {
            _currentStep = step;
          });
        },
        onStepCancel: () {
          setState(() {
            if (_currentStep > 0) {
              _currentStep = _currentStep - 1;
            } else {
              App.router.pop(context);
            }
          });
        },
        onStepContinue: () => _validator(),
      ),
    );
  }

  void _validator() {
    if (_currentStep == 0) {
      // Validate number
      if (_inputController.text.length != 11) {
        setState(() {
          _validate = true;
          _errorMessage = "Phone number must be 11 digits";
        });
      } else if (!_matchInt()) {
        setState(() {
          _validate = true;
          _errorMessage = "Phone number must be correct";
        });
      }
    }
  }

  _matchInt() {
    RegExp re = RegExp(
      r'(\d{11})',
      multiLine: false,
    );
    return re.hasMatch(_inputController.text);
  }

  void _continue(int currentStep) {
    setState(() {
      if (_currentStep < _steps.length - 1) {
        _currentStep = _currentStep + 1;
      } else {
        // TODO: Validate data and register a new user
        return null;
      }
    });
  }
}

Continue 按钮不会显示任何错误!

【问题讨论】:

    标签: flutter


    【解决方案1】:

    而不是在构建方法之外创建Step,它应该在您的构建方法内部。

    确保您在 StateFullWidget 内构建您的 TextField 小部件

    您也可以通过onChange查看您的文字

                      TextField(
                        controller: textEditingController,
                        onChanged: (String string){
                          print(string);
                          print(_validate);
                          if (string.length < 3) {
                            setState(() {
                              _validate = true;
                            });
                          }else {
                            setState(() {
                              _validate = false;
                            });
                          }
                        },
                        keyboardType: TextInputType.number,
                        decoration: new InputDecoration(hintText: 'Enter the number',
                            errorText: _validate ? 'here' : 'change'),
                      )
    

    【讨论】:

    • 你好,这很好用,谢谢......我只是想知道如何在将步骤移动到 build() 后更改 StepState ?
    • 你能简单解释一下你想做什么吗? 更具体
    • 验证通过后,当前步骤应标记为已完成,所以我不知道如何控制state 属性将其从StepState.editing 更改为StepState.complete
    • 这些Stepper 属性可能会对您有所帮助onStepContinueonStepCancelStepperonStepContinue: (){ if(_validate) { setState(() { _currentStep++; }); } }
    猜你喜欢
    • 2020-12-15
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多