我刚开始学习flutter,已经做了一个表单应用程序,可以检查验证,如果验证器显示,则禁用“保存”按钮。但问题是,即使我为每个textFormField都将autovalidateMode参数设置为AutovalidateMode.onUserInteraction,所有验证器都会同时被触发。问题来了:
有问题的o/p:
所需o/p:
以下是最小可复制代码:
import 'package:flutter/material.dart';
class StudentInfoScreen extends StatefulWidget {
const StudentInfoScreen({super.key});
@override
State<StudentInfoScreen> createState() => _StudentInfoScreenState();
}
class _StudentInfoScreenState extends State<StudentInfoScreen> {
final formKey = GlobalKey<FormState>();
TextEditingController rNoController = TextEditingController();
TextEditingController nameController = TextEditingController();
TextEditingController stdController = TextEditingController();
String validator = 'Field cannot be empty';
bool isButtonDisabled = true;
@override
void dispose() {
rNoController.dispose();
nameController.dispose();
stdController.dispose();
super.dispose();
}
void validateInputs() {
if (formKey.currentState!.validate()) {
setState(() {
isButtonDisabled = false;
});
} else {
setState(() {
isButtonDisabled = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Details'),
elevation: 3,
automaticallyImplyLeading: false,
),
body: GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
child: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
child: Form(
key: formKey,
child: Column(
children: [
TextFormField(
controller: rNoController,
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (_) {
validateInputs();
},
validator: (value) {
if (value!.isNotEmpty) {
return null;
}
return validator;
},
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: TextFormField(
controller: nameController,
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (_) {
validateInputs();
},
validator: (value) {
if (value!.isNotEmpty) {
return null;
}
return validator;
},
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: TextFormField(
controller: stdController,
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (_) {
validateInputs();
},
validator: (value) {
if (value!.isNotEmpty) {
return null;
}
return validator;
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ElevatedButton(
onPressed: (isButtonDisabled) ? null : () {},
child: const Text('Save'),
),
],
)
],
),
),
),
),
),
);
}
}
我在模拟器上运行代码。
1条答案
按热度按时间gijlo24d1#
您正在
TextFormField
s中的onChanged
回调中触发validateInputs
。您的
validateInputs
函数调用formKey.currentState!.validate()
,该函数在每次击键时验证整个表单。从
onChanged
中删除这个逻辑,你应该没问题。