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

Flutter中传递Navigator函数为参数后按钮无响应,如何解决?

问题分析与解决

你的自定义按钮点击无响应的核心问题是没有正确执行传入的action函数:

在ButtonsFunction的ElevatedButton中,onPressed的写法是:

onPressed: () => action,

这里只是返回了action这个函数对象,并没有实际调用它,所以点击按钮时不会触发任何逻辑。

修正方案

方案一:直接调用action函数

把onPressed的回调改成执行action:

Widget ButtonsFunction(String text, IconData icon, Function action) {
  return Column(
    children: [
      ElevatedButton(
        // 修正为调用action函数
        onPressed: () => action(),
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.all(27.0),
          primary: Colors.grey[300],
          side: BorderSide(color: Colors.grey, width: 0.5),
          elevation: 0,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
        ),
        child: Icon(icon, color: Colors.indigo),
      ),
      SizedBox(height: 8.0),
      Text(text, style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  );
}

方案二:优化参数类型并直接赋值(更规范)

因为按钮的onPressed要求的是VoidCallback类型(无参数无返回值的函数),可以把参数类型明确为VoidCallback,然后直接赋值给onPressed:

// 将参数类型从Function改为VoidCallback
Widget ButtonsFunction(String text, IconData icon, VoidCallback action) {
  return Column(
    children: [
      ElevatedButton(
        // 直接赋值action,无需额外包裹
        onPressed: action,
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.all(27.0),
          primary: Colors.grey[300],
          side: BorderSide(color: Colors.grey, width: 0.5),
          elevation: 0,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
        ),
        child: Icon(icon, color: Colors.indigo),
      ),
      SizedBox(height: 8.0),
      Text(text, style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  );
}

验证调用

你的调用代码无需修改,保持原写法即可:

ButtonsFunction('Corporate', Icons.wallet,() => Navigator.pushNamed(context,'/CorporateMatters')),

修正后点击按钮就能正常触发页面导航了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:15:37