4

我正在使用步进器小部件来收集用户信息并对其进行验证,我需要在每个步骤中调用一个 API,因此在每个继续按钮的步骤中验证每个字段......我正在使用表单状态和表单小部件,但问题是它验证步进器中所有步骤中的整个字段...我如何仅验证步进器中的单个步骤?我浏览了 Stepper.dart 中的 Stepper 和 State 类中的文档,但那里没有支持功能

以下是代码

class SubmitPayment extends StatefulWidget {


 SubmitPayment({Key key, this.identifier, this.amount, this.onResendPressed})
      : super(key: key);

  final String identifier;
  final String amount;
  final VoidCallback onResendPressed;

  @override
  State<StatefulWidget> createState() {
    return _SubmitPaymentState();
  }
}

class _SubmitPaymentState extends State<SubmitPayment> {
  final GlobalKey<FormState> _formKeyOtp = GlobalKey<FormState>();
  final FocusNode _otpFocusNode = FocusNode();
  final TextEditingController _otpController = TextEditingController();
  bool _isOTPRequired = false;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Form(
          key: _formKeyOtp,
          child: Column(children: <Widget>[
            Center(
                child: Padding(
                    padding:
                        EdgeInsets.symmetric(horizontal: 16.0, vertical: 5.0),
                    child: Text(
                      Translations.of(context).helpLabelOTP,
                      style: TextStyle(
                          color: Theme.of(context).primaryColor,
                          fontStyle: FontStyle.italic),
                    ))),
            CustomTextField(
              icon: Icons.vpn_key,
              focusNode: _otpFocusNode,
              hintText: Translations.of(context).otp,
              labelText: Translations.of(context).otp,
              controller: _otpController,
              keyboardType: TextInputType.number,
              hasError: _isOTPRequired,
              validator: (String t) => _validateOTP(t),
              maxLength: AppConstants.otpLength,
              obscureText: true,
            ),
            Center(
                child: ButtonBar(
              mainAxisSize: MainAxisSize.max,
              alignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  child: Text(Translations.of(context).resendOtpButton),
                  color: Colors.white,
                  textColor: Theme.of(context).primaryColor,
                  onPressed: widget.onResendPressed,
                ),
                RaisedButton(
                  child: Text(
                    Translations.of(context).payButton,
                  ),
                  onPressed: _doPullPayment,
                ),
              ],
            )),
          ])),
    );
  }

  String _validateOTP(String value) {
    if (value.isEmpty || value.length < AppConstants.otpLength) {
      setState(() => _isOTPRequired = true);
      return Translations.of(context).invalidOtp;
    }
    return "";
  }

  bool _validateOtpForm() {
    _formKeyOtp.currentState.save();
    return this._formKeyOtp.currentState.validate();
  }

  Future<void> _doPullPayment() async {
    setState(() {
      _isOTPRequired = false;
    });

    if (!_validateOtpForm()) return false;

    try {
      setState(() {
        _isOTPRequired = false;
      });
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              content: ListTile(
                leading: CircularProgressIndicator(),
                title: Text(Translations.of(context).processingPaymentDialog),
              ),
            ),
      );

      TransactionApi api =
          TransactionApi(httpDataSource, authenticator.sessionToken);
      String responseMessage = await api.doPullPayment(
          widget.identifier,
          widget.amount,
          _otpController.text,
          TransactionConstants.transactionCurrency);

      Navigator.of(context).pop();
      await showAlertDialog(
          context, Translations.of(context).pullPayment, '$responseMessage');
      Navigator.pop(context);
    } catch (exception) {
      await showAlertDialog(context, Translations.of(context).pullPayment,
          '${exception.message}');
      Navigator.of(context).pop();
    }
  }
4

2 回答 2

8

Form每个步骤使用单独的。使用GlobalKey<FormState>您可以索引的列表,_currentStep然后调用:validate()onStepContinue

List<GlobalKey<FormState>> _formKeys = [GlobalKey<FormState>(), GlobalKey<FormState>(), …];
…

Stepper(
  currentStep: _currentStep,
  onStepContinue: () {
    setState(() {
      if (_formKeys[_currentStep].currentState.validate()) {
        _currentStep++;
      }
    });
  },
  steps: 
  Step(
    child: Form(key: _formKeys[0], child: …),

显然你需要检查最后一步,save而不是validate最后:)

于 2018-08-13T11:31:17.017 回答
0

所以我解决了这个问题:

问题是如果我的逻辑有效,我将返回一个*empty string ("") * ,其中FormState的validate方法期望每个验证器方法,如果通过验证,则与 TextFormField 相关联返回null 。

我改变了以下

 String _validateOTP(String value) {
    if (value.isEmpty || value.length < AppConstants.otpLength) {
      setState(() => _isOTPRequired = true);
      return Translations.of(context).invalidOtp;
    }
    return "";
  }

  String _validateOTP(String value) {
if (value.isEmpty || value.length < AppConstants.otpLength) {
  setState(() => _isOTPRequired = true);
  return Translations.of(context).invalidOtp;
}
return null;

}

然后一切正常。

有关详细信息, 请参阅此链接“如果用户提供的信息有错误,则验证器函数必须返回包含错误消息的字符串。如果没有错误,则该函数不应返回任何内容。”

于 2018-08-28T18:31:15.197 回答