我目前正在学习Flutter-Validation,我从一个视频中复制并编写了这个代码,但即使条件为false,它也会自动通过验证。用户名和密码有两个验证,即使我没有写一个字符,验证也会得到True并传递到下一页。Validation函数写在开头“moveToHome”,它从下面的“Material-InkWell”调用。
它应该如何工作:如果表单为空,则应返回错误消息“Cannot be empty....”,
import 'package:fir_project/utils/routes.dart';
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
String name = "";
bool changeButton = false;
final _formKey = GlobalKey<FormState>();
moveToHome(BuildContext context) async {
if (_formKey.currentState!.validate()) {
setState(() {
changeButton = true;
});
await Future.delayed(Duration(seconds: 1));
await Navigator.pushNamed(context, Myroutes.homeRoute);
setState(() {
changeButton = false;
});
}
}
@override
Widget build(BuildContext context) {
return Material(
color: Colors.white,
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
Image.asset(
"assets/images/loginimg.png",
fit: BoxFit.cover,
),
SizedBox(
height: 20.0,
),
Text(
"Welcome $name",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 32.0),
child: Form(
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
hintText: "Enter Username",
labelText: "Username"),
validator: (value) {
if (value == null || value.isEmpty) {
return "Username Cannot be Empty";
}
return null;
},
onChanged: (value) {
name = value;
setState(() {});
},
),
TextFormField(
obscureText: true,
decoration: InputDecoration(
hintText: "Enter Password",
labelText: "Password"),
validator: (value) {
if (value == null || value.isEmpty) {
return "Password Cannot be Empty";
}
return null;
},
),
SizedBox(
height: 40.0,
),
Material(
color: Colors.teal,
borderRadius:
BorderRadius.circular(changeButton ? 40 : 8),
child: InkWell(
onTap: () {
moveToHome(context);
},
child: AnimatedContainer(
duration: Duration(seconds: 1),
height: 50,
width: changeButton ? 50 : 150,
alignment: Alignment.center,
child: changeButton
? Icon(
Icons.done,
color: Colors.white,
)
: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
),
)
],
),
),
)
],
),
),
));
}
}
2条答案
按热度按时间cnwbcb6i1#
您正在使用多表单微件
和
删除第二个
Form
小部件,它应该可以正常工作。更新代码:
fxnxkyjh2#
试试这样