美文网首页
flutter 表单组件

flutter 表单组件

作者: 喜剧收尾_XWX | 来源:发表于2020-07-27 19:25 被阅读0次
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _loginPageState createState() => _loginPageState();
}

class _loginPageState extends State<MyApp> {
  //全局key用来获取form表单
  GlobalKey<FormState> loginKey = GlobalKey<FormState>();

  //用户名
  String userName;

  //密码
  String password;

  void login() {
    //获取当前的状态
    var loginForm = loginKey.currentState;

    //验证form表单
    if (loginForm.validate()) {
      loginForm.save();
      print('username' + userName + 'password' + password);
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: '表单组件',
      home: Scaffold(
        appBar: AppBar(
          title: Text('表单组件'),
        ),
        body: Column(
          children: <Widget>[
            Container(
              //添加内边距
              padding: const EdgeInsets.all(16.0),
              //添加from表单
              child: Form(
                key: loginKey,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      //装饰器
                      decoration: InputDecoration(
                          //提示文本
                          labelText: '请输入用户名'),
                      //接收输入值
                      onSaved: (value) {
                        userName = value;
                      },
                      onFieldSubmitted: (value) {},
                    ),
                    TextFormField(
                      decoration: InputDecoration(labelText: '请输入密码'),
                      onSaved: (val) {
                        password = val;
                      },

                      //是否密文输入
                      obscureText: true,
                      //验证表单方法
                      validator: (val) {
                        return val.length < 6 ? '密码长度不够6位' : null;
                      },
                    )
                  ],
                ),
              ),
            ),

            //限定容器大小
            SizedBox(
              width: 340.0,
              height: 42,
              //添加登录按钮
              child: RaisedButton(
                onPressed: login,
                child: Text(
                  '登录',
                  style: TextStyle(fontSize: 18.0),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

相关文章

网友评论

      本文标题:flutter 表单组件

      本文链接:https://www.haomeiwen.com/subject/xidtrktx.html