如何为flutter_form_builder的FormBuilderTextField添加标签输入功能
基于 flutter_form_builder 实现 StackOverflow 风格标签输入
实现逻辑
完全对齐StackOverflow标签输入的交互细节,基于 flutter_form_builder 官方提供的自定义字段能力实现,不脱离插件原生的值流转体系,核心交互对齐点:
- 支持通过逗号、空格、回车键触发标签转换,输入分隔符时自动将已录入的纯文本片段转为独立可视化标签
- 标签采用浅蓝填充背景、蓝色文本的样式,每个标签内置删除按钮,点击即可移除
- 表单提交时自动输出标签数组格式,不需要手动从带分隔符的字符串中拆分内容
- 完全兼容 FormBuilder 的校验、初始值设置、值监听等原生能力,可直接挂载到现有FormBuilder表单中使用
可直接复用的示例代码
// 标签列表状态存储 final List<String> _tags = []; // 控制标签输入框内容的控制器 final TextEditingController _tagInputController = TextEditingController(); FormBuilderField<List<String>>( name: 'sampleAttribute', // 替换为业务实际使用的字段标识 initialValue: const [], validator: (value) { if (value == null || value.isEmpty) { return '请至少录入1个标签'; } return null; }, builder: (FormFieldState<List<String>> field) { return InputDecorator( decoration: InputDecoration( labelText: " Separate items, with, commas", labelStyle: const TextStyle( fontSize: 12.0, fontStyle: FontStyle.italic, ), errorText: field.errorText, contentPadding: const EdgeInsets.all(8), ), // 流式布局自动换行展示标签与输入框 child: Wrap( spacing: 8, runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [ // 渲染已生成的标签 ..._tags.map((tag) => Chip( label: Text( tag, style: const TextStyle(color: Colors.blueAccent), ), backgroundColor: Colors.blueAccent.withOpacity(0.1), deleteIcon: const Icon(Icons.close, size: 16), onDeleted: () { _tags.remove(tag); field.didChange(List.from(_tags)); }, )), // 嵌入原生输入框,和标签区无缝融合 SizedBox( width: 200, child: TextField( controller: _tagInputController, decoration: const InputDecoration( border: InputBorder.none, isDense: true, hintText: '输入标签...', ), onSubmitted: (value) { // 回车触发标签生成 final tagContent = value.trim(); if (tagContent.isNotEmpty && !_tags.contains(tagContent)) { _tags.add(tagContent); _tagInputController.clear(); field.didChange(List.from(_tags)); } }, onChanged: (value) { // 检测逗号分隔触发标签生成 if (value.endsWith(',')) { final tagContent = value.replaceAll(',', '').trim(); if (tagContent.isNotEmpty && !_tags.contains(tagContent)) { _tags.add(tagContent); _tagInputController.clear(); field.didChange(List.from(_tags)); } } }, ), ) ], ), ); }, )
体验优化调整
- 通过Wrap组件的自动换行能力,实现标签过多时自动适配容器宽度换行展示,不会出现内容溢出
- 可扩展添加标签长度限制、敏感词校验、重复标签提示逻辑,完全和FormBuilder的校验体系打通
- 提交表单时可直接通过formKey读取对应字段的标签数组值,不需要额外做文本格式转换
内容的提问来源于stack exchange,提问作者Mark Gavagan
相关产品推荐
相关产品推荐

