【问题标题】:How to add validation for flutter form?如何为颤振表单添加验证?
【发布时间】:2020-04-09 08:18:15
【问题描述】:

当我们点击提交按钮时,如何向用户名密码添加验证。

我为 Widget _buildUserNameTF()Widget _buildPasswordTF() 创建了 2 个不同的类

当我们点击Widget _buildLoginBtn() 时,必须在Widget _buildUserNameTF()Widget _buildPasswordTF() 上完成验证

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(),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

我也尝试了以下方法,但输出接口是这样运行的

【问题讨论】:

标签: validation flutter dart


【解决方案1】:

您可以在下面复制粘贴运行完整代码
第1步:您可以在TextFormField中删除formKey

TextFormField(
            keyboardType: TextInputType.text,
            //key: formKey,

第 2 步:用Form 包裹Column 并提供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(),
    );
  }
}

【讨论】:

  • 如何对刚才评论的样式(//style: kLabelStyle)和(//decoration: kBoxDecorationStyle,)做同样的事情
  • 我没有这些变量。重现您的问题。我必须注释掉,在你的情况下,你可以取消注释
  • 这是我的样式代码``` import 'package:flutter/material.dart';最终 kHintTextStyle = TextStyle( 颜色: Colors.white54, fontFamily: 'OpenSans', ); final kLabelStyle = TextStyle(颜色:Colors.white,fontWeight:FontWeight.bold,fontFamily:'OpenSans',);最终 kBoxDecorationStyle = BoxDecoration(颜色:颜色(0xFF6CA8F1),borderRadius:BorderRadius.circular(10.0),boxShadow:[ BoxShadow(颜色:Colors.black12,blurRadius:6.0,偏移量:偏移量(0, 2),),],) ;```
  • 我尝试了编辑后的代码,但输出如下(我编辑了上面的问题并添加了它生成的界面)
猜你喜欢
  • 2020-05-28
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2020-03-07
  • 2020-01-09
  • 2019-02-17
  • 2020-01-19
  • 1970-01-01
相关资源
最近更新 更多