1. import 'package:flutter/material.dart';
    2. class FormTestRoute extends StatefulWidget {
    3. @override
    4. _FormTestRouteState createState() => new _FormTestRouteState();
    5. }
    6. class _FormTestRouteState extends State<FormTestRoute> {
    7. TextEditingController _unameController = new TextEditingController();
    8. TextEditingController _pwdController = new TextEditingController();
    9. GlobalKey _formKey = new GlobalKey<FormState>();
    10. var obscureBoolPwd = true;
    11. @override
    12. Widget build(BuildContext context) {
    13. return Scaffold(
    14. appBar: AppBar(),
    15. body: Padding(
    16. padding: const EdgeInsets.symmetric(vertical: 32.0, horizontal: 24.0),
    17. child: Form(
    18. key: _formKey, //设置globalKey,用于后面获取FormState
    19. autovalidate: false, //开启自动校验
    20. child: Column(
    21. children: <Widget>[
    22. TextFormField(
    23. autofocus: false,
    24. controller: _unameController,
    25. decoration: InputDecoration(
    26. labelText: "用户名",
    27. hintText: "用户名或邮箱",
    28. icon: Icon(Icons.person)),
    29. // 校验用户名
    30. validator: (v) {
    31. return v.trim().length > 0 ? null : "用户名不能为空";
    32. }),
    33. TextFormField(
    34. controller: _pwdController,
    35. decoration: InputDecoration(
    36. labelText: "密码",
    37. hintText: "您的登录密码",
    38. icon: Icon(Icons.lock),
    39. suffixIcon: IconButton(
    40. icon: Icon(
    41. obscureBoolPwd
    42. ? Icons.visibility_off
    43. : Icons.visibility,
    44. ),
    45. onPressed: () {
    46. //更新状态控制密码显示或隐藏
    47. setState(() {
    48. obscureBoolPwd = !obscureBoolPwd;
    49. });
    50. },
    51. )),
    52. obscureText: obscureBoolPwd,
    53. //校验密码
    54. validator: (v) {
    55. return v.trim().length > 5 ? null : "密码不能少于6位";
    56. }),
    57. // 登录按钮
    58. Padding(
    59. padding: const EdgeInsets.only(top: 28.0),
    60. child: Row(
    61. children: <Widget>[
    62. Expanded(
    63. child: RaisedButton(
    64. padding: EdgeInsets.all(15.0),
    65. child: Text("登录"),
    66. color: Theme.of(context).primaryColor,
    67. textColor: Colors.white,
    68. onPressed: () {
    69. if ((_formKey.currentState as FormState).validate()) {
    70. //验证通过提交数据
    71. }
    72. },
    73. ),
    74. ),
    75. ],
    76. ),
    77. )
    78. ],
    79. ),
    80. ),
    81. ),
    82. );
    83. }
    84. }

    image.png