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,
    );
  }
}
相关推荐
tangweiguo03051987几秒前
Flutter GetX 全面指南:状态管理、路由与依赖注入的最佳实践
flutter
Jerry说前后端4 分钟前
Android 移动端 UI 设计:前端常用设计原则总结
android·前端·ui
bytebeats5 分钟前
Jetpack Compose 1.9: 核心新特性简介
android·android jetpack
Icey_World8 分钟前
Mysql笔记-错误条件\处理程序
android
大王派来巡山的小旋风1 小时前
Kotlin基本用法之集合(一)
android·程序员·kotlin
用户2018792831671 小时前
智能广播系统(RemoteCallbackList)的诞生
android
用户2018792831672 小时前
Binder 同应用内(本地)通信是否存在 1MB 大小限制?
android
一条上岸小咸鱼3 小时前
Kotlin 基本数据类型(四):String
android·前端·kotlin
Onion_993 小时前
学习下Github上的Android CICD吧
android·github