[英]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.