要在AlertDialog中使用TextFormField进行验证,您可以使用Form和FormState来实现验证。以下是一个示例代码,演示了如何使用TextFormField在AlertDialog中进行验证。
import 'package:flutter/material.dart';
class MyAlertDialog extends StatefulWidget {
@override
_MyAlertDialogState createState() => _MyAlertDialogState();
}
class _MyAlertDialogState extends State {
final _formKey = GlobalKey(); // 创建一个全局的FormKey
String _name = '';
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('My Dialog'),
content: Form(
key: _formKey, // 将FormKey与Form绑定
child: TextFormField(
validator: (value) {
if (value.isEmpty) {
return '请输入名称';
}
return null;
},
onSaved: (value) {
_name = value;
},
decoration: InputDecoration(
labelText: '名称',
),
),
),
actions: [
FlatButton(
child: Text('取消'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('确认'),
onPressed: () {
if (_formKey.currentState.validate()) { // 验证表单
_formKey.currentState.save(); // 保存表单数据
// 在此处执行确认操作
print('名称: $_name');
Navigator.of(context).pop();
}
},
),
],
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('AlertDialog with TextFormField'),
),
body: Center(
child: RaisedButton(
child: Text('打开对话框'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return MyAlertDialog();
},
);
},
),
),
),
));
}
在上述示例中,我们使用了一个全局的FormKey来与Form小部件进行绑定。然后,在TextFormField中添加了validator属性来进行验证。在确认按钮的onPressed回调中,我们首先使用_formKey.currentState.validate()来验证表单。如果验证通过,我们再使用_formKey.currentState.save()来保存表单数据,并执行确认操作。
当用户点击确认按钮时,表单数据将会被保存,并且对话框将会关闭。如果用户没有输入名称,验证器将会返回一个错误消息并显示在对话框中。