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

Flutter如何传递按钮ID至函数并比较两次点击的ID是否相等

解决方法

要实现点击两个按钮后比较ID是否匹配,你需要做这几步:

  1. 在State类中添加状态变量
    用来存储两次点击的按钮ID,初始设为可空类型:

    int? _firstClickedId;
    int? _secondClickedId;
    
  2. 修改函数接收按钮ID参数并处理逻辑
    更新_unionKeyFunction,让它接收按钮ID,然后区分第一次和第二次点击:

    void _unionKeyFunction(int buttonId) {
      if (_firstClickedId == null) {
        // 第一次点击,记录ID
        _firstClickedId = buttonId;
      } else {
        // 第二次点击,执行比较
        _secondClickedId = buttonId;
        if (_firstClickedId == _secondClickedId) {
          print("Equal");
        } else {
          print("Not equal");
        }
        // 比较完成后重置状态,支持下一轮判断
        _firstClickedId = null;
        _secondClickedId = null;
      }
    }
    
  3. 修改按钮的点击回调,传递对应ID
    把每个按钮的onPressed改成传递对应ID到函数里,注意你原来的回调写法(() => {keyButton1, _unionKeyFunction()})是无效的,那个大括号只是创建了一个无意义的集合,正确写法如下:

    ElevatedButton(
      onPressed: () => _unionKeyFunction(keyButton1),
      child: const Text("Button 1")
    ),
    ElevatedButton(
      onPressed: () => _unionKeyFunction(keyButton2),
      child: const Text("Button 2")
    ),
    ElevatedButton(
      onPressed: () => _unionKeyFunction(keyButton3),
      child: const Text("Button 3")
    ),
    ElevatedButton(
      onPressed: () => _unionKeyFunction(keyButton4),
      child: const Text("Button 4")
    ),
    

逻辑说明

  • 第一次点击按钮时,函数会把当前按钮ID存在_firstClickedId里;
  • 第二次点击时,把ID存在_secondClickedId,然后和第一次的ID比较,输出结果;
  • 比较完成后重置两个变量,这样可以继续进行下一组两次点击的判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:55:32