I have a parameter n, and i have to create n textfields and listen to them, and capture the value of all these fields. Say I have to perform calculations on them. How do I achieve this? I tried to combine loops with widgets but I get lots of errors.
When I used a separate function to return a list of widgets for column's children property, it throws an error stating type int is not a subtype of type string of source
.
generate a list from your d
parameter and then generate a list of text field and text editing contotlers from that list
createTexttextfields (int d){
var textEditingControllers = <TextEditingController>[];
var textFields = <TextField>[];
var list = new List<int>.generate(d, (i) =>i + 1 );
print(list);
list.forEach((i) {
var textEditingController = new TextEditingController(text: "test $i");
textEditingControllers.add(textEditingController);
return textFields.add(new TextField(controller: textEditingController));
});
return textFields;
}
and then use this function in the children property of your widget for example the column widget
return new Scaffold(
appBar: new AppBar(),
body: new Column(
children: createTexttextfields(6),
),
);
But if you want to access them you can't do that by a function you must create them as variables
Widget build(BuildContext context) {
var d=5;//the number of text fields
var textEditingControllers = <TextEditingController>[];
var textFields = <TextField>[];
var list = new List<int>.generate(d, (i) =>i + 1 );
list.forEach((i) {
var textEditingController = new TextEditingController(text: "test $i");
textEditingControllers.add(textEditingController);
return textFields.add(new TextField(controller: textEditingController));
});
return new Scaffold(
appBar: new AppBar(),
body: new Column(
children: textFields),
floatingActionButton: new FloatingActionButton(
onPressed: (){
//clear the text in the second TextEditingController
textEditingControllers[1].clear();
} ,
),
);
}
}
Full Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With