[英]TextField do not pass data to another flutter Widget in same class
這里我們有無狀態的 AddTaskScreen 小部件,在小部件樹中,我們有一個 TextField 來獲取數據並將其傳遞給另一個小部件。即傳遞給 FlatButton 小部件的 onPressed 屬性。
這是問題:在 TextField 中鍵入內容時,其回調工作正常並正確打印值,但是當按下 FlatButton 時,它傳遞空數據而不是 TextField 的值,實際上它沒有將 TextField 的值存儲在 newTaskTitle 變量中以將其傳遞給 Flat按鈕。
感謝您的支持,您能幫我找出問題嗎?
class AddTaskScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
String newTaskTitle;//Here i declare newTasktitle to store value of TextField
return Container(
color: Color(0xff757575),
child: Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(30),topLeft: Radius.circular(30))
),
child: Column(
children: [
TextField(
onChanged: (textValue){
newTaskTitle = textValue;
print(newTaskTitle);//works fine at this step
},
),
SizedBox(height: 15),
FlatButton(
child: Text('add',style: TextStyle(color: Colors.white),),
onPressed:(){
print(newTaskTitle);//result: null
//here we get null as newTaskTitle value,why?
Provider.of<TaskData>(context,listen: false).addTask(newTaskTitle);
Navigator.pop(context);
},
),
],
),
),
);
}
}
在這種情況下,您應該使用 Stateful 小部件來保存 textField 值。 您需要使用 setState({}) 來更新此值。
我建議您使用TextEditingController
更容易使用,以下是您的使用方法:
聲明你的TextEditingController
:
final TextEditingController _txtTask = TextEditingController();
把它放在你的 TextField 中:
TextField(
controller: _txtTask,
),
這就是你獲得價值的方式
_txtTask.text
不需要在onChanged里面放任何函數,直接像_txtTask.text
一樣使用就可以獲取值。 和改變狀態的所有工作都需要將您的類更改為StatefulWidget
。 我希望這是有幫助的,它可能不是你想要的,但這是最好的解決方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.