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,
    );
  }
}
相关推荐
LiWeNHuI6 小时前
Flutter开发:发布插件到Pub
flutter
这个杀手不太累6 小时前
Android ProcessLifecycleOwner
android·lifecycle
SRC_BLUE_177 小时前
NSSCTF - Web | 【第五空间 2021】pklovecloud
android·前端
衿璃8 小时前
Flutter应用架构设计的思考
前端·flutter
tq10869 小时前
学习Hilt注解
android
2501_915921439 小时前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
日日行不惧千万里9 小时前
2025最新仿默往 IM 即时通讯系统源码(PC + Web + iOS + Android)完整版发布!
android·ios
歪歪1009 小时前
React Native开发Android&IOS流程完整指南
android·开发语言·前端·react native·ios·前端框架
雪芽蓝域zzs9 小时前
uniapp 修改android包名
android·uni-app
QuantumLeap丶10 小时前
《Flutter全栈开发实战指南:从零到高级》- 04 - Widget核心概念与生命周期
flutter·xcode