我想在列中添加一个文本小部件,该值应该是用户输入的TextFormField的输入值。
String text;
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
child: TextFormField(
onFieldSubmitted: (value) {
text= value;
},
),
Text(text), // want to add text here
]
抛出错误:
必须为Text小部件提供非空字符串。
应该怎么做才好呢?
首先让String? text;
为空文本根据statfullwidget内部的Submit进行更改。
onFieldSubmitted: (value) {
setState(() {
text = value;
});
},
其次,您需要处理像
这样的空值if (text != null) Text(text!),
或类似Text(text ?? "defaul value"),
Widget将像
String? text;
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
child: TextFormField(
onFieldSubmitted: (value) {
setState(() {
text = value;
});
},
),
),
if (text != null) Text(text!), // want to add text here
]);
}
能解决你的问题吗?
因为在初始化"String " text"变量和Text小部件不能接受空字符串,您可能需要像这样初始化文本
String text = "";
或对文本小部件中的字符串进行place或null检查,如
Text(text??""),
或者,您还可以像这样使用空安全符
String? text;
你的最终代码将像
String text = "";
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
child: TextFormField(
onFieldSubmitted: (value) {
setState((){
text= value;
});
},
),
Text(text??""), // placed null check
]
更新代码:
String? text;
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
child: TextFormField(
onFieldSubmitted: (value) {
text = value;
},
),
Text(text), // want to add text here
]
感谢https://github.com/lgjenero提供的很酷的技巧-根据没有setState
的TextField状态更新小部件。
child: AnimatedBuilder(
animation: _textEditController,
builder: (context, child) {
return Text(
'Create',
style: _textEditController.text.isEmpty ? styleOne : styleTwo,
);
},
),