📝 表单组件详解

Flutter 提供了完整的表单系统,包括表单验证、表单控件等功能。本页面将详细介绍表单相关的组件。

📋 Form

Form 是一个表单容器,用于管理和验证多个表单字段。

渲染预览

请输入用户名
••••••

基本用法

final _formKey = GlobalKey();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        decoration: InputDecoration(
          labelText: '用户名',
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入用户名';
          }
          return null;
        },
      ),
      TextFormField(
        decoration: InputDecoration(
          labelText: '密码',
        ),
        obscureText: true,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入密码';
          }
          if (value.length < 6) {
            return '密码至少6位';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            print('表单验证通过');
          }
        },
        child: Text('提交'),
      ),
    ],
  ),
)

常用属性

属性 类型 说明
key GlobalKey 表单键,用于访问表单状态
child Widget 表单内容
autovalidateMode AutovalidateMode 自动验证模式
onChanged Function 表单值变化回调
💡 提示:使用 GlobalKey 可以访问表单状态,调用 validate() 方法进行验证,save() 方法保存数据。

✏️ TextFormField

TextFormField 是一个带有验证功能的文本输入框,通常与 Form 配合使用。

渲染预览

✉️ 请输入邮箱
🔒 ••••••••

✓ 提交时会验证邮箱格式

✓ 密码会被隐藏显示

基本用法

TextFormField(
  decoration: InputDecoration(
    labelText: '邮箱',
    prefixIcon: Icon(Icons.email),
    hintText: '请输入邮箱',
    border: OutlineInputBorder(),
  ),
  keyboardType: TextInputType.emailAddress,
  validator: (value) {
    if (value == null || value.isEmpty) {
      return '请输入邮箱';
    }
    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
      return '邮箱格式不正确';
    }
    return null;
  },
  onSaved: (value) {
    print('保存邮箱: $value');
  },
)

常用属性

属性 类型 说明
decoration InputDecoration 输入框装饰
keyboardType TextInputType 键盘类型
obscureText bool 是否隐藏文本(密码)
validator FormFieldValidator 验证函数
onSaved FormFieldSetter 保存回调
maxLines int 最大行数
💡 提示:TextFormField 提供了完整的表单验证功能,包括必填验证、格式验证等。

☑️ CheckboxListTile

CheckboxListTile 是一个带有复选框的列表项,常用于表单中的选项选择。

渲染预览

同意服务条款
我已阅读并同意服务条款
接收推送通知
获取最新消息和更新

基本用法

bool _agreeToTerms = false;

CheckboxListTile(
  title: Text('同意服务条款'),
  subtitle: Text('我已阅读并同意服务条款'),
  value: _agreeToTerms,
  onChanged: (bool? value) {
    setState(() {
      _agreeToTerms = value ?? false;
    });
  },
  controlAffinity: ListTileControlAffinity.leading,
  secondary: Icon(Icons.description),
)

常用属性

属性 类型 说明
value bool? 复选框值
onChanged Function 值变化回调
title Widget 标题
subtitle Widget 副标题
controlAffinity ControlAffinity 控件位置
secondary Widget 次要图标
💡 提示:CheckboxListTile 常用于用户协议、偏好设置等场景。

🔘 RadioListTile

RadioListTile 是一个带有单选按钮的列表项,用于单选场景。

渲染预览

其他

基本用法

enum Gender { male, female, other }
Gender? _selectedGender;

Column(
  children: [
    RadioListTile(
      title: Text('男'),
      value: Gender.male,
      groupValue: _selectedGender,
      onChanged: (Gender? value) {
        setState(() {
          _selectedGender = value;
        });
      },
    ),
    RadioListTile(
      title: Text('女'),
      value: Gender.female,
      groupValue: _selectedGender,
      onChanged: (Gender? value) {
        setState(() {
          _selectedGender = value;
        });
      },
    ),
    RadioListTile(
      title: Text('其他'),
      value: Gender.other,
      groupValue: _selectedGender,
      onChanged: (Gender? value) {
        setState(() {
          _selectedGender = value;
        });
      },
    ),
  ],
)

常用属性

属性 类型 说明
value T 选项值
groupValue T? 组值,确定哪个被选中
onChanged Function 值变化回调
title Widget 标题
subtitle Widget 副标题
secondary Widget 次要图标
💡 提示:RadioListTile 通过相同的 groupValue 来实现单选功能,同一组中的 RadioListTile 共享同一个 groupValue。