表单验证
class FormWidget extends StatefulWidget {
@override
_FormWidgetState createState() => _FormWidgetState();
}
class _FormWidgetState extends State<FormWidget> {
GlobalKey<FormState> formGlobalKey = GlobalKey<FormState>();
String userName;
String pwd;
void save() {
var form = formGlobalKey.currentState;
if (form.validate()) {
form.save();
print(userName + "," + pwd);
}
}
void reset() {
var form = formGlobalKey.currentState;
form.reset();
}
@override
Widget build(BuildContext context) {
return Form(
key: formGlobalKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(
labelText: "姓名",
),
validator: (content) {
if (content.length > 8) {
return "姓名过长";
} else if (content.length <= 0) {
return "姓名过短";
}
},
onSaved: (value) {
userName = value;
},
),
TextFormField(
obscureText: true,
decoration: InputDecoration(
labelText: "密码",
),
validator: (content) {
if (content.length < 8) {
return "密码过短";
}
},
onSaved: (value) {
pwd = value;
},
),
RaisedButton(
onPressed: save,
child: Text("保存"),
),
RaisedButton(
onPressed: reset,
child: Text("重置"),
)
],
),
);
}
}