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

Flutter自定义Widget传String参数遇Invalid constant value报错如何解决?

Flutter 「Invalid constant value」报错解决

错误原因

报错的核心原因是你为InputDecorator添加了const修饰符,const要求被修饰对象的所有属性值都必须是编译期可确定的常量,但你传入的title是运行时动态接收的实例参数,不满足常量要求,因此触发错误,和InputDecoration是不是Widget没有关联。
你之前尝试的widget.title取值、改用StatefulWidget等方案均不生效,是因为这些方案都没有解决const的常量校验要求,只要const修饰符存在,无论用什么方式读取动态的title参数都会触发报错。

修复方案

直接删除InputDecorator前面的const修饰符即可,修复后代码如下:

import 'package:flutter/material.dart';

class TemperatureInputDecoration extends StatelessWidget {
  const TemperatureInputDecoration({Key? key, required this.title})
    : super(key: key);
  final String title;

  @override
  Widget build(BuildContext context) {
    // 移除InputDecorator前的const修饰符
    return InputDecorator(
      decoration: InputDecoration(
        labelText: title,
        focusColor: Colors.orangeAccent,
      ),
    );
  }
}

补充优化说明

如果想保留常量性能优化,可以将固定不变的属性单独标记为const,比如上面代码里的focusColor是固定值,你可以单独给InputDecoration中常量部分做标记,不需要给整个InputDecorator加const。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:36:03