给我undefinded中的错误验证器,但我在Flutter中使用了全局密钥,如何调试这个错误



在表单文本字段中使用验证器函数时发生未定义的命名参数错误

我使用了Global键,并希望验证我的表单文本字段,但当使用验证器函数编译器时,显示错误验证器未定义。我在Flutter中的代码如下:

import 'package:flutter/material.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
State<LoginScreen> createState() => _LoginScreen();
}
class _LoginScreen extends State<LoginScreen> {
//GlobalKey<FormState> formKey = GlobalKey();
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
//child: Text('This is bakwas container'),
appBar: AppBar(
title: const Text('Login'),
),
body: Form(
key: _formKey,
//validator:(){},
child: Center(
child: SizedBox(
width: MediaQuery.of(context).size.width * .7,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const TextField(
// validator: (value) {
//   if (value == null || value.isEmpty) {
//     return 'Please enter some text';
//   }
//   return null;
// },
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email', hintText: 'abc@example.com'),
),
//const SizedBox(height: 10,)
const TextField(
obscureText: true,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(labelText: 'Password'),
),
Container(
margin: const EdgeInsets.only(top: 10),
child: ElevatedButton(
onPressed: () {}, child: const Text('Press IT')))
],
),
),
),
));
}
}

要使用validator,需要将TextFiled替换为TextFormField

TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email', hintText: 'abc@example.com'),
),

如果您使用的是TextField,您的验证应该如下所示

class _MyHomeScreenState extends State<MyHomeScreen> {
final _userEmailController = TextEditingController();
void errorDialog(String title, String msg) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
title,
style: const TextStyle(fontWeight: FontWeight.bold),
),
content: Text(
msg,
textAlign: TextAlign.center,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
)
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Test"),),
body: Column(
children: [
TextField(
controller: _userEmailController,
decoration: const InputDecoration(
hintText: 'asdf@gmail.com',
),
),
ElevatedButton(
onPressed: () {
if (_userEmailController.text.isEmpty) {
errorDialog('Message', 'User email can not be empty!');
}
},
child: const Text(
'Login',
style: TextStyle(fontSize: 18),
),
),
],
),
);
}
}

最新更新