gpt4 book ai didi

flutter - 如何比较 2 TextFormField 中的值

转载 作者:行者123 更新时间:2023-12-03 03:03:31 25 4
gpt4 key购买 nike

我希望验证 2 TextFormField 内的值是否s 匹配。
我可以单独验证它们。
但是我怎么能捕获这两个值来通过比较来验证呢?

import 'package:flutter/material.dart';

class RegisterForm extends StatefulWidget {
@override
_RegisterFormState createState() => _RegisterFormState();
}

class _RegisterFormState extends State<RegisterForm> {

final _formKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Stack(
children: [
Container(
padding: EdgeInsets.all(20),
height: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
hintText: 'Password'
),
validator: (value) {
// I want to compare this value against the TextFormField below.
if(value.isEmpty){
return 'is empty';
}
return value;
},
),
TextFormField(
decoration: InputDecoration(
hintText: 'Confirm Password'
),
validator: (value) {
if(value.isEmpty){
return 'is empty';
}
return value;
},
),
RaisedButton(
onPressed: (){
if (_formKey.currentState.validate()) {
print('ok');
} else {
print('not ok');
}
},
),
],
),
)
],
),
);
}
}
一种可能的解决方案如下。
我可以将它们存储为 _RegisterFormState 中的值并在 validate 中检索它们 block 。但是有没有更清洁的方法来实现这一目标?
class _RegisterFormState extends State<RegisterForm> {


final _formKey = GlobalKey<FormState>();

String password;
String confirmPassword;

.....

TextFormField(
decoration: InputDecoration(
hintText: 'Password'
),
validator: (value) {
// I want to compare this value against the TextFormField below.
if(value.isEmpty){
setState(() {
password = value;
});
performValidation(password, confirmPassword); // some custom validation method
return 'is empty';
}
return value;
},
),

.....
}
P.S:如果有更好的方法通过状态管理工具来做到这一点,我正在使用 Provider .不是在寻找 Bloc 解决方案。

最佳答案

我已经执行了几个步骤来实现这一点。你可以引用它来实现你的目标。

  • 创建一个有状态的小部件并从那里返回一个 InputBox
  • 添加一个名为回调的属性并将其数据类型设置为
    值 setter 回调;
  • 将此回调分配给输入框的 onChanged 事件

  • onChanged: (text) {widget.callback(text);},


  • 在要使用输入框的类中使用自定义小部件
  • 在使用您的小部件时将回调传递给它
                InputWithLabel(

    callback: (value) {

    password = value;

    },
    ),
    InputWithLabel(

    callback: (value) {

    confirmPassword = value;

    },
    ),
  • 最后,我们必须比较这些值,
    您可以将 key 绑定(bind)到您的表单添加在 中使用它已保存 它的事件。您可以将其包装在 Button 的回调中
    if (InputValidation.validatePasswordandConfirm(password, cpassword)) {
    // your after form code
    }

  • 要让它实时比较,请在 setState(){} 中标记输入回调之一,并在您的自定义文本小部件中创建一个名为 compareTxt 的新属性;
    并在验证器上检查比较文本并返回错误消息
    validator: (text) {
    if (widget.comaparetext != text) {
    return 'Password does not match';
    }

    关于flutter - 如何比较 2 TextFormField 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64374205/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com