Reputation: 81
i want to obtain text value from these dynamic 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
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
Upvotes: 2
Views: 6703
Reputation: 3469
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();
}
}
Upvotes: 8