shadcn_ui-form

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Shadcn UI — Form

Shadcn UI — 表单

Instructions

使用说明

ShadForm
provides centralized form state, a single
Map<String, dynamic>
for all field values, and no need to manage individual controllers. Use a
GlobalKey<ShadFormState>
to call
saveAndValidate()
and read
value
. Give each form field an
id
; use
Shad*FormField
widgets (e.g.
ShadInputFormField
,
ShadCheckboxFormField
,
ShadSelectFormField
,
ShadDatePickerFormField
,
ShadTimePickerFormField
,
ShadRadioGroupFormField
) inside
ShadForm
.
ShadForm
提供集中式表单状态管理,所有字段值存储在单个
Map<String, dynamic>
中,无需管理单独的控制器。使用
GlobalKey<ShadFormState>
调用
saveAndValidate()
并读取
value
。为每个表单字段分配一个
id
;在
ShadForm
内部使用
Shad*FormField
组件(例如
ShadInputFormField
ShadCheckboxFormField
ShadSelectFormField
ShadDatePickerFormField
ShadTimePickerFormField
ShadRadioGroupFormField
)。

Basic form

基础表单

dart
final formKey = GlobalKey<ShadFormState>();

ShadForm(
  key: formKey,
  child: Column(
    children: [
      ShadInputFormField(
        id: 'username',
        label: const Text('Username'),
        placeholder: const Text('Enter your username'),
        description: const Text('This is your public display name.'),
        validator: (v) {
          if (v.length < 2) return 'Username must be at least 2 characters.';
          return null;
        },
      ),
      const SizedBox(height: 16),
      ShadButton(
        child: const Text('Submit'),
        onPressed: () {
          if (formKey.currentState!.saveAndValidate()) {
            print('value: ${formKey.currentState!.value}');
          } else {
            print('validation failed');
          }
        },
      ),
    ],
  ),
)
dart
final formKey = GlobalKey<ShadFormState>();

ShadForm(
  key: formKey,
  child: Column(
    children: [
      ShadInputFormField(
        id: 'username',
        label: const Text('Username'),
        placeholder: const Text('Enter your username'),
        description: const Text('This is your public display name.'),
        validator: (v) {
          if (v.length < 2) return 'Username must be at least 2 characters.';
          return null;
        },
      ),
      const SizedBox(height: 16),
      ShadButton(
        child: const Text('Submit'),
        onPressed: () {
          if (formKey.currentState!.saveAndValidate()) {
            print('value: ${formKey.currentState!.value}');
          } else {
            print('validation failed');
          }
        },
      ),
    ],
  ),
)

Submit and get value

提交并获取值

dart
ShadButton(
  child: const Text('Submit'),
  onPressed: () {
    final formState = formKey.currentState!;
    if (!formState.saveAndValidate()) return;
    print('Form value: ${formState.value}');
  },
),
dart
ShadButton(
  child: const Text('Submit'),
  onPressed: () {
    final formState = formKey.currentState!;
    if (!formState.saveAndValidate()) return;
    print('Form value: ${formState.value}');
  },
),

Initial value

初始值

Set default values with
initialValue
on
ShadForm
:
dart
ShadForm(
  initialValue: {
    'username': 'john_doe',
    'email': 'john_doe@example.com',
  },
  child: // form fields with matching ids
)
通过
ShadForm
initialValue
设置默认值:
dart
ShadForm(
  initialValue: {
    'username': 'john_doe',
    'email': 'john_doe@example.com',
  },
  child: // 对应id的表单字段
)

Set field or full value

设置单个字段或完整表单值

  • Single field:
    formKey.currentState!.setFieldValue('username', 'new_username');
    (use
    notifyField: false
    to skip updating the field UI).
  • Entire form:
    formKey.currentState!.setValue({...});
    (use
    notifyFields: false
    to skip updating fields).
  • 单个字段:
    formKey.currentState!.setFieldValue('username', 'new_username');
    (使用
    notifyField: false
    可跳过更新字段UI)。
  • 完整表单:
    formKey.currentState!.setValue({...});
    (使用
    notifyFields: false
    可跳过更新所有字段)。

Value transformers

值转换器

Use
fromValueTransformer
and
toValueTransformer
on form fields when the form value type differs from the field type (e.g. form stores string, field uses
DateTime
):
dart
ShadDatePickerFormField(
  id: 'date',
  fromValueTransformer: (value) => DateTime.tryParse(value ?? ''),
  toValueTransformer: (date) =>
      date == null ? null : DateFormat('yyyy-MM-dd').format(date),
  ...
)
当表单值类型与字段类型不同时(例如表单存储字符串,字段使用
DateTime
),可在表单字段上使用
fromValueTransformer
toValueTransformer
dart
ShadDatePickerFormField(
  id: 'date',
  fromValueTransformer: (value) => DateTime.tryParse(value ?? ''),
  toValueTransformer: (date) =>
      date == null ? null : DateFormat('yyyy-MM-dd').format(date),
  ...
)

Dot notation for nested values

嵌套值的点符号用法

Field IDs like
user.name
or
profile.settings.theme
produce nested maps in
formKey.currentState!.value
, e.g.
{'user': {'name': '...', 'email': '...'}}
. Provide
initialValue
as a nested map (not dot-notation keys). Customize separator with
fieldIdSeparator
(e.g.
'/'
); set
fieldIdSeparator: null
to disable nesting and keep flat keys.
类似
user.name
profile.settings.theme
的字段ID会在
formKey.currentState!.value
中生成嵌套映射,例如
{'user': {'name': '...', 'email': '...'}}
。需以嵌套映射形式提供
initialValue
(而非点符号键)。可通过
fieldIdSeparator
自定义分隔符(例如
'/'
);设置
fieldIdSeparator: null
可禁用嵌套,保持扁平键。

Additional resources

额外资源

  • Full details on initial value, setFieldValue/setValue, value transformers, and dot notation: reference.md
  • Form field examples: Checkbox, Switch, Input, Select, RadioGroup, DatePicker, TimePicker component docs/skills.
  • 关于初始值、setFieldValue/setValue、值转换器和点符号的详细说明:reference.md
  • 表单字段示例:Checkbox、Switch、Input、Select、RadioGroup、DatePicker、TimePicker组件文档/技能。