Flutter向常量参数传入类管理的字符串报无效常量错误如何解决
错误原因
你代码中的InputDecoration被const修饰符标记,要求其所有参数值都必须是编译期常量,但当前实现存在两个问题:
- 自定义的
Texts类语法不符合Dart规范:Dart没有let关键字,且你定义的toForm不是编译期常量 - 实例属性
texts.toForm[*]是运行时才能解析的值,不符合const参数的要求
解决方案
方案1:修正常量定义+保留const修饰(性能最优)
首先将Texts类的toForm定义为静态编译期常量,无需实例化即可通过类名直接访问:
class Texts{ // static const声明的列表属于编译期常量 static const List<String> toForm = ['Enter Your Name', 'John Fernando', 'This is a Helper Text']; }
修改TextFormField代码,直接用类名访问常量列表元素,可保留const修饰:
TextFormField( cursorRadius: Radius.circular(26), cursorColor: Colors.green, onChanged: onTextInChange, textInputAction: TextInputAction.search, decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: Texts.toForm[0], hintText: Texts.toForm[1], helperText: Texts.toForm[2], labelStyle: TextStyle(fontSize: 18), hintStyle: TextStyle(fontSize: 18), ), )
方案2:去掉InputDecoration的const修饰(灵活度最高)
如果你确实需要通过实例化的texts对象获取值,直接删掉InputDecoration前面的const关键字即可,无需强制使用常量参数。
对应Texts类修正为Dart语法的实例属性写法:
class Texts{ final List<String> toForm = ['Enter Your Name', 'John Fernando', 'This is a Helper Text']; }
修改后的TextFormField代码:
TextFormField( cursorRadius: Radius.circular(26), cursorColor: Colors.green, onChanged: onTextInChange, textInputAction: TextInputAction.search, // 去掉const修饰符 decoration: InputDecoration( border: UnderlineInputBorder(), labelText: texts.toForm[0], hintText: texts.toForm[1], helperText: texts.toForm[2], labelStyle: TextStyle(fontSize: 18), hintStyle: TextStyle(fontSize: 18), ), )
内容的提问来源于stack exchange,提问作者nimsara-c
相关产品推荐
相关产品推荐

