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,
    );
  }
}
相关推荐
松仔log1 小时前
JetPack——Paging3+Room
android·java·zoom
Lei活在当下6 小时前
先用起来,再理解,关于协程Coroutine应该知道的事
android·java·jvm
kernelcraft6 小时前
cuongpmyoutube-dl-android:多平台视频下载的Android客户端
android·其他
佚泽7 小时前
Android Studio 如何配置gradle
android·ide·android studio
苏坡余10 小时前
Android Pixel7 13.0 HAL Service 调试
android
木子雨廷11 小时前
Flutter 桌面小组件开发
前端·flutter
私人珍藏库11 小时前
【Android】AI视频剪辑-Ai剪辑视频 免费无广告
android·app·工具·软件·多功能
乐活青年11 小时前
新版Android Studio不显示gradle task list 问题
android·ide·android studio
alphageek811 小时前
JeffMony开源的VideoDownloader,Android平台视频下载SDK
android·其他·开源·音视频
亚空间仓鼠12 小时前
Docker容器化高可用架构部署方案(十五)
android·redis·docker·架构·sentinel