創建一個用于設定提交按鈕禁用直到所有都需要的演示TextField
不為空...
用戶名和密碼TextField
為空..然后提交按鈕應該被禁用...
我已經完成了我的基本方法,但正在尋找高級代碼,這樣它就不會重復輸入,就像我有更多的文本欄位一樣
這是我的基本代碼...
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
}
},
),
]),
),
),
);
}
}
uj5u.com熱心網友回復:
你可以添加監聽器
@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,
),
uj5u.com熱心網友回復:
首先定義這個變數:
final _formKey = GlobalKey<FormState>();
然后像這樣在小部件樹中使用 Form 小部件:
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,
),
]),
),
),
并使用其密鑰來處理驗證狀態。你可以設定你checkfieldvalue
的validator
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535054.html
標籤:扑镖