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

Flutter如何向对话框传递参数并展示?现有代码报错该如何解决?

问题原因
  • 核心语法错误为你给ListBody的children属性添加了const修饰符,const要求修饰的对象必须是编译期常量,但数组内的Text(message)使用了函数运行时才传入的动态参数message,不符合Dart语法规则。
  • 你看到的三条文本相关提示是IDE在Text组件语法非法时带出的官方文档说明,并非直接报错,修复语法问题后提示会自动消失。
修复方案

删除ListBody的children属性前的const关键字即可,修复后完整代码如下:

Future _showMyDialog(String message) async {
  return showDialog(
    context: context,
    barrierDismissible: true, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('Warning'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(message),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('OK'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
补充说明

其余位置的const修饰(比如Text('Warning')、Text('OK'))可以保留,因为这些Text的内容是编译期就确定的固定字符串,符合const常量要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 01:12:01