我正在尝试创建一个新的TextInput
小部件来自定义TextFormField
,但我无法自定义labelText
。我需要为我的TextFormField
发送构造函数labelText
并显示此字符串。
class TextInput extends StatelessWidget {
final TextEditingController textControler;
final String textLabelHint;
const TextInput({Key? key, required this.textControler,required this.textLabelHint}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: TextFormField(
controller: textControler,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: textLabelHint,
),
),
);
}
}
但我有问题:
labelText: textLabelHint, //Invalid constant value.
您需要从decoration: const InputDecoration(...)
中删除const
,因为textLabelHint
不是const
值:
class TextInput extends StatelessWidget {
final TextEditingController textControler;
final String textLabelHint;
const TextInput(
{Key? key, required this.textControler, required this.textLabelHint})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: TextFormField(
controller: textControler,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: textLabelHint,
),
),
);
}
}
之所以出现此错误,是因为textLabelHint
是一个最终类属性(而非常量(,它可能会根据构造函数值进行更改。但是,尝试传递此值的位置是InputDecoration
,您已将其标记为const
。因此,错误表明。
要解决此问题,请删除InputDecoration
:之前的const
关键字
class TextInput extends StatelessWidget {
final TextEditingController textControler;
final String textLabelHint;
const TextInput({Key? key, required this.textControler,required this.textLabelHint}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: TextFormField(
controller: textControler,
decoration: InputDecoration( // <-- Notice the removed const
border: OutlineInputBorder(),
labelText: textLabelHint,
),
),
);
试试这个:
class TextInput extends StatelessWidget {
final TextEditingController textControler;
final String textLabelHint;
const TextInput(
{Key? key, required this.textControler, required this.textLabelHint})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: TextFormField(
controller: textControler,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: textLabelHint,
),
),
);
}
}