我使用Form
添加了对文本字段的验证,它在其他屏幕上完美地工作,但在一个屏幕上它会导致问题,当我导航到该屏幕时,不单击按钮,它在文本字段上显示错误消息,我只是在initState()
中调用api方法。代码如下:
addproduct() {
_formKey.currentState!.validate()
? showDialog(
context: context,
builder: (BuildContext context) {
return LoginSucessDailog(
text: 'Your product is added successfully',
title: 'Product Added',
);
})
: print("error");}
@override
void initState() {
super.initState();
init();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.always,
child: Column(children: [
SizedBox10(),
Container(
width: MediaQuery.of(context).size.width * 0.9,
child: Align(
alignment: Alignment.topLeft,
child: customImageButton(
context,
"+",
() {},
MediaQuery.of(context).size.width * 0.3,
MediaQuery.of(context).size.height * 0.13)),
),
SizedBox20(),
// Product name
textformfieldCustomwithouticon(
context,
TextInputType.text,
MediaQuery.of(context).size.width * 0.9,
productname,
//onchange
(String value) {
setState(() {
productname.text = value;
});
},
//validator
(value) {
if (value == null || value.isEmpty) {
return 'This is required field';
}
return null;
},
// Add Product
Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.9,
height: MediaQuery.of(context).size.height * 0.07,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
HexColor("#7367f0")),
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
))),
onPressed: () {
addproduct();
},
child: Text('Add Product',
style: GoogleFonts.montserrat(fontSize: 20)),
),
),
),
SizedBox10(),
]),
)),
);
}
}
请帮助我哪里做错了。
改动很小
autovalidateMode: AutovalidateMode.always,
autovalidateMode: AutovalidateMode.disabled,
或不写autovalidateMode参数