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

Flutter自定义BotonEnviar Widget传递函数未执行的解决方法

问题:Flutter自定义按钮点击后未执行传入的回调函数

我创建了BotonEnviar这个StatelessWidget,用于触发自定义函数,但点击按钮后,只有按钮内部的print("pulsado enviar visto en el widget del boton");有输出,传入的回调里的代码(包括PublicarTema().publicarTema的调用)完全没执行。

相关代码

BotonEnviar 实现

class BotonEnviar extends StatelessWidget {
   BotonEnviar({Key? key, required this.funcion, required this.texto}) : super(key: key);

  final void Function() funcion;
  final String texto;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      width: 180,
      child: ElevatedButton(
        onPressed: () {
          print("pulsado enviar visto en el widget del boton");
          this.funcion;
        },
        child: Text(
          '${this.texto}' ,
          style: TextStyle(color: Colors.white,fontSize: 18),
        ),
      ),
    );
  }
}

BotonEnviar 使用代码

...
SizedBox(
  height: 15,
),
BotonEnviar(funcion: () {
  print("pulsado boton");
  PublicarTema().publicarTema(temaController.text);
}, texto: 'Enviar',),
...

PublicarTema 类实现

class PublicarTema {
  publicarTema(String titulo){
    //accion al pulsar boton ENVIAR
    print("itulo recibido ${titulo}");
  }
}

问题原因与修复

问题出在BotonEnviar的onPressed回调里:你只是引用了this.funcion这个函数变量,但没有调用它。

只需要把this.funcion;改成this.funcion();,加上括号执行函数即可:

onPressed: () {
  print("pulsado enviar visto en el widget del boton");
  this.funcion(); // 执行传入的回调函数
},

另外补充一个小细节:PublicarTema里的打印语句有笔误,"itulo recibido"少了字母t,建议修正为"titulo recibido",避免后续查看日志时混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 01:17:38