Flutter Form组件的基本使用

Form组件是一个可以包含一个或多个子元素的容器类组件。

TextFormField组件是Form中常用于做用户输入的组件。

GlobalKey的currentState调用validate(),会触发TextFormField组件的validator。然后再调用save(),会触发TextFormField组件的onSaved,这是用变量就会被赋值。

简单示例

dart 复制代码
class MyState extends State {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  late String userName;
  late String psd;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Form from = Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(labelText: "用户名"),
            onSaved: (newValue) {
              userName = newValue!;
            },
            validator: (value) {
              return value!.trim().isNotEmpty ? null : "用户名不能为空";
            },
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(labelText: "密码"),
            onSaved: (newValue) {
              psd = newValue!;
            },
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              TextButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState?.save();
                    print(userName);
                    print(psd);
                  }
                },
                child: Text("登录"),
              ),
              TextButton(
                onPressed: () {
                  _formKey.currentState?.reset();
                },
                child: Text("重置"),
              ),
            ],
          ),
        ],
      ),
    );

    return Scaffold(
      appBar: AppBar(title: Text("登录")),
      body: from,
    );
  }
}
相关推荐
恋猫de小郭5 小时前
2026,Android Compose 终于支持 Hot Reload 了,但是收费
android·前端·flutter
mygljx16 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
xinhuanjieyi17 小时前
ruoyimate导入sql\antflow\bpm_init_db.sql报错
android·数据库·sql
闲猫18 小时前
基于RABC的权限控制设计
android
星霜笔记21 小时前
GitMob — 手机端 GitHub 管理工具
android·kotlin·github·android jetpack
LiuYaoheng1 天前
问题记录:Android Studio Low memory
android·ide·android studio
独隅1 天前
Python 标准库 (Standard Library) 全面使用指南
android·开发语言·python
always_TT1 天前
strlen、strcpy、strcat等常用字符串函数
android
qqty12171 天前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_895521341 天前
MySQL中between and的基本用法
android·数据库·mysql