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,
    );
  }
}
相关推荐
阿华的代码王国1 天前
【Android】内外部存储的读写
android·内外存储的读写
inmK11 天前
蓝奏云官方版不好用?蓝云最后一版实测:轻量化 + 不限速(避更新坑) 蓝云、蓝奏云第三方安卓版、蓝云最后一版、蓝奏云无广告管理工具、安卓网盘轻量化 APP
android·工具·网盘工具
giaoho1 天前
Android 热点开发的相关api总结
android
农夫三拳_有点甜1 天前
Flutter Expanded 组件总结
flutter
火柴就是我1 天前
跟着官方demo 学flame 之 word 坐标系以及Camera的一些属性
flutter
咖啡の猫1 天前
Android开发-常用布局
android·gitee
新镜1 天前
【Flutter】drag_select_grid_view: ^0.6.2 使用
flutter
程序员老刘1 天前
Google突然“变脸“,2026年要给全球开发者上“紧箍咒“?
android·flutter·客户端
Tans51 天前
Androidx Lifecycle 源码阅读笔记
android·android jetpack·源码阅读
雨白1 天前
实现双向滑动的 ScalableImageView(下)
android