我想在列中添加一個文本部件,其值應該是用戶輸入的TextFormField的輸入值。
代碼
String text;
欄目(
children: <Widget>[
填充(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10) 。
孩子。TextFormField(
onFieldSubmitted: (value) {
text= value;
},
),
Text(text), //要在這里添加文本。
]
它拋出一個錯誤:
必須向Text widget提供一個非空的字串。
什么才是好的方法呢?
uj5u.com熱心網友回復:
首先使文本為空,如 String? text;
根據statefullWidget里面的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) 。
孩子。TextFormField(
onFieldSubmitted: (value) {
setState(() {
文本=值。
});
},
),
),
if (text != null) Text(text!), //want to add text here)
]);
}
在你的案例中,它能解決嗎?
uj5u.com熱心網友回復:
因為你在初始化 "String text "變數時沒有分配任何值,而且Text widget不能接受空字串,你可能需要像這樣初始化文本
String text = "";
或者像這樣在文本部件中的字串上放置或空檢查
Text(text??"")。
或者另外,你可以像這樣使用null-safety
。String? text。
你的最終代碼將像
一樣String text = "" ;
欄目(
children: <Widget>[
padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10) 。
孩子。TextFormField(
onFieldSubmitted: (value) {
setState((){
text= value。
});
},
),
Text(text??""), // placed null check。
]
uj5u.com熱心網友回復:
更新你的代碼:
String? text;
欄目(
children: <Widget>[
padding(
padding: const EdgeInsets.fromLTRB(30, 10, 30, 10) 。
孩子。TextFormField(
onFieldSubmitted: (value) {
text = value;
},
),
Text(text), //要在這里添加文本。
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313092.html
標籤:
