You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何在onPressed()方法中获取TagButton的文本值

解决Flutter自定义TagButton组件传递选中标签值的问题

步骤1:修改TagButton的回调参数类型

将原组件的无参回调改为带参数的类型,让组件能把标签名称和选中状态传递给父组件,同时简化内部状态切换逻辑:

class TagButton extends StatefulWidget {
  final String name;
  // 调整回调函数,传递标签名和当前选中状态
  final void Function(String tagName, bool isSelected)? onPressed;

  TagButton({super.key, required this.name, required this.onPressed});

  @override
  State<TagButton> createState() => _TagButtonState();
}

class _TagButtonState extends State<TagButton> {
  bool chosenTag = false;

  @override
  Widget build(BuildContext context) {
    return TextButton(
        style: ButtonStyle(
            backgroundColor: WidgetStatePropertyAll(
                chosenTag ? CustomColors.secondaryColor : Colors.grey)),
        onPressed: () {
          setState(() {
            // 简化状态切换逻辑
            chosenTag = !chosenTag;
          });
          // 触发父组件回调,传递关键信息
          widget.onPressed?.call(widget.name, chosenTag);
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.tag,
              color: Colors.white,
            ),
            Text(widget.name, style: TextStyle(color: Colors.white)),
          ],
        ));
  }
}

步骤2:在help_form.dart中维护选中标签列表并处理回调

在父组件中创建列表保存选中标签,通过回调实时更新列表内容:

// 在help_form.dart的State类中定义选中标签列表
List<String> selectedTags = [];

// 使用TagButton的代码
TagButton(
    name: "Electricity",
    onPressed: (tagName, isSelected) {
      if (isSelected) {
        // 避免重复添加
        if (!selectedTags.contains(tagName)) {
          selectedTags.add(tagName);
        }
      } else {
        selectedTags.remove(tagName);
      }
      // 后续可直接使用selectedTags列表提交到数据库
      print("当前选中标签:$selectedTags");
    }),
TagButton(
    name: "DIY",
    onPressed: (tagName, isSelected) {
      if (isSelected) {
        if (!selectedTags.contains(tagName)) {
          selectedTags.add(tagName);
        }
      } else {
        selectedTags.remove(tagName);
      }
      print("当前选中标签:$selectedTags");
    }),
TagButton(
    name: "Programming",
    onPressed: (tagName, isSelected) {
      if (isSelected) {
        if (!selectedTags.contains(tagName)) {
          selectedTags.add(tagName);
        }
      } else {
        selectedTags.remove(tagName);
      }
      print("当前选中标签:$selectedTags");
    }),

补充说明

  • 若需要更严谨的状态管理,可结合Provider、Riverpod等状态管理工具,统一维护选中标签状态,适合标签数量较多或跨组件使用的场景。
  • 提交数据库时,直接将selectedTags序列化为对应格式(如JSON)即可。

内容的提问来源于stack exchange,提问作者Zorgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:57:10