如何禁用提交按钮,直到字段没有正确填充在扑动



创建一个演示,设置提交按钮禁用,直到所有需要的TextField不是空的…

username和passwordTextField为空。那么提交按钮应该被禁用…

我已经完成了我的基本方式,但寻找先进的代码,使它可以不重复键入,像我有更多的文本字段

这是我的基本代码…

class _Stack4State extends State<Stack4> {
TextEditingController txtusername = TextEditingController();
TextEditingController txtpassword = TextEditingController();
bool isenable = false;
void checkfieldvalue(String username, String password) {
if (username.length > 3 && password.length > 6) {
setState(() {
isenable = true;
});
} else {
setState(() {
isenable = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
const SizedBox(
height: 20,
),
TextField(
controller: txtusername,
onChanged: (value) {
checkfieldvalue(txtusername.text, txtpassword.text);
},
),
SizedBox(
height: 20,
),
TextField(
controller: txtpassword,
onChanged: (value) {
checkfieldvalue(txtusername.text, txtpassword.text);
}),
const SizedBox(
height: 20,
),
ElevatedButton(
child: isenable ? Text('Register') : Text('Fill Data First'),
onPressed: () {
if (isenable == true) {
//code for submit
}
},
),
]),
),
),
);
}
}

首先定义这个变量:

final _formKey = GlobalKey<FormState>();

然后在你的小部件树中使用表单小部件,像这样:

SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Form(
key: _formKey,
child: Column(
children: [
const SizedBox(
height: 20,
),
TextField(
controller: txtusername,
onChanged: (value) {
checkfieldvalue(
txtusername.text, txtpassword.text);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'username is empty';
}else if (value.characters.length < 4){
return 'username is in wrong format';
}
return null;
},
),
SizedBox(
height: 20,
),
TextField(
controller: txtpassword,
onChanged: (value) {
checkfieldvalue(
txtusername.text, txtpassword.text);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'password is empty';
}else if (value.characters.length < 4){
return 'password is in wrong format';
}
return null;
},
),
const SizedBox(
height: 20,
),
],
)),
ElevatedButton(
child:
Text('Register'),
onPressed: _formKey.currentState != null &&
_formKey.currentState.validate()
? () {}
: null,
),
]),
),
),

,并使用其键来处理验证状态。您可以在validator中设置您的checkfieldvalue

你可以addListener

@override
void initState() {
super.initState();
txtusername.addListener(() {
checkfieldvalue(txtusername.text, txtpassword.text);
setState(() {});
});
txtpassword.addListener(() {
checkfieldvalue(txtusername.text, txtpassword.text);
setState(() {});
});
}

按钮
ElevatedButton(
child: isenable ? Text('Register') : Text('Fill Data First'),
onPressed: isenable
? () {
if (isenable == true) {
//code for submit
}
}
: null,
),

最新更新