flutter - Form表单验证

表单验证

flutter - Form表单验证_第1张图片

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: "姓名",
            ),
            // ignore: missing_return
            validator: (content) {
     
              if (content.length > 8) {
     
                return "姓名过长";
              } else if (content.length <= 0) {
     
                return "姓名过短";
              }
            },
            onSaved: (value) {
     
              userName = value;
            },
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: "密码",
            ),
            // ignore: missing_return
            validator: (content) {
     
              if (content.length < 8) {
     
                return "密码过短";
              }
            },
            onSaved: (value) {
     
              pwd = value;
            },
          ),
          RaisedButton(
            onPressed: save,
            child: Text("保存"),
          ),
          RaisedButton(
            onPressed: reset,
            child: Text("重置"),
          )
        ],
      ),
    );
  }
}

你可能感兴趣的:(Flutter,Form)