Validation 如何为颤振表单添加验证?

Validation 如何为颤振表单添加验证?,validation,flutter,dart,Validation,Flutter,Dart,单击提交按钮时,如何向用户名密码添加验证 我为Widget\u buildUserNameTF()和Widget\u buildPasswordTF() 当我们点击Widget\u buildLoginBtn()时,验证必须在Widget\u buildUserNameTF()和Widget\u buildPasswordTF() 导入“包装:颤振/材料.省道”; 导入“包:flifter/services.dart”; 导入“package:flatter_app/utilities/cons

单击提交按钮时,如何向用户名密码添加验证

我为
Widget\u buildUserNameTF()
Widget\u buildPasswordTF()

当我们点击
Widget\u buildLoginBtn()
时,验证必须在
Widget\u buildUserNameTF()
Widget\u buildPasswordTF()

导入“包装:颤振/材料.省道”;
导入“包:flifter/services.dart”;
导入“package:flatter_app/utilities/constants.dart”;
类LoginPage扩展StatefulWidget{
@凌驾
_LoginPagentate createState()=>新建;
//状态createState(){
//返回_loginpagentate();
//  }
}
类_loginpagentate扩展状态{
最终脚手架键=新的GlobalKey();
final formKey=new GlobalKey();
//FormType _FormType=FormType.login;
字符串_userName=“”;
字符串_password=“”;
void validateAndSave(){
最终形式=formKey.currentState;
if(form.validate()){
form.save();
//performLogin();
}
}
void performLogin(){
最终蛇形杆=新蛇形杆(
内容:新文本(“用户名:$\u用户名,密码:$\u密码”),
);
scaffoldKey.currentState.showSnackBar(snackbar);
}
小部件_buildUserNameTF(){
返回列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
正文(
“用户名”,
风格:克拉贝尔风格,
),
尺寸箱(高度:10.0),
容器(
对齐:alignment.centerLeft,
装饰:kBoxDecorationStyle,
身高:60.0,
子项:TextFormField(
键盘类型:TextInputType.text,
key:formKey,
自动验证:_自动验证,
样式:TextStyle(
颜色:颜色,白色,
fontFamily:“OpenSans”,
),
装饰:输入装饰(
边框:InputBorder.none,
contentPadding:仅限边集(顶部:14.0),
前缀:图标(
Icons.account_圈,
颜色:颜色,白色,
),
hintText:'输入您的用户名',
hintStyle:kHintTextStyle,
),
验证器:(值){
返回值.isEmpty?“需要用户名”:null;
},
已保存:(值){
返回_userName=value;
},
),
),
],
);
}
Widget_buildPasswordTF(){
返回列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
正文(
“密码”,
风格:克拉贝尔风格,
),
尺寸箱(高度:10.0),
容器(
对齐:alignment.centerLeft,
装饰:kBoxDecorationStyle,
身高:60.0,
子项:TextFormField(
蒙昧文字:对,
key:formPassKey,
自动验证:_自动验证,
样式:TextStyle(
颜色:颜色,白色,
fontFamily:“OpenSans”,
),
装饰:输入装饰(
边框:InputBorder.none,
contentPadding:仅限边集(顶部:14.0),
前缀:图标(
Icons.lock,
颜色:颜色,白色,
),
hintText:'输入您的密码',
hintStyle:kHintTextStyle,
),
验证器:(字符串值){
if(value.isEmpty){
返回“需要密码”;
}
如果(值。长度<6){
返回“密码太短”;
}
返回null;
//返回值.isEmpty?“需要密码”:null;
//| | value.length<6?“密码太短”:null;
},
onSaved:(字符串值){
返回_password=value;
},
//验证器:(val)=>
//val.length<6?“密码太短”:null,
//onSaved:(val)=>_password=val,
),
),
],
);
}
小部件_buildLoginBtn(){
返回容器(
填充:边缘组。对称(垂直:25.0),
宽度:double.infinity,
孩子:表格(
孩子:升起按钮(
标高:5.0,
按下按钮:(
){
validateAndSave();
},
//=>打印(“按下登录按钮”),
填充:所有边缘设置(15.0),
形状:圆形矩形边框(
边界半径:边界半径。圆形(30.0),
),
颜色:颜色,白色,
子:文本(
“登录”,
样式:TextStyle(
颜色:颜色(0xFF527DAA),
字母间距:1.5,
字体大小:18.0,
fontWeight:fontWeight.bold,
fontFamily:“OpenSans”,
),
),
),
),
);
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:德雷吉翁(
值:SystemUIOverlyStyle.light,
儿童:手势检测器(
onTap:()=>FocusScope.of(context.unfocus(),
子:堆栈(
儿童:[
容器(
高度:双无限,
宽度:double.infinity,
装饰:盒子装饰(
梯度:线性梯度(
开始:Alignment.topCenter,
结束:对齐。底部中心,
颜色:[
颜色(0xFF73AEF5),
颜色(0xFF61A4F1),
颜色(0xFF478DE0),
颜色(0xFF398AE5),
],
停止:[0.1,0.4,0.7,0.9],
),
),
),
容器(
高度:双无限,
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/utilities/constants.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
//  State<StatefulWidget> createState() {
//    return _LoginPageState();
//  }
}

class _LoginPageState extends State<LoginPage> {
  final scaffoldKey = new GlobalKey<ScaffoldState>();
  final formKey = new GlobalKey<FormState>();

//  FormType _formType = FormType.login;
  String _userName = "";
  String _password = "";

  void validateAndSave() {
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();

//      performLogin();
    }
  }

      void performLogin() {
    final snackbar = new SnackBar(
      content: new Text("Username : $_userName, password : $_password"),
    );
    scaffoldKey.currentState.showSnackBar(snackbar);
  }


  Widget _buildUserNameTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Username',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 60.0,
          child: TextFormField(
            keyboardType: TextInputType.text,
            key: formKey,
            autovalidate: _autoValidate,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.account_circle,
                color: Colors.white,
              ),
              hintText: 'Enter your Username',
              hintStyle: kHintTextStyle,
            ),
            validator: (value) {
              return value.isEmpty ? 'Username is Required.' : null;
            },
            onSaved: (value) {
              return _userName = value;
            },
          ),
        ),
      ],
    );
  }

  Widget _buildPasswordTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Password',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 60.0,
          child: TextFormField(
            obscureText: true,
            key: formPassKey,
            autovalidate: _autoValidate,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.white,
              ),
              hintText: 'Enter your Password',
              hintStyle: kHintTextStyle,
            ),
            validator: (String value) {
              if (value.isEmpty) {
                return 'Password is Required.';
              }
              if (value.length < 6) {
                return 'Password too short.';
              }
              return null;
//              return value.isEmpty ? 'Password is Required.' : null;
//        || value.length < 6 ? 'Password too short' : null;
            },
            onSaved: (String value) {
              return _password = value;
            },
//           validator: (val) =>
//           val.length < 6 ? 'Password too short' : null,
//           onSaved: (val) => _password = val,
          ),
        ),
      ],
    );
  }


  Widget _buildLoginBtn() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 25.0),
      width: double.infinity,
      child: Form(
        child: RaisedButton(
          elevation: 5.0,
          onPressed: (
              ){
            validateAndSave();
          },
          //        => print('Login Button Pressed'),
          padding: EdgeInsets.all(15.0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30.0),
          ),
          color: Colors.white,
          child: Text(
            'LOGIN',
            style: TextStyle(
              color: Color(0xFF527DAA),
              letterSpacing: 1.5,
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              fontFamily: 'OpenSans',
            ),
          ),
        ),
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Stack(
            children: <Widget>[
              Container(
                height: double.infinity,
                width: double.infinity,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF73AEF5),
                      Color(0xFF61A4F1),
                      Color(0xFF478DE0),
                      Color(0xFF398AE5),
                    ],
                    stops: [0.1, 0.4, 0.7, 0.9],
                  ),
                ),
              ),
              Container(
                height: double.infinity,
                child: SingleChildScrollView(
                  physics: AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.symmetric(
                    horizontal: 40.0,
                    vertical: 120.0,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
//                    key: formKey,
                    children: <Widget>[
                      Text(
                        'Sign In',
                        style: TextStyle(
                          color: Colors.white,
                          fontFamily: 'OpenSans',
                          fontSize: 30.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 30.0),
                      _buildUserNameTF(),
                      SizedBox(
                        height: 30.0,
                      ),
                      _buildPasswordTF(),
                      _buildLoginBtn(),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
TextFormField(
            keyboardType: TextInputType.text,
            //key: formKey,
child: Form(
                key: formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'Sign In',
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; 

final kHintTextStyle = TextStyle(
  color: Colors.white54,
  fontFamily: 'OpenSans',
);

final kLabelStyle = TextStyle(
  color: Colors.white,
  fontWeight: FontWeight.bold,
  fontFamily: 'OpenSans',
);

final kBoxDecorationStyle = BoxDecoration(
  color: Color(0xFF6CA8F1),
  borderRadius: BorderRadius.circular(10.0),
  boxShadow: [
    BoxShadow(
      color: Colors.black12,
      blurRadius: 6.0,
      offset: Offset(0, 2),
    ),
  ],
);

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
//  State<StatefulWidget> createState() {
//    return _LoginPageState();
//  }
}

class _LoginPageState extends State<LoginPage> {
  final scaffoldKey = new GlobalKey<ScaffoldState>();
  final formKey = new GlobalKey<FormState>();

//  FormType _formType = FormType.login;
  String _userName = "";
  String _password = "";

  void validateAndSave() {
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();

//      performLogin();
    }
  }

  void performLogin() {
    final snackbar = new SnackBar(
      content: new Text("Username : $_userName, password : $_password"),
    );
    scaffoldKey.currentState.showSnackBar(snackbar);
  }

  Widget _buildUserNameTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Username',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Container(
          alignment: Alignment.centerLeft,
          //decoration: kBoxDecorationStyle,
          height: 60.0,
          child: TextFormField(
            keyboardType: TextInputType.text,
            //key: formKey,
            autovalidate: false,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.account_circle,
                color: Colors.white,
              ),
              hintText: 'Enter your Username',
              hintStyle: kHintTextStyle,
            ),
            validator: (value) {
              return value.isEmpty ? 'Username is Required.' : null;
            },
            onSaved: (value) {
              return _userName = value;
            },
          ),
        ),
      ],
    );
  }

  Widget _buildPasswordTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Password',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 60.0,
          child: TextFormField(
            obscureText: true,
            //key: formPassKey,
            autovalidate: false,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.white,
              ),
              hintText: 'Enter your Password',
              hintStyle: kHintTextStyle,
            ),
            validator: (String value) {
              if (value.isEmpty) {
                return 'Password is Required.';
              }
              if (value.length < 6) {
                return 'Password too short.';
              }
              return null;
//              return value.isEmpty ? 'Password is Required.' : null;
//        || value.length < 6 ? 'Password too short' : null;
            },
            onSaved: (String value) {
              return _password = value;
            },
//           validator: (val) =>
//           val.length < 6 ? 'Password too short' : null,
//           onSaved: (val) => _password = val,
          ),
        ),
      ],
    );
  }

  Widget _buildLoginBtn() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 25.0),
      width: double.infinity,
      child: Form(
        child: RaisedButton(
          elevation: 5.0,
          onPressed: () {
            validateAndSave();
          },
          //        => print('Login Button Pressed'),
          padding: EdgeInsets.all(15.0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30.0),
          ),
          color: Colors.white,
          child: Text(
            'LOGIN',
            style: TextStyle(
              color: Color(0xFF527DAA),
              letterSpacing: 1.5,
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              fontFamily: 'OpenSans',
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Stack(
            children: <Widget>[
              Container(
                height: double.infinity,
                width: double.infinity,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF73AEF5),
                      Color(0xFF61A4F1),
                      Color(0xFF478DE0),
                      Color(0xFF398AE5),
                    ],
                    stops: [0.1, 0.4, 0.7, 0.9],
                  ),
                ),
              ),
              Container(
                height: double.infinity,
                child: SingleChildScrollView(
                  physics: AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.symmetric(
                    horizontal: 40.0,
                    vertical: 120.0,
                  ),
                  child: Form(
                    key: formKey,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
//                    key: formKey,
                      children: <Widget>[
                        Text(
                          'Sign In',
                          style: TextStyle(
                            color: Colors.white,
                            fontFamily: 'OpenSans',
                            fontSize: 30.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 30.0),
                        _buildUserNameTF(),
                        SizedBox(
                          height: 30.0,
                        ),
                        _buildPasswordTF(),
                        _buildLoginBtn(),
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginPage(),
    );
  }
}