[英]TextField do not pass data to another flutter Widget in same class
Here we have stateless AddTaskScreen widget, inside widget tree we have a TextField to get data and pass it over to another widget.Namely to pass it to the onPressed property of FlatButton widget.这里我们有无状态的 AddTaskScreen 小部件,在小部件树中,我们有一个 TextField 来获取数据并将其传递给另一个小部件。即传递给 FlatButton 小部件的 onPressed 属性。
Here is problem: when typing something in TextField its callback works fine and print value correctly, but when press FlatButton it pass over a null data instead of value of TextField, actually it did not store value of TextField in newTaskTitle variable to pass it to Flat button.这是问题:在 TextField 中键入内容时,其回调工作正常并正确打印值,但是当按下 FlatButton 时,它传递空数据而不是 TextField 的值,实际上它没有将 TextField 的值存储在 newTaskTitle 变量中以将其传递给 Flat按钮。
Thank for your support, can you help me find out the problem?感谢您的支持,您能帮我找出问题吗?
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);
},
),
],
),
),
);
}
}
In this case you should use Stateful widget for save textField value.在这种情况下,您应该使用 Stateful 小部件来保存 textField 值。 You need to use setState({}) for update this value.
您需要使用 setState({}) 来更新此值。
I suggest you use TextEditingController
for more easy use, here's how you use it:我建议您使用
TextEditingController
更容易使用,以下是您的使用方法:
Declare your TextEditingController
:声明你的
TextEditingController
:
final TextEditingController _txtTask = TextEditingController();
Put it inside your TextField:把它放在你的 TextField 中:
TextField(
controller: _txtTask,
),
This is how you get the value这就是你获得价值的方式
_txtTask.text
No need to put any function such onChanged, just use it like this _txtTask.text
to get the value.不需要在onChanged里面放任何函数,直接像
_txtTask.text
一样使用就可以获取值。 And everything that work with changing state you need to change your class to StatefulWidget
.和改变状态的所有工作都需要将您的类更改为
StatefulWidget
。 I hope this is helpful, it might not as you wanted but this is the best workaround.我希望这是有帮助的,它可能不是你想要的,但这是最好的解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.