TextFormField
是 Flutter 框架中的一个组件,用于创建带有文本输入功能的表单字段。当你在使用 TextFormField
进行验证时,如果错误信息没有显示出来,可能是以下几个原因造成的:
validator
属性或者 errorText
属性。以下是一个简单的 TextFormField
示例,包含验证逻辑和错误显示:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('TextFormField Validation')),
body: MyForm(),
),
);
}
}
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
String _name = '';
String? _validateName(String? value) {
if (value == null || value.isEmpty) {
return 'Name is required';
}
return null;
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: _validateName,
onSaved: (String? value) {
_name = value!;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
// Handle form submission
}
},
child: Text('Submit'),
),
],
),
);
}
}
null
。Form
组件包裹所有的表单字段,并为其指定一个全局键(GlobalKey
),这样就可以在整个表单范围内访问表单的状态。通过上述代码和解释,你应该能够解决 TextFormField
在验证时不显示错误的问题。如果问题仍然存在,请检查是否有其他代码逻辑影响了表单的状态更新或错误信息的显示。
领取专属 10元无门槛券
手把手带您无忧上云