gpt4 book ai didi

flutter - 如何在Flutter中添加TextEditingController并从动态TextFormField中获取文本值?

转载 作者:行者123 更新时间:2023-12-01 21:41:31 25 4
gpt4 key购买 nike

我想从这些动态 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();
}
}

问题是我不知道如何在 flutter 中将 TextEditingController 传递给这个表单字段我从 this stack overflow answer 得到了上述解决方案

基本上我想要文本字段,当我点击一个按钮时,文本字段必须递增我想要每个文本字段的值,而且我应该能够删除相应的字段

请帮帮我提前致谢

最佳答案

您可以动态获取所有这些字段的值,将 Controller 添加到列表中:

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();
}

}

关于flutter - 如何在Flutter中添加TextEditingController并从动态TextFormField中获取文本值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61306150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com