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,
    );
  }
}
相关推荐
xiangxiongfly9158 分钟前
Android GsonFactory总结
android·gson·gsonfactory
WythePlus2 小时前
Android 14 SELinux策略深度解析
android·安全策略·selinux策略
俩个逗号。。5 小时前
Kotlin flow 详解
android·开发语言·kotlin
橙光成长7 小时前
android-ad-cleaner:android免 Root 批量关闭系统开屏与营销推送
android·1024程序员节
深圳雨林凯AI7 小时前
图案裂变的底色衰减:alpha通道、亮度对比与白墨分色的量化拆解
android
mmsx8 小时前
Android 模块化收口:能力组合框架、手写 LifecycleOwner 与热修复共存
android
恋猫de小郭10 小时前
Flutter 可以更直接地调用原生 API 了,Dart Direct Native Interop
android·前端·flutter
2501_9160088910 小时前
iPhone 设备信息查看,用 KeyMob 看型号、序列号、电池健康和 UDID
android·ios·小程序·https·uni-app·iphone·webview
码点11 小时前
二.Flutter 速成第二课:核心概念与第一个自定义页面
flutter
好的佩奇20 小时前
蓝牙之通信架构
android·flutter·蓝牙