[英]how to add TextEditingController and obtain text value from dynamic TextFormField in Flutter?
i want to obtain text value from these dynamic TextFormField我想从这些动态 TextFormField 中获取文本值
class MyPets extends StatefulWidget {
@override
_MyPetsState createState() => _MyPetsState();
}
class _MyPetsState extends State<MyPets> {
List<Widget> _children = [];
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
actions: <Widget>[IconButton(icon: Icon(Icons.add), onPressed: _add)],
),
body: ListView(children: _children),
);
}
void _add() {
TextEditingController controller = TextEditingController();
controllers.add(controller); //adding the current controller to the list
for (int i = 0; i < controllers.length; i++) {
print(
controllers[i].text); //printing the values to show that it's working
}
_children = List.from(_children)
..add(
TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: "This is TextField $_count",
icon: IconButton(icon: Icon(Icons.remove_circle), onPressed: rem),
),
),
);
setState(() => ++_count);
}
rem() {
setState(() {
_children.removeAt(_count);
controllers.removeAt(_count);
});
}
@override
void dispose() {
controllers.clear();
super.dispose();
}
}
problem is i don't know how to pass TextEditingController to this form-field in flutter i got above solution from this stack overflow answer问题是我不知道如何将 TextEditingController 传递给 flutter 中的这个表单字段我从这个堆栈溢出答案中得到了上述解决方案
basically i want textfields and when i tap a button textfield must increment and i want the value from each textfield and also i should able to delete the respective fields基本上我想要文本字段,当我点击按钮时,文本字段必须增加,我想要每个文本字段的值,而且我应该能够删除相应的字段
please help me thank in advance请帮我提前谢谢
You can dynamically take the value of all these fields adding the controllers to a list:您可以动态获取所有这些字段的值,将控制器添加到列表中:
class _MyPetsState extends State<MyPets> {
List<Widget> _children = [];
List<TextEditingController> controllers = []; //the controllers list
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
actions: <Widget>[IconButton(icon: Icon(Icons.add), onPressed: _add)],
),
body: ListView(children: _children),
);
}
void _add() {
TextEditingController controller = TextEditingController();
controllers.add(controller); //adding the current controller to the list
for(int i = 0; i < controllers.length; i++){
print(controllers[i].text); //printing the values to show that it's working
}
_children = List.from(_children)
..add(TextFormField(
controller: controller,
decoration: InputDecoration(hintText: "This is TextField $_count"),
));
setState(() => ++_count);
}
@override
void dispose() {
controllers.clear();
super.dispose();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.